<template>
  <a-drawer
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :width="width >= 800 ? 800 : '100%'"
    @before-ok="save"
    @close="reset"
  >
    <GiForm ref="formRef" v-model="form" :columns="columns" />
  </a-drawer>
</template>

<script setup lang="ts">
import { Message, type TreeNodeData } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { addUserNew, getUserDetailNew, updateUserNew } from '@/apis/system/user-new'
import { type ColumnItem, GiForm } from '@/components/GiForm'
import type { Status } from '@/types/global'
import { useResetReactive } from '@/hooks'
import { useDept, useRole, usePost } from '@/hooks/app'
import { encryptByRsa } from '@/utils/encrypt'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改用户' : '新增用户'))
const formRef = ref<InstanceType<typeof GiForm>>()
const { roleList, getRoleList } = useRole()
const { deptList, getDeptList } = useDept()
const { postList, getPostList } = usePost()

const [form, resetForm] = useResetReactive({
  account: '',        // 账号
  name: '',           // 姓名
  password: '',
  mobile: '',         // 手机号
  email: '',
  gender: 'male',     // 性别
  deptId: '',         // 所属部门
  roleIds: [] as string[],        // 角色
  status: 1 as Status,
  avatar: '',         // 头像地址
  birthdate: '',      // 出生日期
  education: '',      // 学历
  hiredate: '',       // 入职日期
  identityCard: '',   // 身份证
  majorField: '',     // 专业
  postIds: [] as string[],        // 岗位
  userCode: '',       // 员工编码
  userStatus: '',     // 在职状态
  userType: '',       // 员工性质
  workField: '',      // 工作方向
})

