<template>
    <a-modal :open="modal.open" :title="modal.title" :width="600" :confirm-loading="modal.confirmLoading"
        :after-close="onAfterClose" :cancel-text="cancelText" @ok="handleOk" @cancel="handleCancel">
        <a-form ref="formRef" :model="formData" :rules="formRules">
            <a-row :gutter="24">
                <!-- 姓名 -->
                <a-col :span="12">
                    <a-form-item label="所属服务站点" name="orgCode">
                        <a-tree-select v-model:value="formData.orgCode" style="width: 100%" :tree-data="treeData"
                            tree-checkable allow-clear :show-checked-strategy="SHOW_PARENT" placeholder="请选择站点"
                            tree-node-filter-prop="label" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="施工人员姓名" name="name">
                        <a-input v-model:value="formData.name" placeholder="请输入施工人员姓名" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="身份证号码" name="idNumber">
                        <a-input v-model:value="formData.idNumber" placeholder="请输入身份证号码"  @change="extractBirthDateFromIdCard"/>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="性别" name="gender">
                        <a-radio-group v-model:value="formData.gender">
                            <a-radio value="1">男</a-radio>
                            <a-radio value="2">女</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="出生日期" name="birthDate">
                        <a-input v-model:value="formData.birthDate" placeholder="根据身份证号码自动识别" disabled />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="手机号码" name="phoneNum">
                        <a-input v-model:value="formData.phoneNum" placeholder="请输入手机号码" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="资格证照名称" name="qualificationName">
                        <a-input v-model:value="formData.qualification" placeholder="请输入资格证照名称" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="资格证照等级" name="qualificationLev">
                        <a-input v-model:value="formData.name" placeholder="请输入资格证照等级" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="资格证照等级" name="qualificationLev">
                        <gx-upload v-model="formData.imgList" accept-types=".jpg,.png,.webp" :fileNumber="1" />
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref, defineProps } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal } from '@/hooks'
import { useDicsStore } from '@/store'
import AreaCascader from '@/components/AreaCascader/index.vue'
const emit = defineEmits(['ok'])
const activeKey = ref('1')
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRecord, formData, formRef, formRules, resetForm } = useForm()
import { validatePhone, validateEmail, validateIdCard } from '@/utils/validate'
const cancelText = ref('取消')
const treeData = [
    {
        label: 'Node1',
        value: '0-0',
        children: [
            {
                label: 'Child Node1',
                value: '0-0-0',
            },
        ],
    },
    {
        label: 'Node2',
        value: '0-1',

        children: [
            {
                label: 'Child Node3',
                value: '0-1-0',
                disabled: true,
            },
            {
                label: 'Child Node4',
                value: '0-1-1',
            },
            {
                label: 'Child Node5',
                value: '0-1-2',
            },
        ],
    },
];
formData.value.gender='1'
formRules.value = {
    orgCode: [{ required: true, message: '请选择服务组织',trigger: ['blur','change']}],
    name: [{ required: true, message: '请输入施工人员姓名',trigger: 'blur'  }],
    idNumber: [{ validator: validateIdCard, trigger: ['blur', 'input'] }, { required: true, message: '请输入联系方式', trigger: 'blur' }],
    phoneNum: [{ validator: validatePhone, trigger: ['blur', 'input'] }, { required: true, message: '请输入联系方式', trigger: 'blur' }],
}
/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: '分配节点',
    })
}

// 提取出生日期方法
const extractBirthDateFromIdCard = () => {
    console.log(111)
  const { idNumber } = formData.value;
  if (!idNumber) {
    formData.value.birthDate = '';
    return;
  }

  let year, month, day;

  // 15位身份证：YYMMDD
  if (idNumber.length === 15) {
    year = '19' + idNumber.substring(6, 8); // 默认1900年代
    month = idNumber.substring(8, 10);
    day = idNumber.substring(10, 12);
  }
  // 18位身份证：YYYYMMDD
  else if (idNumber.length === 18) {
    year = idNumber.substring(6, 10);
    month = idNumber.substring(10, 12);
    day = idNumber.substring(12, 14);
  }
  else {
    formData.value.birthDate = '';
    return;
  }

  // 验证是否为合法日期
  const date = new Date(year, month - 1, day); // 注意：月份从0开始
  if (
    date.getFullYear() !== parseInt(year, 10) ||
    date.getMonth() + 1 !== parseInt(month, 10) ||
    date.getDate() !== parseInt(day, 10)
  ) {
    formData.value.birthDate = ''; // 不合法则清空
    return;
  }

  // 格式化为 YYYY-MM-DD
  const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  formData.value.birthDate = formattedDate;
};

/**
 * 确定
 */
function handleOk() {
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()
                const params = {
                    ...formData.value,
                }
                let result = null
                switch (modal.value.type) {
                    case 'create':
                        result = await apis.serverObj.createItem(params).catch(() => {
                            throw new Error()
                        })
                        break
                    case 'edit':
                        result = await apis.serverObj.updateItem(params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (config('http.code.success') === result?.code) {
                    hideModal()
                    emit('ok')
                }
            } catch (error) {
                hideLoading()
            }
        })
        .catch(() => {
            hideLoading()
        })
}

/**
 * 取消
 */
function handleCancel() {
    hideModal()
}

/**
 * 关闭后
 */
function onAfterClose() {
    resetForm()
    hideLoading()
}

defineExpose({
    handleCreate,
})
</script>

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