<template>
  <div class="page-container">
    <n-card>
      <!-- 搜索表单 -->
      <div class="search-form">
        <n-form inline :model="searchForm" label-placement="left">
          <n-form-item label="id">
            <n-input v-model:value="searchForm.id" placeholder="请输入id" clearable />
          </n-form-item>
          <n-form-item label="名称">
            <n-input v-model:value="searchForm.name" placeholder="请输入名称" clearable />
          </n-form-item>
          <n-form-item label="状态">
            <n-select v-model:value="searchForm.status" placeholder="请选择状态" clearable style="width: 150px" :options="statusOptions" />
          </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>

      <!-- 工具栏 -->
      <!-- <div class="table-toolbar">
        <n-space>
          <n-button type="primary" @click="handleAdd">
            <template #icon><n-icon><AddOutline /></n-icon></template>
            新增
          </n-button>
          <n-button @click="importModalVisible = true">
            <template #icon><n-icon><CloudUploadOutline /></n-icon></template>
            导入
          </n-button>
          <n-button @click="handleExport">
            <template #icon><n-icon><DownloadOutline /></n-icon></template>
            导出{{ selectedIds.length > 0 ? `(${selectedIds.length})` : '' }}
          </n-button>
          <n-button type="error" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
            <template #icon><n-icon><TrashOutline /></n-icon></template>
            删除
          </n-button>
        </n-space>
      </div> -->

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-key="(row) => row.id"
        :scroll-x="1200"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
        @update:checked-row-keys="handleCheck"
      />
    </n-card>

    <!-- 新增/编辑弹窗 -->
    <!-- <n-modal v-model:show="modalVisible" preset="card" :title="modalTitle" style="width: 600px">
      <n-form ref="formRef" :model="formData" :rules="formRules" label-placement="left" label-width="100px">
        <n-form-item label="微信id" path="wuid">
          <n-input v-model:value="formData.wuid" placeholder="请输入微信id" />
        </n-form-item>
        <n-form-item label="openid" path="openid">
          <n-input v-model:value="formData.openid" placeholder="请输入openid" />
        </n-form-item>
        <n-form-item label="微信唯一id" path="unionid">
          <n-input v-model:value="formData.unionid" placeholder="请输入微信唯一id" />
        </n-form-item>
        <n-form-item label="手机号" path="phone">
          <n-input v-model:value="formData.phone" placeholder="请输入手机号" />
        </n-form-item>
        <n-form-item label="微信昵称" path="nickName">
          <n-input v-model:value="formData.nickName" placeholder="请输入微信昵称" />
        </n-form-item>
        <n-form-item label="用户头像" path="avatarUrl">
          <ImageUpload v-model="formData.avatarUrl" />
        </n-form-item>
        <n-form-item label="名称" path="name">
          <n-input v-model:value="formData.name" placeholder="请输入名称" />
        </n-form-item>
        <n-form-item label="用户性别：1-男；2-女
" path="gender">
          <n-select v-model:value="formData.gender" placeholder="请选择用户性别：1-男；2-女
" :options="genderOptions" />
        </n-form-item>
        <n-form-item label="公众号原始ID" path="gzhId">
          <n-input v-model:value="formData.gzhId" placeholder="请输入公众号原始ID" />
        </n-form-item>
        <n-form-item label="公众号openid" path="gzhOpenid">
          <n-input v-model:value="formData.gzhOpenid" placeholder="请输入公众号openid" />
        </n-form-item>
        <n-form-item label="资产人资图片" path="assetsUrl">
          <n-input v-model:value="formData.assetsUrl" placeholder="请输入资产人资图片" />
        </n-form-item>
        <n-form-item label="资产审核结果, 1 通过  2,未通过" path="assetsState">
          <n-input v-model:value="formData.assetsState" placeholder="请输入资产审核结果, 1 通过  2,未通过" />
        </n-form-item>
        <n-form-item label="银行卡号" path="bankCard">
          <n-input v-model:value="formData.bankCard" placeholder="请输入银行卡号" />
        </n-form-item>
        <n-form-item label="开户行名称" path="bankOpenName">
          <n-input v-model:value="formData.bankOpenName" placeholder="请输入开户行名称" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-select v-model:value="formData.status" placeholder="请选择状态" :options="statusOptions" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="modalVisible = false">取消</n-button>
          <n-button type="primary" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal> -->

    <!-- 导入弹窗 -->
    <!-- <n-modal v-model:show="importModalVisible" preset="card" title="导入User" style="width: 500px">
      <n-space vertical>
        <n-alert type="info">
          <template #header>导入说明</template>
          <ul style="margin: 0; padding-left: 16px; line-height: 1.8">
            <li>请先下载导入模板，按模板格式填写数据</li>
            <li>支持 .xlsx 或 .xls 格式</li>
          </ul>
        </n-alert>
        <n-space>
          <n-button type="primary" @click="handleDownloadTemplate">
            <template #icon><n-icon><DownloadOutline /></n-icon></template>
            下载模板
          </n-button>
        </n-space>
        <n-upload :max="1" accept=".xlsx,.xls" :show-file-list="true" :custom-request="handleImportUpload">
          <n-upload-dragger>
            <div style="margin-bottom: 12px">
              <n-icon size="48" :depth="3"><CloudUploadOutline /></n-icon>
            </div>
            <n-text style="font-size: 16px">点击或拖拽文件到此处上传</n-text>
            <n-p depth="3" style="margin: 8px 0 0 0">支持 .xlsx 或 .xls 格式</n-p>
          </n-upload-dragger>
        </n-upload>
      </n-space>
      <template #footer>
        <n-button @click="importModalVisible = false">关闭</n-button>
      </template>
    </n-modal> -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, onMounted } from 'vue'
