<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol"
          name="EmployeesApplyForm">
          <a-row>
            <a-col :span="24">
              <SectionDivider :title="'基本信息'" />
            </a-col>
            <a-col :span="12">
              <a-form-item label="姓名" v-bind="validateInfos.name" id="EmployeesApplyForm-name" name="name">
                <!-- <a-input v-model:value="formData.name" placeholder="请输入姓名" disabled allow-clear></a-input> -->
                <span>{{ formData.name }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="联系电话" v-bind="validateInfos.tel" id="EmployeesApplyForm-tel" name="tel">
                <!-- <a-input v-model:value="formData.tel" placeholder="请输入联系电话" disabled allow-clear></a-input> -->
                <span>{{ formData.tel }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="性别" v-bind="validateInfos.sex" id="EmployeesApplyForm-sex" name="sex">
                <!-- <j-dict-select-tag type='radio' v-model:value="formData.sex" dictCode="sex" placeholder="请选择性别" disabled
                allow-clear /> -->
                <span>{{ formData.sex }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="年龄" v-bind="validateInfos.sex" id="EmployeesApplyForm-sex" name="sex">
                <span> {{ handleComputedAge(formData.dateOfBirth) }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="出生日期" v-bind="validateInfos.dateOfBirth" id="EmployeesApplyForm-dateOfBirth"
                name="dateOfBirth">
                <!-- <a-date-picker placeholder="请选择出生日期" v-model:value="formData.dateOfBirth" value-format="YYYY-MM-DD"
                  style="width: 100%" disabled allow-clear /> -->
                <span>{{ formData.dateOfBirth }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="民族" v-bind="validateInfos.national" id="EmployeesApplyForm-national" name="national">
                <!-- <a-input v-model:value="formData.national" placeholder="请输入民族" disabled allow-clear></a-input> -->
                <span>{{ formData.national }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="身份证号">
                <span>{{ formData.idCard }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="婚否" v-bind="validateInfos.marriedOrNot" id="EmployeesApplyForm-marriedOrNot"
                name="marriedOrNot">
                <!-- <j-dict-select-tag type='radio' v-model:value="formData.marriedOrNot" dictCode="married_or_not"
                  placeholder="请选择婚否" disabled allow-clear /> -->
                <span>{{ formData.marriedOrNot }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="身高" v-bind="validateInfos.height" id="EmployeesApplyForm-height" name="height">
                <!-- <a-input-number v-model:value="formData.height" placeholder="请输入身高" style="width: 100%" disabled /> -->
                <span>{{ formData.height }}cm</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="体重" v-bind="validateInfos.weight" id="EmployeesApplyForm-weight" name="weight">
                <!-- <a-input-number v-model:value="formData.weight" placeholder="请输入体重" style="width: 100%" disabled /> -->
                <span>{{ formData.weight }}kg</span>
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item label="是否吸烟" v-bind="validateInfos.isSmoking" id="EmployeesApplyForm-isSmoking"
                name="isSmoking">
                <j-dict-select-tag type='radio' v-model:value="formData.isSmoking" dictCode="is_smoking"
                  placeholder="请选择是否吸烟" disabled allow-clear />
                <span>{{ formData.isSmoking }}</span>
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item label="健康状况" v-bind="validateInfos.healthStatus" id="EmployeesApplyForm-healthStatus"
                name="healthStatus">
                <!-- <j-dict-select-tag type='radio' v-model:value="formData.healthStatus" dictCode="health_status" disabled
                  placeholder="请选择健康状况" allow-clear /> -->
                <span>{{ formData.healthStatus }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="政治面貌" v-bind="validateInfos.politicalAppearance"
                id="EmployeesApplyForm-politicalAppearance" name="politicalAppearance">
                <!-- <j-dict-select-tag v-model:value="formData.politicalAppearance" dictCode="political_appearance" disabled
                  placeholder="请选择政治面貌" allow-clear /> -->
                <span>{{ formData.politicalAppearance }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="户籍所在地" v-bind="validateInfos.houseAddress" id="EmployeesApplyForm-houseAddress"
                name="houseAddress">
                <!-- <a-input v-model:value="formData.houseAddress" placeholder="请输入户籍所在地" disabled allow-clear></a-input> -->
                <span>{{ formData.houseAddress }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="紧急联系人" v-bind="validateInfos.emergencyContact"
                id="EmployeesApplyForm-emergencyContact" name="emergencyContact">
                <!-- <a-input v-model:value="formData.emergencyContact" placeholder="请输入紧急联系人" disabled
                  allow-clear></a-input> -->
                <span>{{ formData.emergencyContact }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="紧急联系人电话" v-bind="validateInfos.emergencyTel" id="EmployeesApplyForm-emergencyTel"
                name="emergencyTel">
                <!-- <a-input v-model:value="formData.emergencyTel" placeholder="请输入紧急联系人电话" disabled allow-clear></a-input> -->
                <span>{{ formData.emergencyTel }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="与本人关系" v-bind="validateInfos.emergencyRelationship"
                id="EmployeesApplyForm-emergencyRelationship" name="emergencyRelationship">
                <!-- <a-input v-model:value="formData.emergencyRelationship" placeholder="请输入紧急联系人与本人关系" disabled
                  allow-clear></a-input> -->
                <span>{{ formData.emergencyRelationship }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="户口性质" v-bind="validateInfos.hukouNature" id="EmployeesApplyForm-hukouNature"
                name="hukouNature">
                <!-- <j-dict-select-tag type='radio' v-model:value="formData.hukouNature" dictCode="hukou_nature" disabled
                  placeholder="请选择户口性质" allow-clear /> -->
                <span>{{ formData.hukouNature }}</span>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
    <JFormContainer>
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol2" :wrapperCol="wrapperCol2"
          name="EmployeesApplyForm">
          <a-row>
            <a-col :span="24">
              <SectionDivider :title="'证件信息'" />
            </a-col>
            <a-col :span="23" :push="1">
              <a-tabs v-model:activeKey="activeKey">
                <a-tab-pane key="1" tab="身份证">
                  <a-row>
                    <a-col :span="12">
                      <a-form-item label="身份证正面" v-bind="validateInfos.idCardPositive"
                        id="BizEmployeesInfoForm-idCardPositive" name="idCardPositive">
                        <j-image-upload v-if="!!formData.idCardPositive" :fileMax="1" :bizPath="`employeesZzxx`"
                          :value="opeMediaAddress + formData.idCardPositive" disabled></j-image-upload>
                        <span v-else>未上传</span>
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item label="身份证反面" v-bind="validateInfos.idCardNegative"
                        id="BizEmployeesInfoForm-idCardNegative" name="idCardNegative">
                        <j-image-upload v-if="!!formData.idCardNegative" :fileMax="1" :bizPath="`employeesZzxx`"
                          :value="opeMediaAddress + formData.idCardNegative" disabled></j-image-upload>
                        <span v-else>未上传</span>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-tab-pane>
                <a-tab-pane key="3" tab="健康证">
                  <a-row>
                    <a-col :span="12">
                      <a-form-item label="健康证正面" v-bind="validateInfos.healthCertificatePositive"
                        id="BizEmployeesInfoForm-healthCertificatePositive" name="healthCertificatePositive">
                        <j-image-upload v-if="!!formData.healthCertificatePositive" :fileMax="1"
                          :bizPath="`employeesZzxx`" :value="opeMediaAddress + formData.healthCertificatePositive"
                          disabled></j-image-upload>
                        <span v-else>未上传</span>
                      </a-form-item>
                    </a-col>
                    <!-- <a-col :span="12">
                      <a-form-item label="健康证反面" v-bind="validateInfos.healthCertificateNegative"
                        id="BizEmployeesInfoForm-healthCertificateNegative" name="healthCertificateNegative">
                        <j-image-upload :fileMax="1" :bizPath="`employeesZzxx`"
                          v-model:value="formData.healthCertificateNegative" disabled></j-image-upload>
                      </a-form-item>
                    </a-col> -->
                  </a-row>

                </a-tab-pane>
                <a-tab-pane key="4" tab="银行卡">
                  <a-row>
                    <a-col :span="12">
                      <a-form-item label="银行卡正面" v-bind="validateInfos.bankPositive"
                        id="BizEmployeesInfoForm-bankPositive" name="bankPositive">
                        <j-image-upload v-if="!!formData.bankPositive" :fileMax="1" :bizPath="`employeesZzxx`"
                          :value="opeMediaAddress + formData.bankPositive" disabled></j-image-upload>
                        <span v-else>未上传</span>
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item label="银行卡反面" v-bind="validateInfos.bankNegative"
                        id="BizEmployeesInfoForm-bankNegative" name="bankNegative">
                        <j-image-upload v-if="!!formData.bankNegative" :fileMax="1" :bizPath="`employeesZzxx`"
                          :value="opeMediaAddress + formData.bankNegative" disabled></j-image-upload>
                        <span v-else>未上传</span>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-tab-pane>
                <a-tab-pane key="5" tab="资质证件">
                  <a-row>
                    <a-col :span="24">
                      <a-form-item label="资质证" v-bind="validateInfos.qualification"
                        id="BizEmployeesInfoForm-qualification" name="qualification" :labelCol="labelCol3">
                        <j-image-upload v-if="!!formData.qualification" :fileMax="1" :bizPath="`employeesZzxx`"
                          :value="opeMediaAddress + formData.qualification" disabled></j-image-upload>
                        <span v-else>未上传</span>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-tab-pane>
                <a-tab-pane key="6" tab="无犯罪证明">
                  <a-row>
                    <a-col :span="24">
                      <a-form-item label="无犯罪证明" v-bind="validateInfos.noCrimeCertificate"
                        id="BizEmployeesInfoForm-noCrimeCertificate" name="noCrimeCertificate" :labelCol="labelCol3">
                        <j-image-upload v-if="!!formData.noCrimeCertificate" :fileMax="1" :bizPath="`employeesZzxx`"
                          :value="opeMediaAddress + formData.noCrimeCertificate" disabled></j-image-upload>
                        <span v-else>未上传</span>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-tab-pane>
              </a-tabs>
            </a-col>
            <a-col :span="24">
              <div v-if="formData.applyType == 0">
                <SectionDivider :title="'邀请结果'" />
              </div>
              <div v-if="formData.applyType == 1">
                <SectionDivider :title="'申请审核'" />
              </div>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="formData.applyType == 0 ? '邀请意见' : '审核意见'" v-bind="validateInfos.status"
                id="EmployeesApplyForm-status" name="status">
                <div v-if="disabled">
                  <!-- 被邀请 -->
                  <div v-if="formData.applyType == 0">
                    <span v-if="formData.status == 1">待确认</span>
                    <span v-if="formData.status == 2">已接受</span>
                    <span v-if="formData.status == 3">已拒绝</span>
                  </div>
                  <!-- 主动申请 -->
                  <div v-if="formData.applyType == 1">
                    <span v-if="formData.status == 1">待审核</span>
                    <span v-if="formData.status == 2">申请通过</span>
                    <span v-if="formData.status == 3">申请驳回</span>
                  </div>
                </div>
                <a-select v-else v-model:value="statusVal" placeholder="请选择审核意见" style="width: 200px" :disabled="false">
                  <a-select-option value="auditPass">申请通过</a-select-option>
                  <a-select-option value="auditFaild">申请驳回</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12" v-show="formData.auditContent || statusVal == 'auditFaild'">
              <!-- 被邀请 -->
              <div v-if="formData.applyType == 0">
                <!-- <a-form-item label="拒绝原因" v-bind="validateInfos.auditContent" id="EmployeesApplyForm-auditContent"
                  name="auditContent">
                  <a-textarea v-if="!disabled" :autosize="{ minRows: 3 }" maxlength="50" show-count
                    v-model:value="formData.auditContent" allow-clear></a-textarea>
                  <span v-else>{{ formData.auditContent }} </span>
                </a-form-item> -->
              </div>
              <!-- 主动申请 -->
              <div v-if="formData.applyType == 1 && formData.status != 2">
                <a-form-item label="驳回原因" v-bind="validateInfos.auditContent" id="EmployeesApplyForm-auditContent"
                  name="auditContent">
                  <a-textarea v-if="!disabled" :autosize="{ minRows: 3 }" maxlength="50" show-count
                    v-model:value="formData.auditContent" allow-clear placeholder="请输入驳回原因"></a-textarea>
                  <span v-else>{{ formData.auditContent }}</span>
                </a-form-item>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../EmployeesApply.api';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true }
});
const opeMediaAddress = import.meta.env.VITE_OPE_MEDIA_ADDRESS
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const activeKey = ref('1')
const formData = reactive<Record<string, any>>({
  id: '',
  openId: '',
  employeeId: '',
  name: '',
  sex: '',
  national: '',
  idCard: '',
  tel: '',
  dateOfBirth: '',
  marriedOrNot: '',
  height: undefined,
  weight: undefined,
  address: '',
  isSmoking: '',
  healthStatus: '',
  houseAddress: '',
  politicalAppearance: '',
  emergencyContact: '',
  emergencyTel: '',
  emergencyRelationship: '',
  hukouNature: '',
  idCardPositive: '',
  idCardNegative: '',
  healthCertificatePositive: '',
  healthCertificateNegative: '',
  bankPositive: '',
  bankNegative: '',
  qualification: '',
  noCrimeCertificate: '',
  regional: '',
  createTime: '',
  status: '',
  auditContent: '',
  applyType: '',
  startTime: '',
  endTime: '',
});
const statusVal = ref('')
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 8 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const labelCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 4 } });
const wrapperCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const labelCol3 = ref<any>({ xs: { span: 24 }, sm: { span: 2 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({
  auditContent: [
    {
      validator: async (_rule, value) => {
        if (statusVal.value === 'auditFaild' && !value) {
          return Promise.reject('请输入驳回原因!');
        }
        return Promise.resolve();
      },
    },
  ],
});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});


/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key]
      }
    })
    //赋值
    Object.assign(formData, tmpData);
    if (formData.status == '2') {
      statusVal.value = 'auditPass'
    }
    if (formData.status == '3') {
      statusVal.value = 'auditFaild'
    }
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  model.statusVal = statusVal.value
  if (!disabled.value) {
    if (!statusVal.value) {
      createMessage.warning('请选择审批意见');
      return;
    }
  }
  confirmLoading.value = true;
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}

function handleComputedAge(ageText) {
  // 检查输入是否有效
  if (!ageText || typeof ageText !== 'string') {
    return NaN;
  }

  // 解析日期字符串
  const birthDate = new Date(ageText);

  // 检查日期是否合法（例如防止 '2025-99-99' 这类无效日期）
  if (isNaN(birthDate.getTime())) {
    return NaN;
  }

  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  const dayDiff = today.getDate() - birthDate.getDate();

  // 如果还没到生日，则年龄减1
  if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
    age--;
  }

  return age >= 0 ? age : 0; // 防止返回负数
}

defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {}
</style>
