<template>
  <div class="page-container">
    <!-- 用户列表 -->
    <n-card class="user-list-card" size="small">
      <!-- 搜索表单 -->
      <div class="search-form">
        <n-form inline :model="searchForm" label-placement="left">
          <n-form-item label="用户名">
            <n-input v-model:value="searchForm.username" placeholder="请输入用户名" clearable />
          </n-form-item>
          <n-form-item>
            <n-space>
              <n-button type="primary" @click="handleSearch">
                <template #icon><n-icon><SearchOutline /></n-icon></template>
                搜索
              </n-button>
              <n-button @click="handleReset">
                <template #icon><n-icon><RefreshOutline /></n-icon></template>
                重置
              </n-button>
            </n-space>
          </n-form-item>
        </n-form>
      </div>
      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :row-key="(row: SysUser) => row.id"
        v-model:checked-row-keys="checkedRowKeys"
        remote
      />

      <div class="pagination-container" style="display: flex; justify-content: flex-end; margin-top: 12px">
        <n-pagination
          v-model:page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :item-count="pagination.itemCount"
          :page-sizes="[10, 20, 50, 100]"
          show-size-picker
          show-quick-jumper
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        >
          <template #prefix>
            共 {{ pagination.itemCount }} 条
          </template>
        </n-pagination>
      </div>
    </n-card>
    <!-- 新增/编辑弹窗 -->
    <!-- 导入弹窗 -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, onMounted, } from 'vue'
import { useRoute } from 'vue-router'
import { NButton, NTag, NSelect, NSpace, NPagination,  useMessage, type DataTableColumns  } from 'naive-ui'
import { SearchOutline, RefreshOutline } from '@vicons/ionicons5'
import { userApi,   type SysUser,  } from '@/api/system'
import { deptApi, type SysDept } from '@/api/org'
import { useUserStore } from '@/stores/user'
import { dictDataApi } from '@/api/org'

const message = useMessage()
const userStore = useUserStore()
const route = useRoute()

// 权限检查
const hasPermission = (permission: string) => userStore.hasPermission(permission)

// ==================== 部门选择 ====================
const deptOptions = ref<SysDept[]>([])
const assetsStateOptions = ref<{ label: string; value: any }[]>([])

const selectedDeptId = ref<number | undefined>(undefined)

// 加载部门树（用于下拉选择）
async function loadDeptOptions() {
  try {
    const tree = await deptApi.deptTree()
    deptOptions.value = tree
  } catch (error) {
    // 错误已在拦截器处理
  }

  try {
    const data = await dictDataApi.listByType('assets_state')
    assetsStateOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue) }))
  } catch {}
}

// ==================== 搜索表单 ====================
const searchForm = reactive({
  username: '',
  status: null as number | null,
  userType: null as string | null
})

const defaultFormData: SysUser = {
  id: null,
  deptId: null,
  deptName: '',
  username: '',
  password: '',
  nickname: '',
  avatar: '',
  email: '',
  phone: '',
  gender: null,
  status: 0,
  assetsState: 0,
  bankCard: '',
  bankOpenName: '',
  remark: '',
  userType: '', // 用户类型: admin-后台管理员 pc-PC前台用户 app-App/小程序用户
  openId: '',   // 微信openId
  isQuit: null ,    // 是否离职(0-否 1-是)
  postNames: '', // 岗位名称列表
  createTime: ''
}
const formData = reactive<SysUser>({ ...defaultFormData })

// ==================== 表格 ====================
const tableData = ref<SysUser[]>([])
const loading = ref(false)
const checkedRowKeys = ref<number[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0
})


const columns: DataTableColumns<SysUser> = [
  { type: 'selection' },
  { title: '用户名', key: 'username', width: 100 },
  { title: '昵称', key: 'nickname', width: 100 },
  { title: '姓名', key: 'name', width: 100 },
  { title: '手机号', key: 'phone', width: 120 , render(row) {
      return row.phone || '-'
    }
  },
  { title: '银行卡号', key: 'bankCard' },
  { title: '开户行名称', key: 'bankOpenName' },
  { title: '资产人资图片', key: 'assetsUrl' ,
     render(row) {
      return row.assetsUrl ? h('img', { 
        src: row.assetsUrl, 
        style: { width: '60px', height: '60px', objectFit: 'cover', borderRadius: '4px' },
        onClick:() => clickPhoto(row.assetsUrl) 
      }) : '-'
    }
  },
  { title: '资产审核结果', key: 'assetsState', 
    render(row) {
      return h(NSelect,{
      // 绑定当前行的status值（双向绑定核心）
        value: row.assetsState,
        // 选中值变化时，更新当前行数据
        'onUpdate:value': (val) => {
          row.assetsState = val
          //可在这里触发接口保存、校验等逻辑
          Object.assign(formData, row)
          handleSubmit();
        },
        options: assetsStateOptions.value, // 绑定下拉选项
        disabled: row.assetsState !== 3 || !hasPermission("biz:user:audit")
      })
    }
  },
  // {
  //   title: '状态',
  //   key: 'status',
  //   width: 80,
  //   render(row) {
  //     const statusMap: Record<number, { type: 'success' | 'error' | 'warning' | 'info'; label: string }> = {
  //       0: { type: 'error', label: '禁用' },
  //       1: { type: 'success', label: '启用' },
  //       2: { type: 'warning', label: '待审核' },
  //       3: { type: 'error', label: '审核拒绝' }
  //     }
  //     const status = statusMap[row.status] || { type: 'info', label: '未知' }
  //     return h(NTag, { type: status.type, size: 'small' }, { default: () => status.label })
  //   }
  // },
  { title: '注册时间', key: 'createTime', width: 170 }
]

// ==================== 数据加载 ====================
async function loadData() {
  loading.value = true
  try {
    const res = await userApi.page({
      page: pagination.page,
      pageSize: pagination.pageSize,
      username: searchForm.username || undefined,
      status: searchForm.status ?? undefined,
      userType: searchForm.userType || undefined,
      deptId: selectedDeptId.value
    })
    tableData.value = res.list
    pagination.itemCount = Number(res.total)
    console.log('Pagination updated:', pagination.itemCount)
  } catch (error) {
    // 错误已在拦截器处理
  } finally {
    loading.value = false
  }
}

function clickPhoto(photoUrl: string){
  console.log(photoUrl)
}

// ==================== 操作方法 ====================
function handleSearch() {
  pagination.page = 1
  loadData()
}

function handleReset() {
  searchForm.username = ''
  searchForm.status = null
  // searchForm.userType = null
  selectedDeptId.value = undefined
  handleSearch()
}

function handlePageChange(page: number) {
  pagination.page = page
  loadData()
}

function handlePageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize
  pagination.page = 1
  loadData()
}



async function handleSubmit() {

  try {
    const submitData = { ...formData } as SysUser
    if (submitData.id) {
      await userApi.update1(submitData)
      message.success('修改成功')
    } 
    loadData()
  } catch (error) {
    // 错误已在拦截器处理
  }
}


onMounted(() => {
  const deptId = route.query.deptId
  if (deptId) {
    selectedDeptId.value = Number(deptId)
  }
  
  const userTypeVal = Array.isArray(route.query.userType) 
    ? route.query.userType[0]  // 数组取第一个值
    : route.query.userType

  searchForm.userType = userTypeVal ?? null  // 空值转为null，匹配类型

  loadDeptOptions()
  loadData()
})
</script>

<style scoped>

</style>