import { NButton, NSpace, NIcon, useMessage, useDialog, type DataTableColumns, type UploadCustomRequestOptions } from 'naive-ui'
import { SearchOutline, RefreshOutline, TrashOutline } from '@vicons/ionicons5'
import { userApi, type User } from '@/api/user'
import { dictDataApi } from '@/api/org'

const message = useMessage()
const dialog = useDialog()

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

// 表格数据
const tableData = ref<User[]>([])
const loading = ref(false)
const selectedIds = ref<number[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})

// 弹窗
const modalVisible = ref(false)
const modalTitle = ref('')
const importModalVisible = ref(false)
const formRef = ref()
const defaultFormData: User = {
  wuid: '',
  openid: '',
  unionid: '',
  phone: '',
  nickName: '',
  avatarUrl: '',
  name: '',
  gender: undefined,
  gzhId: '',
  gzhOpenid: '',
  assetsUrl: '',
  assetsState: undefined,
  bankCard: '',
  bankOpenName: '',
  status: undefined,
}
const formData = reactive<User>({ ...defaultFormData })

// 字典选项（下拉框/单选框/复选框关联字典时使用）
const genderOptions = ref<{ label: string; value: any }[]>([])
const statusOptions = ref<{ label: string; value: any }[]>([])
const assetsStateOptions = ref<{ label: string; value: any }[]>([])


// 表单校验规则
const formRules = {
}

