<template>
  <div class="page-container">

    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">用户管理</span>
          <div class="header-actions">
            <el-cascader v-model="searchRegionValue" :options="areaCascaderOptions"
              :props="{ value: 'id', label: 'name' }" placeholder="所属站点" style="width: 350px; margin-right: 10px"
              clearable @change="handleSearchRegionChange" />
            <el-input v-model="searchForm.keyword" placeholder="搜索姓名/手机号" style="width: 200px; margin-right: 10px;"
              clearable @keyup.enter="handleSearch" @clear="handleSearch" />
            <el-button type="primary" icon="Plus" @click="handleAdd"
              v-hasPermi="['archieves:customer:add']">新增用户</el-button>
          </div>
        </div>
      </template>

      <el-table :data="tableData" v-loading="loading" style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }">
        <el-table-column label="用户基本信息" width="250">
          <template #default="scope">
            <div style="display: flex; align-items: center;">
              <el-avatar :size="40" :src="scope.row.avatarUrl" style="margin-right: 10px;" />
              <div>
                <div style="font-weight: bold;">{{ scope.row.name }}
                  <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
                </div>
                <div style="font-size: 12px; color: #999;">{{ scope.row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="住址" show-overflow-tooltip min-width="150">
          <template #default="scope">
            {{[scope.row.regionCode ? scope.row.regionCode.split('/').map(c => codeToName(c)).filter(Boolean).join(' ')
              : '', scope.row.address].filter(Boolean).join(' ') || '-'}}
          </template>
        </el-table-column>
        <el-table-column label="用户标签" width="200">
          <template #default="scope">
            <el-tag v-for="tag in scope.row.tags" :key="tag.id" :type="tag.colorType || 'info'" effect="light"
              size="small" style="margin-right: 5px;">{{ tag.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单数量" width="120" align="center" sortable prop="orderCount">
          <template #default="scope">
            <div>{{ scope.row.orderCount }}单</div>
          </template>
        </el-table-column>
        <el-table-column prop="petCount" label="关联宠物" width="100" align="center">
          <template #default="scope">
            <el-tag size="small" round>{{ scope.row.petCount }}只</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" inline-prompt active-text="正常"
              inactive-text="停用" @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip min-width="150" />
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleDetail(scope.row)"
              v-hasPermi="['archieves:customer:query']">详情</el-button>
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)"
              v-hasPermi="['archieves:customer:edit']">编辑</el-button>
            <el-dropdown trigger="click" @command="(cmd) => handleCommand(cmd, scope.row)"
              style="margin-left: 10px; vertical-align: middle">
              <el-button link type="primary" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="remark" v-hasPermi="['archieves:customer:remark']">添加备注</el-dropdown-item>
                  <el-dropdown-item command="delete" style="color: #F56C6C"
                    v-hasPermi="['archieves:customer:remove']">删除用户</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="getList" @current-change="getList" />
      </div>
    </el-card>

    <!-- User Detail Drawer -->
    <CustomerDetailDrawer ref="customerDetailRef" v-model:visible="drawerVisible" :customer-id="currentCustomerId"
      editable @add-pet="openAddPet" @pet-detail="handlePetDetail" @pet-edit="handlePetEdit"
      @pet-remark="handlePetRemark" @pet-delete="handlePetDelete" />

    <!-- Pet Profile Drawer -->
    <pet-detail-drawer v-model:visible="petDrawerVisible" :pet-id="selectedPetId" editable @remark-saved="getList" />

    <!-- Add/Edit User Dialog -->
    <EditCustomerDialog v-model:visible="dialogVisible" :edit-data="customerEditData" @success="onCustomerSaved" />

    <!-- Remark Dialog -->
    <el-dialog v-model="remarkDialogVisible" title="添加备注" width="400px">
      <el-input v-model="remarkForm.content" type="textarea" :rows="3" placeholder="请输入备注内容..." />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="remarkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRemark">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <EditPetDialog v-model:visible="petDialogVisible" :user-id="currentUser.id"
      :user-options="currentUser.id ? [currentUser] : []" :pet-data="petEditData" :locked-owner="true"
      @success="onPetSaved" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listCustomer, getCustomer, delCustomer, changeCustomerStatus, updateCustomerRemark } from '@/api/archieves/customer'
import { listAllTag } from '@/api/archieves/tag'
import { listPetByUser, delPet, updatePetRemark } from '@/api/archieves/pet'
import { listAllChangeLog } from '@/api/archieves/changeLog'
import { listAreaStation } from '@/api/system/areaStation'
import { useRegionData } from '@/hooks/useRegionData'
import CustomerDetailDrawer from '@/components/CustomerDetailDrawer/index.vue'
import PetDetailDrawer from '@/components/PetDetailDrawer/index.vue'
import EditCustomerDialog from '@/components/EditCustomerDialog/index.vue'
import EditPetDialog from '@/components/EditPetDialog/index.vue'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()
const { codeToName, loadRegionData } = useRegionData()
const { proxy } = getCurrentInstance()
const { sys_user_sex, sys_customer_status, sys_house_type, sys_entry_method, sys_pet_gender, sys_pet_size, sys_pet_type } = toRefs(
  proxy?.useDict('sys_user_sex', 'sys_customer_status', 'sys_house_type', 'sys_entry_method', 'sys_pet_gender', 'sys_pet_size', 'sys_pet_type')
)

const loading = ref(false)
const total = ref(0)

const allNodes = ref([])
const searchRegionValue = ref([])

const areaCascaderOptions = computed(() => {
  const buildTree = (data, parentId) => {
    return data
      .filter(item => String(item.parentId) === String(parentId))
      .map(item => {
        const children = buildTree(data, item.id)
        const node = { id: item.id, name: item.name }
        if (children.length > 0) {
          node.children = children
        } else if (String(item.type) !== '2') {
          node.disabled = true
        }
        return node
      })
  }
  return buildTree(allNodes.value, 0)
})

const loadAreaStation = () => {
  listAreaStation().then((res) => {
    allNodes.value = res.data || []
  })
}

const handleSearchRegionChange = (value) => {
  if (value && value.length > 0) {
    const lastId = value[value.length - 1]
    const node = allNodes.value.find(n => String(n.id) === String(lastId))
    if (node && String(node.type) === '2') {
      searchForm.stationId = lastId
      searchForm.areaId = node.parentId
    } else {
      searchForm.areaId = lastId
      searchForm.stationId = undefined
    }
  } else {
    searchForm.areaId = undefined
    searchForm.stationId = undefined
  }
  handleSearch()
}

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  areaId: undefined,
  stationId: undefined,
  status: undefined
})

