<template>
    <div>
        <div class="basic-info-title">
            <img src="@/assets/enterpriseLibrary/basic-info.png" alt="基本信息">
            <span>基本信息</span>
        </div>
        <el-form :model="form" :rules="rules" ref="basicInfoForm" label-width="110px" label-position="top">
            <el-row :gutter="24">
                <el-col :span="8">
                    <!-- 身份证人面像 -->
                    <el-form-item label="身份证人面像" prop="fileList">
                        <UploadFile :fileList="form.fileList" :fileUploadRule="fileUploadRule" @del-file="handleDelFile"
                            @file-change="handleFileChange" type="face_id_card_portrait" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <!-- 身份证国徽面 -->
                    <el-form-item label="身份证国徽面" prop="fileList2">
                        <UploadFile :fileList="form.fileList2" :fileUploadRule="fileUploadRule2"
                            @del-file="handleDelFile" @file-change="handleFileChange" type="national_emblem_id_card" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="人员职位" prop="personnelPosition">
                        <el-select class="form-item" v-model="form.personnelPosition" placeholder="请选择人员职位"
                            @change="handlePersonnelPositionChange">
                            <el-option v-for="item in dict.type.personnel_position" :key="item.value"
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="人员姓名" prop="personnelName">
                        <el-input v-model.trim="form.personnelName" placeholder="自动提取" clearable show-word-limit
                            maxlength="32"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="身份证号码" prop="personnelIdCard">
                        <el-input v-model.trim="form.personnelIdCard" placeholder="自动提取" clearable show-word-limit
                            maxlength="18"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="入职时间" prop="employmentDate">
                        <el-date-picker class="form-item" v-model="form.employmentDate" placeholder="请选择入职时间"
                            value-format="yyyy-MM-dd" type="date"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="从业年限" prop="employmentYears">
                        <el-input min="0" max="60" type="number" v-model="form.employmentYears"
                            placeholder="请输入从业年限"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="8">
                    <!-- 学历证书 -->
                    <el-form-item label="学历证书" prop="fileList3">
                        <UploadFile :fileList="form.fileList3" uploadType="png、jpg、jpeg、pdf"
                            :fileUploadRule="fileUploadRule3" @del-file="handleDelFile" @file-change="handleFileChange"
                            type="academic_certificate" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="毕业院校" prop="graduateSchool">
                        <el-input v-model.trim="form.graduateSchool" placeholder="自动提取" clearable show-word-limit
                            maxlength="64"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="毕业专业" prop="graduationMajor">
                        <el-input v-model.trim="form.graduationMajor" placeholder="自动提取" clearable show-word-limit
                            maxlength="64"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="学历" prop="qualification">
                        <el-input v-model.trim="form.qualification" placeholder="自动提取" clearable show-word-limit
                            maxlength="32"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="毕业时间" prop="graduationDate">
                        <el-date-picker class="form-item" v-model="form.graduationDate" placeholder="自动提取"
                            value-format="yyyy-MM-dd" type="date"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="联系方式" prop="personnelPhone">
                        <el-input v-model.trim="form.personnelPhone" placeholder="请输入联系方式" clearable show-word-limit
                            maxlength="11"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8"></el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="劳动合同" prop="fileList4">
                        <UploadFile :fileList="form.fileList4" uploadType="pdf、doc、docx" maxFileTips="100MB"
                            :fileUploadRule="fileUploadRule4" @del-file="handleDelFile" @file-change="handleFileChange"
                            type="labor_contract" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import UploadFile from '@/views/common/UploadFile.vue'
