<template>
  <ElDrawer ref="elDrawerRef" v-model="drawerVisible" :title="drawerProps.title" v-bind="$attrs" destroy-on-close>
    <template #header="scope">
      <slot name="header" v-bind="scope">
        <div style="display: flex">
          <slot name="title">
            <span style="flex: 1">{{ drawerProps.title }}</span>
          </slot>
        </div>
      </slot>
    </template>

    <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :model="drawerProps.row" @submit.enter.prevent="handleConfirm">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属组织" prop="orgId">
            <el-tree-select
              v-model="drawerProps.row.orgId"
              :data="treeData"
              check-strictly
              placeholder="请选择组织"
              :render-after-expand="false"
              clearable
              :default-expand-all="true"
              :props="treeProps"
              @change="loadPosition" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" prop="positionId">
            <el-select v-model="drawerProps.row.positionId" placeholder="请选择职位">
              <el-option v-for="item in positionData" :key="item.positionId" :label="item.name" :value="item.positionId" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="账号" prop="account">
            <el-input v-model="drawerProps.row.account" :disabled="drawerProps.title == '编辑'" placeholder="请填写账号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="drawerProps.row.userName" placeholder="请填写姓名" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12"></el-col>
        <el-col :span="12"></el-col>
      </el-row>

      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="drawerProps.row.nickName" placeholder="请填写昵称" clearable />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户类型" prop="status">
            <el-radio-group v-model="drawerProps.row.userType">
              <el-radio-button :value="item.dictValue" v-for="(item, index) in userTypes" :key="index" :label="item.dictLabel" />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="drawerProps.row.gender">
              <el-radio-button :value="item.dictValue" v-for="(item, index) in genders" :key="index" :label="item.dictLabel" />
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="手机号" prop="phoneNumber">
        <el-input v-model="drawerProps.row.phoneNumber" placeholder="请填写手机号" clearable />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="drawerProps.row.email" placeholder="请填写邮箱" clearable />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="drawerProps.row.status">
          <el-radio-button :value="item.dictValue" v-for="(item, index) in commonStatus" :key="index" :label="item.dictLabel" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="drawerProps.row.remark" placeholder="请填写备注" clearable />
      </el-form-item>
    </el-form>

    <template #footer>
      <slot name="footer">
        <ElButton @click="drawerVisible = false">取 消</ElButton>
        <ElButton type="primary" @click="handleConfirm()">确 定</ElButton>
      </slot>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts" name="OrgForm">
import { UserBO } from '@/api/interface/system/user'
import OrgApi from '@/api/module/system/org'
import PositionApi from '@/api/module/system/position'
import { ResultEnum } from '@/enums/HttpEnum'
import { FormInstance, FormRules } from 'element-plus'
import { useDictOptions } from '@/hooks'
import { OrgTreeVO } from '@/api/interface/system/org'
import { PositionVO } from '@/api/interface/system/position'

const commonStatus = useDictOptions('COMMON_STATUS')
const genders = useDictOptions('USER_GENDER')
const userTypes = useDictOptions('USER_TYPE')
const rules = reactive<FormRules>({
  account: [{ required: true, message: '请填写账号' }],
  userName: [{ required: true, message: '请填写姓名' }],
  email: [{ type: 'email', message: '请填写正确的邮箱地址', trigger: 'blur' }],
  phoneNumber: [{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空' }]
})

interface EcoDrawerProps {
  api?: (params: any) => Promise<any> // 调用接口
  title: string // 顶部标题
  isView: boolean
  row: Partial<UserBO>
  getTableList?: () => void
}

const treeData = ref<OrgTreeVO[]>([])
const positionData = ref<PositionVO[]>([])
const treeProps = {
  label: 'name',
  value: 'orgId'
}

const drawerVisible = ref(false)
const drawerProps = ref<EcoDrawerProps>({
  isView: false,
  title: '',
  row: {}
})

// emit
const emit = defineEmits(['submit'])

// 接收父组件传过来的参数
const acceptParams = (params: EcoDrawerProps) => {
  drawerProps.value = params
  drawerVisible.value = true
  loadTree()
  drawerProps.value.row.status = drawerProps.value.row.status || '1'
  drawerProps.value.row.userType = drawerProps.value.row.userType || 'pc_user'
}

const loadTree = () => {
  OrgApi.tree().then(res => {
    treeData.value = [
      {
        parentId: '-1',
        orgId: '0',
        name: '顶层',
        children: res.data
      }
    ]
  })
}
const loadPosition = () => {
  positionData.value = []
  drawerProps.value.row.positionId = ''
  if (!drawerProps.value.row.orgId) return
  PositionApi.list({ orgId: drawerProps.value.row.orgId }).then(res => {
    positionData.value = res.data
  })
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>()
const handleConfirm = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return
    try {
      const { code } = await drawerProps.value.api!(drawerProps.value.row)
      if (code == ResultEnum.SUCCESS) {
        ElMessage.success({ message: `${drawerProps.value.title}成功！` })
        drawerProps.value.getTableList!()
        emit('submit')
        drawerVisible.value = false
      }
    } catch (error) {
      console.log(error)
    }
  })
}

defineExpose({
  acceptParams
})
</script>

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