const searchForm = reactive({
  keyword: '',
  areaId: undefined,
  stationId: undefined
})

const dialogVisible = ref(false)
const drawerVisible = ref(false)
const remarkDialogVisible = ref(false)
const petDialogVisible = ref(false)

const currentUser = ref({})
const tableData = ref([])

const allUserTags = ref([])
const currentCustomerId = ref(null)
const customerDetailRef = ref(null)
const petDrawerVisible = ref(false)
const selectedPetId = ref(null)

const customerEditData = ref(null)
const petEditData = ref(null)

const remarkForm = reactive({ content: '' })

const getList = () => {
  loading.value = true
  queryParams.keyword = searchForm.keyword
  queryParams.areaId = searchForm.areaId || undefined
  queryParams.stationId = searchForm.stationId || undefined
  listCustomer(queryParams).then((res) => {
    tableData.value = res.rows
    total.value = res.total
  }).finally(() => {
    loading.value = false
  })
}

const handleSearch = () => {
  queryParams.pageNum = 1
  getList()
}

const loadTags = () => {
  listAllTag({ category: 'customer', status: 0 }).then((res) => {
    allUserTags.value = res.data || []
  }).catch(() => { })
}

const handleAdd = () => {
  customerEditData.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  customerEditData.value = row
  dialogVisible.value = true
}

const onCustomerSaved = () => {
  dialogVisible.value = false
  getList()
}

const handleDetail = (row) => {
  currentUser.value = row
  currentCustomerId.value = row.id
  drawerVisible.value = true
}

const remarkTargetType = ref('customer')

const handleRemark = (row) => {
  currentUser.value = row
  remarkTargetType.value = 'customer'
  remarkForm.content = row.remark || ''
  remarkDialogVisible.value = true
}

const saveRemark = () => {
  if (!remarkForm.content) return ElMessage.warning('请输入内容')

  if (remarkTargetType.value === 'customer') {
    const data = {
      id: currentUser.value.id,
      content: remarkForm.content
    }
    updateCustomerRemark(data).then(() => {
      ElMessage.success('备注添加成功')
      remarkDialogVisible.value = false
      getList()
    })
  } else {
    const data = {
      petId: currentUser.value.id,
      content: remarkForm.content
    }
    updatePetRemark(data).then(() => {
      ElMessage.success('宠物备注添加成功')
      remarkDialogVisible.value = false
      if (customerDetailRef.value) {
        customerDetailRef.value.refresh()
      }
      getList()
    })
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该用户档案吗?', '提示', { type: 'warning' }).then(() => {
    delCustomer(row.id).then(() => {
      ElMessage.success('删除成功')
      getList()
    })
  })
}

const handleStatusChange = (row) => {
  const statusText = row.status === 0 ? '启用' : '停用'
  ElMessageBox.confirm(`确认${statusText}用户 "${row.name}" 吗?`, '提示', { type: 'warning' }).then(() => {
    changeCustomerStatus(row.id, row.status).then(() => {
      ElMessage.success(`${statusText}成功`)
    })
  }).catch(() => {
    row.status = row.status === 0 ? 1 : 0
  })
}

const handleCommand = (command, row) => {
  if (command === 'remark') {
    handleRemark(row)
  } else if (command === 'delete') {
    handleDelete(row)
  }
}

const openAddPet = () => {
  petEditData.value = null
  petDialogVisible.value = true
}

const handlePetDetail = (row) => {
  selectedPetId.value = row.id
  petDrawerVisible.value = true
}

const handlePetEdit = (row) => {
  petEditData.value = row
  petDialogVisible.value = true
}

const handlePetRemark = (row) => {
  currentUser.value = row
  remarkTargetType.value = 'pet'
  remarkForm.content = row.remark || ''
  remarkDialogVisible.value = true
}

const handlePetDelete = (row) => {
  ElMessageBox.confirm(`确认删除宠物 [${row.name}] 吗?`, '提示', { type: 'warning' }).then(() => {
    delPet(row.id).then(() => {
      ElMessage.success('宠物删除成功')
      if (customerDetailRef.value) {
        customerDetailRef.value.refresh()
      }
      getList()
    })
  })
}

const onPetSaved = () => {
  petDialogVisible.value = false
  if (customerDetailRef.value) {
    customerDetailRef.value.refresh()
  }
  getList()
}

onMounted(() => {
  getList()
  loadTags()
  loadAreaStation()
  loadRegionData()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-weight: bold;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.profile-basic {
  margin-left: 20px;
}

.name-row {
  display: flex;
  align-items: center;
}

.name {
  font-size: 20px;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.upload-avatar {
  cursor: pointer;
}

.form-section-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  font-size: 14px;
  font-weight: bold;
  color: #409EFF;
  border-bottom: 1px solid #e4e7ed;
}

.user-form {
  padding: 10px;
}
</style>