// 表格列
const columns: DataTableColumns<User> = [
  { title: '微信id', key: 'wuid' },
  // { title: 'openid', key: 'openid' },
  // { title: '微信唯一id', key: 'unionid' },
  { title: '手机号', key: 'phone' },
  { title: '微信昵称', key: 'nickName' },
  { 
    title: '用户头像', 
    key: 'avatarUrl',
    width: 100,
    render(row) {
      return row.avatarUrl ? h('img', { 
        src: row.avatarUrl, 
        style: { width: '60px', height: '60px', objectFit: 'cover', borderRadius: '4px' } 
      }) : '-'
    }
  },
  { title: '名称', key: 'name' },
  { title: '用户性别', key: 'gender',
    render(row) {
      const val = row.gender
      const opt = genderOptions.value.find(o => o.value === val || String(o.value) === String(val))
      return opt ? opt.label : (val ?? '-')
    }
  },
  // { title: '公众号原始ID', key: 'gzhId' },
  // { title: '公众号openid', key: 'gzhOpenid' },
  { title: '资产人资图片', key: 'assetsUrl' },
  { title: '资产审核结果', key: 'assetsState' ,
    render(row) {
      const val = row.assetsState
      const opt = assetsStateOptions.value.find(o => o.value === val || String(o.value) === String(val))
      return opt ? opt.label : (val ?? '-')
    }
  },
  { title: '银行卡号', key: 'bankCard' },
  { title: '开户行名称', key: 'bankOpenName' },
  { title: '创建时间', key: 'createTime'  },
  { title: '修改时间', key: 'updateTime' },
  { title: '创建人', key: 'createBy' },
  { title: '更新人', key: 'updateBy' },
  { title: '状态', key: 'status',
    render(row) {
      const val = row.status
      const opt = statusOptions.value.find(o => o.value === val || String(o.value) === String(val))
      return opt ? opt.label : (val ?? '-')
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 140,
    fixed: 'right',
    render(row) {
      // if(row.assetsState === 0){
      //   return h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'nowrap' } }, [
      //     h(NButton, { size: 'small', quaternary: row.assetsState === '0', type: 'error', onClick: () => handleDelete(row) }, {
      //       default: () => [h(NIcon, null, { default: () => h(TrashOutline) }), ' 资产审核']
      //     })
      //   ])
      // }
    }
  }
]

// 加载数据
async function loadData() {
  loading.value = true
  try {
    const res = await userApi.page({
      page: pagination.page,
      pageSize: pagination.pageSize,
      id: searchForm.id || undefined,
      name: searchForm.name || undefined,
      status: searchForm.status || undefined,
    })
    tableData.value = res.list
    pagination.itemCount = res.total
  } finally {
    loading.value = false
  }
}

// 搜索
function handleSearch() {
  pagination.page = 1
  loadData()
}

// 重置
function handleReset() {
  searchForm.id =  null

  searchForm.name = ''

  searchForm.status =  null

  handleSearch()
}

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

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

// 选择
function handleCheck(keys: Array<string | number>) {
  selectedIds.value = keys as number[]
}

// 新增
function handleAdd() {
  modalTitle.value = '新增User'
  Object.assign(formData, defaultFormData)
  modalVisible.value = true
}

// 编辑
function handleEdit(row: User) {
  modalTitle.value = '编辑User'
  Object.assign(formData, row)
  if (formData.createTime && typeof formData.createTime === 'string') {
    formData.createTime = new Date(formData.createTime.replace(' ', 'T')).getTime()
  }
  if (formData.updateTime && typeof formData.updateTime === 'string') {
    formData.updateTime = new Date(formData.updateTime.replace(' ', 'T')).getTime()
  }
  modalVisible.value = true
}

// 提交
async function handleSubmit() {
  await formRef.value?.validate()
  try {
    const submitData = { ...formData } as User
    submitData.avatarUrl = formData.avatarUrl ?? ''
    if (typeof submitData.createTime === 'number') {
      submitData.createTime = new Date(submitData.createTime).toISOString().slice(0, 19).replace('T', ' ')
    }
    if (typeof submitData.updateTime === 'number') {
      submitData.updateTime = new Date(submitData.updateTime).toISOString().slice(0, 19).replace('T', ' ')
    }
    if (submitData.id) {
      await userApi.update(submitData)
      message.success('修改成功')
    } else {
      await userApi.create(submitData)
      message.success('新增成功')
    }
    modalVisible.value = false
    loadData()
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 删除
function handleDelete(row: User) {
  dialog.warning({
    title: '提示',
    content: '确定要删除该记录吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await userApi.delete([row.id!])
        message.success('删除成功')
        loadData()
      } catch (error) {
        // 错误已在拦截器处理
      }
    }
  })
}

// 批量删除
function handleBatchDelete() {
  dialog.warning({
    title: '提示',
    content: `确定要删除选中的 ${selectedIds.value.length} 条记录吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await userApi.delete(selectedIds.value)
        message.success('删除成功')
        selectedIds.value = []
        loadData()
      } catch (error) {
        // 错误已在拦截器处理
      }
    }
  })
}

// 导出
async function handleExport() {
  try {
    const params: Record<string, any> = {}
    if (selectedIds.value.length > 0) params.ids = selectedIds.value
    if (searchForm.id != null) params.id = searchForm.id
    if (searchForm.name) params.name = searchForm.name
    if (searchForm.status != null) params.status = searchForm.status
    const blob = await userApi.export(params)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'User数据.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 下载导入模板
async function handleDownloadTemplate() {
  try {
    const blob = await userApi.downloadTemplate()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'User导入模板.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 导入上传
async function handleImportUpload({ file }: UploadCustomRequestOptions) {
  if (!file.file) return
  try {
    const result = await userApi.importData(file.file)
    if (result.fail > 0) {
      dialog.warning({
        title: '导入结果',
        content: `成功: ${result.success} 条，失败: ${result.fail} 条\n错误信息: ${(result.errors || []).join('\n') || '无'}`,
        positiveText: '确定'
      })
    } else {
      message.success(`导入成功，共 ${result.success} 条数据`)
      importModalVisible.value = false
    }
    loadData()
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 加载字典选项
async function loadDictOptions() {
  try {
    const data = await dictDataApi.listByType('gender')
    genderOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue) }))
  } catch {}
  try {
    const data = await dictDataApi.listByType('sys_status')
    statusOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue) }))
  } catch {}
  try {
    const data = await dictDataApi.listByType('assets_state')
    assetsStateOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue) }))
  } catch {}
}

onMounted(() => {
  loadData()
  loadDictOptions()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}

.table-toolbar {
  margin-bottom: 16px;
}
</style>
