<template>
  <el-dialog v-model="dialogVisible" width="600" :title="waitShenheForm.title" append-to-body>
    <!--人员调动-->
    <el-form v-if="waitShenheForm.isPersonnelTransfer" ref="stationChangeFormRef" :model="waitShenheForm.form" :rules="stationChangeRules" label-width="120px">
      <el-form-item label="工号 / 姓名">
          <el-tag>{{waitShenheForm.form.teacherNo}} - {{waitShenheForm.form.realName}}</el-tag>
      </el-form-item>

      <el-form-item label="原部门名称">
        <el-input v-model="waitShenheForm.form.deptName" disabled />
      </el-form-item>
      <el-form-item label="现二级部门" prop="newDeptCode">
        <el-select v-model="newSecDeptCode" @change="getDeptListByParent" placeholder="请选择二级部门">
          <el-option v-for="item in secDeptList"
                     :key="item.deptCode"
                     :label="item.deptName"
                     :value="item.deptCode">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="现子级部门">
        <el-select v-model="newSecChildDeptCode" placeholder="请选择下级部门" clearable style="width: 100%">
          <el-option v-for="item in newSecChildDeptCodeList"
                     :key="item.deptCode"
                     :label="item.deptName"
                     :value="item.deptCode">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="调令日期" prop="changeDate">
        <el-date-picker
          v-model="waitShenheForm.form.changeDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      
      <el-form-item label="岗位类型" prop="pos">
        <el-select v-model="waitShenheForm.form.pos" placeholder="请选择岗位类型" style="width: 100%">
          <el-option
            v-for="item in global.STATION_TYPE"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="waitShenheForm.form.remarks" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
      
      <el-form-item>
        <div style="text-align: right; width: 100%;">
          <el-button type="primary" @click="dialogSubmit(5)">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
    <!--党员调动-->
    <el-form v-if="waitShenheForm.isPartyTransfer" ref="partChangeFormRef" :model="waitShenheForm.form" :rules="partChangeRules" label-width="120px">
      <el-form-item label="工号 / 用户名">
        <el-tag>{{waitShenheForm.form.teacherNo}} - {{waitShenheForm.form.realName}}</el-tag>
      </el-form-item>

      <el-form-item label="原支部名">
        <el-select disabled v-model="waitShenheForm.form.oldBranchName" style="width: 100%">
          <el-option
            v-for="item in baseInfoAbout.partBranchList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="现支部名" prop="branchName">
        <el-select clearable v-model="waitShenheForm.form.branchName" placeholder="请选择现支部" style="width: 100%">
          <el-option
            v-for="item in baseInfoAbout.partBranchList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="党费" prop="partyFee">
        <el-input-number v-model="waitShenheForm.form.partyFee" :precision="2" :min="0" style="width: 100%" />
      </el-form-item>
      
      <el-form-item label="变动时间" prop="changeTime">
        <el-date-picker
          v-model="waitShenheForm.form.changeTime"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="waitShenheForm.form.remarks" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
      
      <el-form-item>
        <div style="text-align: right; width: 100%;">
          <el-button type="primary" @click="dialogSubmit(6)">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, nextTick } from 'vue'
  import { useMessage, useMessageBox } from '/@/hooks/message'
  import { getAllInfoAboutList } from '/@/api/professional/professionaluser/teacherbase'
  import { getDeptListByLevelTwo, getDeptListByParent as getDeptListByParentApi } from '/@/api/basic/basicdept'
  import { addObj as addStationChangeObj } from '/@/api/professional/professionaluser/professionalteacherstationchange'
  import { addObj as addPartyChangeObj } from '/@/api/professional/professionaluser/professionalpartychange'
  import global from '/@/components/tools/commondict.vue'
  import type { Pagination } from '/@/hooks/table'

  // 表单类型常量
  const FORM_TYPE = {
    PERSONNEL_TRANSFER: 5, // 人员调动
    PARTY_TRANSFER: 6      // 党员调动
  } as const

  // 类型定义
  interface FormData {
    newDeptCodeList?: any[]
    deptCodeList?: any[]
    teacherNo?: string
    realName?: string
    userName?: string
    deptName?: string
    id?: string
    oldBranchId?: string
    oldBranchName?: string
    newDeptCode?: string
    newSecDeptCode?: string
    changeDate?: string
    pos?: string
    remarks?: string
    branchName?: string
    partyFee?: number
    changeTime?: string
    [key: string]: any
  }

  interface WaitShenheForm {
    form: FormData
    title: string
    isPersonnelTransfer: boolean
    isPartyTransfer: boolean
  }

  // 表单 ref
  const stationChangeFormRef = ref()
  const partChangeFormRef = ref()
  
  // 人员调动验证规则
  const stationChangeRules = {
    newDeptCode: [{ required: true, message: '请选择要调入的二级部门', trigger: 'blur' }],
    changeDate: [{ required: true, message: '请选择调令日期', trigger: 'blur' }],
    pos: [{ required: true, message: '请选择岗位类型', trigger: 'blur' }]
  }
  
  // 党员调动验证规则
  const partChangeRules = {
    branchName: [{ required: true, message: '请选择现支部', trigger: 'blur' }],
    changeTime: [{ required: true, message: '请选择变动时间', trigger: 'blur' }]
  }

  /**
   * 定义Props
   * @param page 分页信息
   * @param nowRow 当前行数据
   */
  const props = defineProps<{
    page?: Pagination
    nowRow: Record<string, any>
  }>()

  /**
   * 定义Emits
   */
  const emit = defineEmits<{
    (e: 'getList', page?: Pagination): void
  }>()

  // 消息提示 hooks
  const message = useMessage()
  const messageBox = useMessageBox()

  // 响应式数据
  const dialogVisible = ref(false)
  
  /**
   * 等待审核表单
   */
  const waitShenheForm = reactive<WaitShenheForm>({
    form: {
      newDeptCodeList: [],
      deptCodeList: []
    },
    title: '',
    isPersonnelTransfer: false,
    isPartyTransfer: false
  })
  
  const baseInfoAbout = reactive({
    partBranchList: [] as any[]
  })
  
  const secDeptList = ref<any[]>([])
  const newSecChildDeptCodeList = ref<any[]>([])
  const newSecDeptCode = ref('')
  const newSecChildDeptCode = ref('')
  const teacherNo = ref('')

  // 方法定义
  /**
   * 初始化字典数据
   */
  const initDicData = async () => {
    const response = await getAllInfoAboutList()
    const map = response.data
    baseInfoAbout.partBranchList = map['partBranchList'] || []
  }

  /**
   * 初始化对话框
   * @param val 表单类型：5-人员调动，6-党员调动
   */
  const init = async (val: number) => {
    if (val !== FORM_TYPE.PERSONNEL_TRANSFER && val !== FORM_TYPE.PARTY_TRANSFER) {
      return
    }
    
    await initDicData()
    teacherNo.value = props.nowRow.teacherNo
    handleFormType(val)
  }

  /**
   * 处理表单类型显示
   * @param val 表单类型
   */
  const handleFormType = (val: number) => {
    // 重置所有表单状态
    waitShenheForm.isPersonnelTransfer = false
    waitShenheForm.isPartyTransfer = false
    
    if (val === FORM_TYPE.PERSONNEL_TRANSFER) {
      // 人员调动：加载部门数据
      waitShenheForm.title = "人员调动"
      waitShenheForm.isPersonnelTransfer = true
      waitShenheForm.form = { ...props.nowRow }
      waitShenheForm.form.id = ''
      waitShenheForm.form.newDeptCodeList = []
      waitShenheForm.form.deptCodeList = []
      newSecDeptCode.value = ''
      newSecChildDeptCode.value = ''
      
      getDeptListByLevelTwo().then((res: any) => {
        secDeptList.value = res.data || []
        dialogVisible.value = true
        // 弹窗打开后，清除表单验证状态，避免立即显示验证提示
        nextTick(() => {
          stationChangeFormRef.value?.clearValidate()
        })
      })
    } else if (val === FORM_TYPE.PARTY_TRANSFER) {
      // 党员调动：设置原支部
      waitShenheForm.title = "党员调动"
      waitShenheForm.isPartyTransfer = true
      waitShenheForm.form = { ...props.nowRow }
      waitShenheForm.form.id = ''
      waitShenheForm.form.realName = waitShenheForm.form.userName || waitShenheForm.form.realName
      waitShenheForm.form.oldBranchName = waitShenheForm.form.oldBranchId
      dialogVisible.value = true
      // 弹窗打开后，清除表单验证状态，避免立即显示验证提示
      nextTick(() => {
        partChangeFormRef.value?.clearValidate()
      })
    }
  }
  /**
   * 提交表单
   * @param val 表单类型：5-人员调动，6-党员调动
   */
  const dialogSubmit = async (val: number) => {
    if (val !== FORM_TYPE.PERSONNEL_TRANSFER && val !== FORM_TYPE.PARTY_TRANSFER) {
      return
    }

    waitShenheForm.form.teacherNo = teacherNo.value

    // 表单验证配置
    const formRefMap: Record<number, any> = {
      [FORM_TYPE.PERSONNEL_TRANSFER]: stationChangeFormRef.value,
      [FORM_TYPE.PARTY_TRANSFER]: partChangeFormRef.value
    }
    
    const formRef = formRefMap[val]
    
    // 人员调动：在验证前同步数据
    if (val === FORM_TYPE.PERSONNEL_TRANSFER) {
      waitShenheForm.form.newDeptCode = newSecDeptCode.value
      waitShenheForm.form.newSecDeptCode = newSecChildDeptCode.value || newSecDeptCode.value
    }

    // 验证表单
    if (formRef) {
      try {
        await formRef.validate()
      } catch (err) {
        return
      }
    }

    // 先确认，用户取消时不执行后续操作
    try {
      await messageBox.confirm('确认提交?')
    } catch (err: any) {
      // 用户取消操作，直接返回，不显示错误提示
      return
    }
    
    // 用户确认后，执行提交操作
    try {
      let res: any
      
      if (val === FORM_TYPE.PERSONNEL_TRANSFER) {
        // 人员调动：使用人员调动接口
        res = await addStationChangeObj(waitShenheForm.form)
      } else if (val === FORM_TYPE.PARTY_TRANSFER) {
        // 党员调动：使用党员调动接口
        res = await addPartyChangeObj(waitShenheForm.form)
      }
      
      if (res && res.data === '-1') {
        message.warning("当前不允许提交")
      } else if (res) {
        message.success("提交成功")
        emit("getList", props.page)
        dialogVisible.value = false
      }
    } catch (err: any) {
      // 处理业务错误
      message.error(err.msg)
    }
  }

  /**
   * 获取子部门列表
   */
  const getDeptListByParent = async () => {
    newSecChildDeptCode.value = ''
    newSecChildDeptCodeList.value = []
    
    if (!newSecDeptCode.value) {
      return
    }
    
    const res = await getDeptListByParentApi(newSecDeptCode.value)
    newSecChildDeptCodeList.value = res.data || []
  }

  // 暴露方法
  defineExpose({
    init
  })
</script>