import { validMobile, validIdCard } from '@/utils/validate'
import {convertChineseDate} from '@/utils/bonus'
export default {
    name: 'BasicInfoPersonnel',
    dicts: ['personnel_position', 'identification_tag'],
    components: {
        UploadFile
    },
    props: {
        detailData: {
            type: Object,
            default: () => { }
        }
    },
    data() {
        return {
            form: {
                personnelPosition: '',
                personnelName: '',
                employmentDate: '',
                employmentYears: '',
                graduateSchool: '',
                graduationMajor: '',
                qualification: '',
                graduationDate: '',
                personnelPhone: '',
                personnelIdCard: '',
                fileList: [],
                fileList2: [],
                fileList3: [],
                fileList4: [],
                delFileList: [],
            },
            // OCR 识别规则
            ocrRuleList: ['face_id_card_portrait', 'national_emblem_id_card', 'academic_certificate', 'labor_contract'],
            fileUploadList: [],
            // 根据返回的chat_res对象结构修改映射关系
            ocrResultParams: {
                "姓名": "personnelName",
                "公民身份号码": "personnelIdCard",
                "毕业院校": "graduateSchool",
                "毕业专业": "graduationMajor",
                "学历": "qualification",
                "毕业时间": "graduationDate",
            },
            rules: {
                personnelPosition: [
                    { required: true, message: '请选择人员职位', trigger: 'change' }
                ],
                personnelName: [
                    { required: true, message: '请输入人员姓名', trigger: 'blur' }
                ],
                personnelIdCard: [
                    { required: true, message: '请输入身份证号码', trigger: 'blur' },
                    {
                        validator: this.validateIdCard, trigger: 'blur'
                    }
                ],
                employmentDate: [
                    { required: true, message: '请选择入职时间', trigger: 'change' }
                ],
                employmentYears: [
                    { required: true, message: '请输入从业年限', trigger: 'blur' }
                ],
                graduateSchool: [
                    { required: true, message: '请输入毕业院校', trigger: 'blur' }
                ],
                graduationMajor: [
                    { required: true, message: '请输入毕业专业', trigger: 'blur' }
                ],
                qualification: [
                    { required: true, message: '请输入学历', trigger: 'blur' }
                ],
                graduationDate: [
                    { required: true, message: '请选择毕业时间', trigger: 'change' }
                ],
                personnelPhone: [
                    { required: true, message: '请输入联系方式', trigger: 'blur' },
                    {
                        validator: this.validateMobile, trigger: 'blur'
                    }
                ],
                fileList: [
                    { required: true, message: '请上传身份证人面像', trigger: ['change', 'blur'] }
                ],
                fileList2: [
                    { required: true, message: '请上传身份证国徽面', trigger: ['change', 'blur'] }
                ],
                fileList3: [
                    { required: true, message: '请上传学历证书', trigger: ['change', 'blur'] }
                ],
                fileList4: [
                    { required: true, message: '请上传劳动合同', trigger: ['change', 'blur'] }
                ],

            }
        }
    },
    methods: {
        // 联系方式校验
        validateMobile(rule, value, callback) {
            if (!validMobile(value)) {
                callback(new Error('请输入合法的联系方式'))
            } else {
                callback()
            }
        },
        // 身份证号校验
        validateIdCard(rule, value, callback) {
            if (!validIdCard(value)) {
                callback(new Error('请输入合法的身份证号码'))
            } else {
                callback()
            }
        },
        // 校验规则
        validate() {
            return new Promise((resolve, reject) => {
                this.$refs.basicInfoForm.validate((valid) => {
                    if (valid) {
                        resolve(this.form) // 校验成功返回表单数据
                    } else {
                        reject(new Error('基本信息未填写完整'))
                    }
                })
            })
        },
        // 人员职位
        handlePersonnelPositionChange() {
            const data = this.dict.type.personnel_position.find(item => item.value === this.form.personnelPosition);
            const obj = {
                label: data.label,
                value: data.value,
                qualification: data.raw.remark
            }
            this.$emit('handlePersonnelPosition', obj);
        },
        // ocr文件识别规则
        ocrRule(type) {
            const foundItem = this.dict.type.identification_tag.find(item => item.value === type);
            const item = foundItem ? {
                fileUploadType: foundItem.value,
                fields_json: type !== 'national_emblem_id_card' ? foundItem.raw.remark : '',
                suffix: 'personnel_database'
            } : null;

            this.fileUploadList.push(item)
        },
        // 添加ocr文件识别规则
        addOcrRule() {
            this.ocrRuleList.forEach(item => {
                this.ocrRule(item)
            })
        },
        // 文件变化
        handleFileChange(file, type) {

            if (file instanceof Array && file.length > 0 && file[0].response) {
                const response = file[0].response;
                if (response.ocrResult && response.ocrResult.status_code === 200) {
                    // ocr识别成功
                    const chat_res = response.ocrResult.data;
                    if (chat_res && typeof chat_res === 'object') {
                        // 直接遍历chat_res对象的属性
                        Object.keys(chat_res).forEach(key => {
                            const formField = this.ocrResultParams[key];
                            if (formField && chat_res[key]) {
                                if (formField === 'graduationDate') {
                                    // 单独处理毕业日期
                                    this.form[formField] = convertChineseDate(chat_res[key]);
                                } else {
                                    this.form[formField] = chat_res[key];
                                }
                            }
                        });
                    }
                }
                if (type == 'face_id_card_portrait') { // 身份证人面像
                    this.form.fileList = file;
                    this.$refs.basicInfoForm.validateField(['personnelName', 'personnelIdCard']);
                } else if (type == 'national_emblem_id_card') { // 身份证国徽面
                    this.form.fileList2 = file;
                } else if (type == 'academic_certificate') { // 学历证书
                    this.form.fileList3 = file;
                    this.$refs.basicInfoForm.validateField(['graduateSchool', 'graduationMajor', 'qualification', 'graduationDate']);
                } else if (type == 'labor_contract') { // 劳动合同
                    this.form.fileList4 = file;
                }
            }
        },
        // 文件删除时触发
        handleDelFile(file) {
            console.log(file);
            const delPath = file?.response?.fileRes?.filePath || file?.filePath || null;
            if (delPath) {
                this.form.delFileList.push(delPath);
            }
        },
        setFormData() {
            const fileList = this.getFileList('face_id_card_portrait');
            const fileList2 = this.getFileList('national_emblem_id_card');
            const fileList3 = this.getFileList('academic_certificate');
            const fileList4 = this.getFileList('labor_contract');

            this.form = {
                personnelPosition: this.detailData.enterprisePersonnel.personnelPosition || '',
                personnelName: this.detailData.enterprisePersonnel.personnelName || '',
                personnelIdCard: this.detailData.enterprisePersonnel.personnelIdCard || '',
                employmentDate: this.detailData.enterprisePersonnel.employmentDate || null,
                employmentYears: this.detailData.enterprisePersonnel.employmentYears || '',
                graduateSchool: this.detailData.enterprisePersonnel.graduateSchool || '',
                graduationMajor: this.detailData.enterprisePersonnel.graduationMajor || '',
                qualification: this.detailData.enterprisePersonnel.qualification || '',
                graduationDate: this.detailData.enterprisePersonnel.graduationDate || null,
                personnelPhone: this.detailData.enterprisePersonnel.personnelPhone || '',
                fileList: fileList,
                fileList2: fileList2,
                fileList3: fileList3,
                fileList4: fileList4,
                delFileList: []
            }
        },
        getFileList(businessType) {
            return this.detailData.resourceFileVoList.filter(item => item.businessType === businessType).map(item => {
                return {
                    name: item.fileName,
                    filePath: item.filePath,
                    lsFilePath: item.lsFilePath,
                    fileType: item.fileType
                };
            });
        }
    },
    computed: {
        fileUploadRule() {
            return this.fileUploadList[0] || {};
        },
        fileUploadRule2() {
            return this.fileUploadList[1] || {};
        },
        fileUploadRule3() {
            return this.fileUploadList[2] || {};
        },
        fileUploadRule4() {
            return this.fileUploadList[3] || {};
        }
    },
    watch: {
        // 监听字典数据加载完成
        'dict.type.identification_tag': {
            handler(newVal) {
                if (newVal && newVal.length > 0) {
                    this.addOcrRule();
                }
            },
            // immediate: true // 立即执行一次
        },
        detailData: {
            handler(newVal) {
                if (Object.keys(newVal).length > 0) {
                    this.setFormData();
                }
            },
            deep: true
        }
    },
}
</script>

<style scoped lang="scss">
.basic-info-title {
    display: flex;
    align-items: center;
    margin: 10px 0;

    span {
        margin: 0 5px;
        font-size: 20px;
    }
}

.form-item {
    width: 100%;
}
</style>