<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="qualificationInfoForm" label-width="110px" label-position="top">
            <!-- 建造师证书 -->
            <template v-if="isProjectManager">

                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="建造师证书" prop="fileList">
                            <UploadFile :fileList="form.fileList" uploadType="png、jpg、jpeg、pdf"
                                :fileUploadRule="fileUploadRule" @del-file="handleDelFile"
                                @file-change="handleFileChange" type="constructor_certificate" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="专业类型" prop="professionalType">
                            <el-input v-model.trim="form.professionalType" placeholder="自动提取" clearable show-word-limit
                                maxlength="32"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="证书编号" prop="certificateCode">
                            <el-input v-model.trim="form.certificateCode" placeholder="自动提取" clearable show-word-limit
                                maxlength="32"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="级别" prop="certificateLevel">
                            <el-input v-model.trim="form.certificateLevel" 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="certificateValidityPeriod">
                            <el-date-picker v-model="form.certificateValidityPeriod" type="daterange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                                value-format="yyyy-MM-dd" class="form-item">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="使用有效期" prop="useValidityPeriod">
                            <el-date-picker v-model="form.useValidityPeriod" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
                                class="form-item">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </template>


            <!-- 安全考核B证、安全考核C证、其他人员证书 -->
            <template>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item :label="certificateName" prop="fileList2">
                            <UploadFile :fileList="form.fileList2" uploadType="png、jpg、jpeg、pdf"
                                :fileUploadRule="fileUploadRule2" @del-file="handleDelFile"
                                @file-change="handleFileChange" :type="otherType" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="证书编号" prop="certificateCode2">
                            <el-input v-model.trim="form.certificateCode2" placeholder="自动提取" maxlength="32"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="证书有效期" prop="certificateValidityPeriod2">
                            <el-date-picker v-model="form.certificateValidityPeriod2" type="daterange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                                value-format="yyyy-MM-dd" class="form-item">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="注册专业" prop="registerProfessional">
                            <el-input v-model.trim="form.registerProfessional" placeholder="自动提取" maxlength="32"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </template>
        </el-form>
    </div>
</template>

