<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="accountOpeningCertificateForm" label-width="110px"
            label-position="top">
            <el-form-item label="职称证" prop="fileList">
                <UploadFile :fileList="form.fileList" uploadType="png、jpg、jpeg、pdf" :fileUploadRule="fileUploadRule"
                    @del-file="handleDelFile" @file-change="handleFileChange" type="professional_title_certificate" />
            </el-form-item>
            <el-form-item label="职称名称" prop="titleName">
                <el-input v-model.trim="form.titleName" placeholder="自动提取" clearable show-word-limit
                    maxlength="32"></el-input>
            </el-form-item>
            <el-form-item label="专业名称" prop="professionalName">
                <el-input v-model.trim="form.professionalName" placeholder="自动提取" clearable show-word-limit
                    maxlength="32"></el-input>
            </el-form-item>
            <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-form-item label="人员简介" prop="personnelIntroduction">
                <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" class="form-item"
                    v-model.trim="form.personnelIntroduction" clearable show-word-limit placeholder="请输入人员简介"
                    maxlength="300"></el-input>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
// 设置默认职位 项目经理和项目总工的职称证必填
const DEFAULT_PERSONNEL_POSITION = ['project_manager', 'project_chief_engineer'];
import UploadFile from '@/views/common/UploadFile.vue'
export default {
    name: 'OtherInfoPersonnel',
    components: { UploadFile },
    dicts: ['identification_tag'],
    props: {
        detailData: {
            type: Object,
            default: () => { }
        },
        personnelPosition: {
            type: Object,
            default: () => ({
                label: '项目经理',
                value: 'project_manager',
                qualification: '建造师证书、安全考核B证'
            })
        },
    },
    data() {
        return {
            form: {
                fileList: [],
                titleName: '',
                professionalName: '',
                certificateCode: '',
                personnelIntroduction: '',
                delFileList: [],
            },
            // 人员证书id
            personnelCertificateId: [null],
            // OCR 识别规则 
            ocrRuleList: ['professional_title_certificate'],
            fileUploadList: [],
            // 根据返回的chat_res对象结构修改映射关系
            ocrResultParams: {
                "职称名称": "titleName",
                "证书编号": "certificateCode",
                "专业名称": "professionalName",
            },
            rules: {
                fileList: [
                    { required: true, message: '请上传职称证', trigger: 'change' }
                ],
                titleName: [
                    { required: true, message: '请输入职称名称', trigger: 'blur' }
                ],
                professionalName: [
                    { required: true, message: '请输入专业名称', trigger: 'blur' }
                ],
                certificateCode: [
                    { required: true, message: '请输入证书编号', trigger: 'blur' }
                ],

            }
        }
    },
    methods: {
        // 校验规则
        validate() {
            return new Promise((resolve, reject) => {
                this.$refs.accountOpeningCertificateForm.validate((valid) => {
                    if (valid) {
                        resolve(this.form) // 校验成功返回表单数据
                    } else {
                        reject(new Error('其他信息未填写完整'))
                    }
                })
            })
        },
        // ocr文件识别规则
        ocrRule(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;
            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?.chat_res;
                    if (chat_res && typeof chat_res === 'object') {
                        // 直接遍历chat_res对象的属性
                        Object.keys(chat_res).forEach(key => {
                            let formField = formField = this.ocrResultParams[key];
                            if (formField && chat_res[key]) {
                                this.form[formField] = chat_res[key];
                            }
                        });
                    }
                }
                this.form.fileList = file;
                this.$refs.accountOpeningCertificateForm.validateField(['titleName', 'certificateCode', 'professionalName']);
            }
        },
        // 文件删除时触发
        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('professional_title_certificate');

            const titleName = this.getFormData('professional_title_certificate', 'titleName');
            const certificateCode = this.getFormData('professional_title_certificate', 'certificateCode');
            const professionalName = this.getFormData('professional_title_certificate', 'professionalName');
            this.$set(this.personnelCertificateId, 0, this.getFormData('professional_title_certificate', 'personnelCertificateId'));
            this.form = {
                titleName: titleName || '',
                professionalName: professionalName || '',
                certificateCode: certificateCode || '',
                personnelIntroduction: this.detailData.enterprisePersonnel.personnelIntroduction || '',
                fileList: fileList,
                delFileList: []
            }

        },

        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
                        }));
                    }
                }
            }

            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 '';
        },
        // 切换校验规则
        switchValidate(newVal) {

            this.rules = {
                titleName: [
                    { required: true, message: '请输入证书编号', trigger: 'blur' }
                ],
                professionalName: [
                    { required: true, message: '请输入专业名称', trigger: 'blur' }
                ],
                certificateCode: [
                    { required: true, message: '请输入证书编号', trigger: 'blur' }
                ],
                fileList: [
                    { required: true, message: '请上传职称证', trigger: 'change' }
                ],
            }
            // 清空校验信息
            this.$nextTick(() => {
                this.$refs.accountOpeningCertificateForm.clearValidate();
            })
        },
    },
    computed: {
        fileUploadRule() {
            return this.fileUploadList[0] || {};
        },
    },
    watch: {
        personnelPosition: {
            handler(newVal) {
                if (DEFAULT_PERSONNEL_POSITION.includes(newVal.value)) {
                    this.switchValidate(newVal);
                } else {
                    this.rules = {};
                    // 清空校验信息
                    this.$nextTick(() => {
                        this.$refs.accountOpeningCertificateForm.clearValidate();
                    })
                }
            },
        },
        // 监听字典数据加载完成
        '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>