const columns: ColumnItem[] = reactive([
  {
    label: '账号',
    field: 'account',
    type: 'input',
    span: 12,
    required: true,
    props: {
      maxLength: 64,
    },
  },
  {
    label: '姓名',
    field: 'name',
    type: 'input',
    span: 12,
    required: true,
    props: {
      maxLength: 30,
    },
  },
  {
    label: '密码',
    field: 'password',
    type: 'input-password',
    span: 12,
    required: !isUpdate.value,
    props: {
      maxLength: 32,
      showWordLimit: true,
    },
    hide: () => isUpdate.value,
  },
  {
    label: '手机号码',
    field: 'mobile',
    type: 'input',
    span: 12,
    props: {
      maxLength: 11,
    },
  },
  {
    label: '员工编码',
    field: 'userCode',
    type: 'input',
    span: 12,
    props: {
      maxLength: 20,
    },
  },
  {
    label: '邮箱',
    field: 'email',
    type: 'input',
    span: 12,
    props: {
      maxLength: 255,
    },
  },
  {
    label: '头像地址',
    field: 'avatar',
    type: 'input',
    span: 12,
    props: {
      placeholder: '头像图片URL',
    },
  },
  {
    label: '性别',
    field: 'gender',
    type: 'radio-group',
    span: 12,
    props: {
      options: [
        { label: '男', value: 'male' },
        { label: '女', value: 'female' },
      ],
    },
  },
  {
    label: '身份证',
    field: 'identityCard',
    type: 'input',
    span: 12,
    props: {
      maxLength: 18,
    },
  },
  {
    label: '所属部门',
    field: 'deptId',
    type: 'tree-select',
    span: 12,
    required: true,
    props: {
      data: deptList,
      allowClear: true,
      allowSearch: true,
      fallbackOption: false,
      filterTreeNode(searchKey: string, nodeData: TreeNodeData) {
        if (nodeData.title) {
          return nodeData.title.toLowerCase().includes(searchKey.toLowerCase())
        }
        return false
      },
    },
  },
  {
    label: '岗位',
    field: 'postIds',
    type: 'select',
    span: 12,
    props: {
      options: postList,
      multiple: true,
      allowClear: true,
      placeholder: '请选择岗位',
    },
  },
  {
    label: '角色',
    field: 'roleIds',
    type: 'select',
    span: 12,
    required: true,
    props: {
      options: roleList,
      multiple: true,
      allowClear: true,
      allowSearch: true,
    },
  },
  {
    label: '学历',
    field: 'education',
    type: 'select',
    span: 12,
    props: {
      options: [
        { label: '博士', value: 'PHD' },
        { label: '硕士', value: 'MASTER' },
        { label: '本科', value: 'BACHELOR' },
        { label: '大专', value: 'JUNIOR_COLLEGE' },
        { label: '高中', value: 'HIGH_SCHOOL' },
        { label: '其他', value: 'OTHER' }
      ],
    },
  },
  {
    label: '专业',
    field: 'majorField',
    type: 'input',
    span: 12,
    props: {
      maxLength: 50,
    },
  },
  {
    label: '工作方向',
    field: 'workField',
    type: 'input',
    span: 12,
    props: {
      maxLength: 50,
    },
  },
  {
    label: '入职日期',
    field: 'hiredate',
    type: 'date-picker',
    span: 12,
    props: {
      valueFormat: 'YYYY-MM-DD',
    },
  },
  {
    label: '出生日期',
    field: 'birthdate',
    type: 'date-picker',
    span: 12,
    props: {
      valueFormat: 'YYYY-MM-DD',
    },
  },
  {
    label: '在职状态',
    field: 'userStatus',
    type: 'select',
    span: 12,
    props: {
      options: [
        { label: '在职', value: 'ENABLED' },
        { label: '离职', value: 'DISABLED' },
      ],
    },
  },
  {
    label: '员工性质',
    field: 'userType',
    type: 'select',
    span: 12,
    props: {
      options: [
        { label: '正式员工', value: 'FULL_TIME' },
        { label: '兼职员工', value: 'PART_TIME' },
        { label: '实习生', value: 'INTERN' },
        { label: '外包员工', value: 'CONTRACTOR' },
      ],
    },
  },
  {
    label: '状态',
    field: 'status',
    type: 'switch',
    span: 12,
    props: {
      type: 'round',
      checkedValue: 1,
      uncheckedValue: 2,
      checkedText: '启用',
      uncheckedText: '禁用',
    },
  },
  {
    label: '资质名称',
    type: 'input',
    field: 'certificationName',
    span: 12,
  },
  {
    label: '有效期',
    field: 'certificationExpireDate',
    span: 12,
    type: 'date-picker',
    props: {
      valueFormat: 'YYYY-MM-DD',
    },
  },
])

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
  
  // 设置默认值
  form.userStatus = 'ENABLED'
  form.userType = 'FULL_TIME'
  form.gender = 'male'
  form.status = 1
}

// 保存
const save = async () => {
  const rawPassword = form.password
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    
    // 准备要提交的数据
    const submitData = {
      ...form,
    }
    
    if (isUpdate.value) {
      await updateUserNew(dataId.value, submitData)
      Message.success('修改成功')
    } else {
      if (rawPassword) {
        submitData.password = encryptByRsa(rawPassword) || ''
      }
      await addUserNew(submitData)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    form.password = rawPassword
    return false
  }
}

// 新增
const onAdd = async () => {
  reset()
  if (!deptList.value.length) {
    await getDeptList()
  }
  if (!roleList.value.length) {
    await getRoleList()
  }
  if (!postList.value.length) {
    await getPostList()
  }
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  try {
    reset()
    dataId.value = id
    if (!deptList.value.length) {
      await getDeptList()
    }
    if (!roleList.value.length) {
      await getRoleList()
    }
    if (!postList.value.length) {
      await getPostList()
    }
    
    // 使用新的API获取用户详情
    const { data } = await getUserDetailNew(id)
    if (!data) {
      return Message.error('获取用户详情失败')
    }
    
    // 将API返回的数据映射到表单
    Object.keys(form).forEach(key => {
      if (data[key] !== undefined) {
        form[key] = data[key]
      }
    })
    
    visible.value = true
  } catch (error) {
    console.error('获取用户详情失败', error)
    Message.error('获取用户详情失败')
  }
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>