<script>
// 建造师证书识别规则
const CONSTRUCTOR_CERTIFICATE = {
    fields_json: "专业类型,证书编号,级别",
    fileUploadType: "constructor_certificate",
    suffix: "personnel_database",
}
import UploadFile from '@/views/common/UploadFile.vue'
export default {
    name: 'QualificationInfoPersonnel',
    components: { UploadFile },
    dicts: ['personnel_position', 'identification_tag'],
    props: {
        personnelPosition: {
            type: Object,
            default: () => ({
                label: '项目经理',
                value: 'project_manager',
                qualification: '建造师证书、安全考核B证'
            })
        },
        detailData: {
            type: Object,
            default: () => { }
        }
    },
    data() {
        return {
            form: {
                professionalType: '',
                certificateCode: '',
                certificateLevel: '',
                certificateValidityPeriod: '',
                useValidityPeriod: '',
                certificateCode2: '',
                certificateValidityPeriod2: '',
                registerProfessional: '',
                fileList: [],
                fileList2: [],
                delFileList: [],
            },
            // 人员证书id
            personnelCertificateId: [null, null],
            // OCR 识别规则 
            ocrRuleList: ['constructor_certificate', 'safety_assessment_certificate_b'],
            fileUploadList: [],
            // 根据返回的chat_res对象结构修改映射关系
            ocrResultParams: {
                "专业类型": "professionalType",
                "证书编号": "certificateCode",
                "级别": "certificateLevel",
            },
            ocrResultParams2: {
                "证书编号": "certificateCode2",
                "注册专业": "registerProfessional",
            },
            // 默认为安全考核B证
            otherType: 'safety_assessment_certificate_b',
            rules: {
                professionalType: [
                    { required: true, message: '请输入专业类型', trigger: 'blur' }
                ],
                certificateCode: [
                    { required: true, message: '请输入证书编号', trigger: 'blur' }
                ],
                certificateLevel: [
                    { required: true, message: '请输入证书级别', trigger: 'blur' }
                ],
                certificateValidityPeriod: [
                    { required: true, message: '请输入证书有效期', trigger: 'blur' }
                ],

                useValidityPeriod: [
                    { required: true, message: '请输入使用有效期', trigger: 'blur' }
                ],
                certificateCode2: [
                    { required: true, message: '请输入证书编号', trigger: 'blur' }
                ],
                certificateValidityPeriod2: [
                    { required: true, message: '请输入证书有效期', trigger: 'blur' }
                ],
                registerProfessional: [
                    { required: true, message: '请输入注册专业', trigger: 'blur' }
                ],
                fileList: [
                    { required: true, message: '请上传建造师证书', trigger: 'change' }
                ],
                fileList2: [
                    { required: true, message: '请上传安全考核B证', trigger: 'change' }
                ],
            }
        }
    },
    methods: {
        // 切换校验规则
        switchValidate(newVal) {
            if (newVal.value === 'project_manager') {
                this.rules = {
                    professionalType: [
                        { required: true, message: '请输入专业类型', trigger: 'blur' }
                    ],
                    certificateCode: [
                        { required: true, message: '请输入证书编号', trigger: 'blur' }
                    ],
                    certificateLevel: [
                        { required: true, message: '请输入证书级别', trigger: 'blur' }
                    ],
                    certificateValidityPeriod: [
                        { required: true, message: '请输入证书有效期', trigger: 'blur' }
                    ],

                    useValidityPeriod: [
                        { required: true, message: '请输入使用有效期', trigger: 'blur' }
                    ],
                    certificateCode2: [
                        { required: true, message: '请输入证书编号', trigger: 'blur' }
                    ],
                    certificateValidityPeriod2: [
                        { required: true, message: '请输入证书有效期', trigger: 'blur' }
                    ],
                    registerProfessional: [
                        { required: true, message: '请输入注册专业', trigger: 'blur' }
                    ],
                    fileList: [
                        { required: true, message: '请上传建造师证书', trigger: 'blur' }
                    ],
                    fileList2: [
                        { required: true, message: '请上传安全考核B证', trigger: 'blur' }
                    ],
                }
            } else if (newVal.value === 'project_chief_engineer') {
                this.rules = {}
            } else {
                this.rules = {
                    certificateCode2: [
                        { required: true, message: '请输入证书编号', trigger: 'blur' }
                    ],
                    certificateValidityPeriod2: [
                        { required: true, message: '请输入证书有效期', trigger: 'blur' }
                    ],
                    registerProfessional: [
                        { required: true, message: '请输入注册专业', trigger: 'blur' }
                    ],
                    fileList2: [
                        { required: true, message: '请上传' + this.certificateName, trigger: 'blur' }
                    ],
                }
                // 清空文件列表
                this.$nextTick(() => {
                    this.$set(this.form, 'fileList2', []);
                    this.form.delFileList.push(...this.form.fileList2.map(item => item?.response?.fileRes?.filePath || item.filePath));
                })

            }
            // 清空校验信息
            this.$nextTick(() => {
                this.$refs.qualificationInfoForm.clearValidate();
            })
        },
        // 校验规则
        validate() {
            return new Promise((resolve, reject) => {
                this.$refs.qualificationInfoForm.validate((valid) => {
                    if (valid) {
                        resolve(this.form);
                    } else {
                        reject(new Error('资质信息未填写完整'));
                    }
                });
            });
        },
        getOtherType() {
            const result = this.personnelPosition.qualification.split('、').filter(item => !item.includes('建造师证书'));
            const firstMatch = this.dict.type.identification_tag.find(item =>
                result.includes(item.label)
            );
            this.otherType = firstMatch ? firstMatch.value : '';
            const ruleItem = this.getRuleItem(this.otherType);
            const baseItems = this.isProjectManager
                ? [{ ...CONSTRUCTOR_CERTIFICATE }, { ...ruleItem }]
                : [{}, { ...ruleItem }];

            this.fileUploadList = baseItems;
        },
        // ocr文件识别规则
        ocrRule(type) {
            const item = this.getRuleItem(type);
            this.fileUploadList.push(item)
        },

        // 获取ocr识别规则
        getRuleItem(type) {
            const foundItem = this.dict.type.identification_tag.find(item => item.value === type);
            const item = foundItem ? {
                fileUploadType: foundItem.value,
                fields_json: foundItem.raw.remark,
                suffix: 'personnel_database'
            } : null;
            return 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 => {
                            let formField = null;
                            if (type === this.otherType) {
                                formField = this.ocrResultParams2[key];
                            } else {
                                formField = this.ocrResultParams[key];
                            }
                            if (formField && chat_res[key]) {
                                this.form[formField] = chat_res[key];
                            }
                        });
                    }
                }
                if (type == 'constructor_certificate') { // 建造师证书
                    this.form.fileList = file;
                    this.$refs.qualificationInfoForm.validateField(['professionalType', 'certificateCode', 'certificateLevel']);
                } else { // b证 c证 其他人员证书
                    this.form.fileList2 = file;
                    this.$refs.qualificationInfoForm.validateField(['certificateCode2', 'registerProfessional']);
                }
            }
        },
        // 文件删除时触发
        handleDelFile(file) {
            console.log(file);
            const delPath = file?.response?.fileRes?.filePath || file?.filePath || null;
            if (delPath) {
                this.form.delFileList.push(delPath);
            }
        },
        setFormData() {
            const { fileUploadType } = CONSTRUCTOR_CERTIFICATE;
            console.log(fileUploadType);

            this.fileUploadList.forEach((item, index) => {
                if (Object.keys(item).length > 0 && item.fileUploadType === fileUploadType) { // 建造师证书
                    this.form.fileList = this.getFileList(item.fileUploadType);
                    this.form.professionalType = this.getFormData(item.fileUploadType, 'professionalType');
                    this.form.certificateCode = this.getFormData(item.fileUploadType, 'certificateCode');
                    this.form.certificateLevel = this.getFormData(item.fileUploadType, 'certificateLevel');

                    this.form.certificateValidityPeriod = this.getFormData(item.fileUploadType, 'certificateValidityPeriod').split(' - ');
                    this.form.useValidityPeriod = this.getFormData(item.fileUploadType, 'useValidityPeriod').split(' - ');
                    this.$set(this.personnelCertificateId, 0, this.getFormData(item.fileUploadType, 'personnelCertificateId'));
                } else if (Object.keys(item).length > 0 && item.fileUploadType !== fileUploadType) { // 安全考核B证、安全考核C证、其他人员证书
                    this.form.fileList2 = this.getFileList(item.fileUploadType);
                    console.log(this.form.fileList2);
                    
                    this.form.registerProfessional = this.getFormData(item.fileUploadType, 'registerProfessional');
                    this.form.certificateCode2 = this.getFormData(item.fileUploadType, 'certificateCode');
                    this.form.certificateValidityPeriod2 = this.getFormData(item.fileUploadType, 'certificateValidityPeriod').split(' - ');
                    this.$set(this.personnelCertificateId, 1, this.getFormData(item.fileUploadType, 'personnelCertificateId'))
                }
            })
            console.log(this.form);
            
        },

        getFileList(businessType) {

            if (this.detailData?.certificateDetailList) {
                for (const certificateDetail of this.detailData.certificateDetailList) {
                    if (certificateDetail.certificate?.certificateType === businessType &&
                        certificateDetail.fileVoList) {
                        return certificateDetail.fileVoList.map(item => ({
                            name: item.fileName,
                            filePath: item.filePath,
                            lsFilePath: item.lsFilePath,
                            fileType: item.fileType,
                            businessType: item.businessType
                        }));
                    }
                }
            }

            return [];
        },

        getFormData(businessType, key) {

            if (!this.detailData?.certificateDetailList) {
                return '';
            }

            const certificates = this.detailData.certificateDetailList
                .map(certificateDetail => certificateDetail.certificate)
                .filter(certificate =>
                    certificate &&
                    certificate.certificateType === businessType
                );


            if (certificates.length > 0) {
                const value = certificates[0][key];
                return value != null ? value : '';
            }

            return '';
        },
        fileChangeByPersonnelPosition() {

            if (this.form.fileList && this.form.fileList.length > 0) {
                this.form.delFileList.push(...this.form.fileList.map(item => item?.response?.fileRes?.filePath || item.filePath));
                this.form.fileList = [];
            }
            if (this.form.fileList2 && this.form.fileList2.length > 0) {
                this.form.delFileList.push(...this.form.fileList2.map(item => item?.response?.fileRes?.filePath || item.filePath));
                this.form.fileList2 = [];
            }
            this.resetForm();
        },
        resetForm() {
            this.form.professionalType = '',
                this.form.certificateCode = '',
                this.form.certificateLevel = '',
                this.form.certificateValidityPeriod = '',
                this.form.useValidityPeriod = '',
                this.form.certificateCode2 = '',
                this.form.certificateValidityPeriod2 = '',
                this.form.registerProfessional = '';
        }
    },
    watch: {
        personnelPosition: {
            handler(newVal) {
                if (newVal.value !== 'project_chief_engineer') {
                    this.switchValidate(newVal);
                    this.getOtherType();
                    this.fileChangeByPersonnelPosition();
                }
            },
        },
        // 监听字典数据加载完成
        'dict.type.identification_tag': {
            handler(newVal) {
                if (newVal && newVal.length > 0) {
                    this.addOcrRule();
                }
            },
        },
        detailData: {
            handler(newVal) {
                if (Object.keys(newVal).length > 0) {
                    const { enterprisePersonnel: { personnelPosition } = {} } = newVal;
                    if (personnelPosition !== 'project_chief_engineer') {
                        this.$nextTick(() => {
                            this.setFormData();
                        })
                    }
                }
            },
        }
    },
    computed: {
        // 是否是项目经理
        isProjectManager() {
            return this.personnelPosition.value === 'project_manager';
        },
        // 证书名称
        certificateName() {
            return this.personnelPosition?.qualification?.split('、').filter(item => !item.includes('建造师证书'))[0] || '';
        },

        fileUploadRule() {
            return this.fileUploadList[0] || {};
        },
        fileUploadRule2() {
            return this.fileUploadList[1] || {};
        },

    }
}
</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>