<template>
    <div>
        <div class="basic-info-title">
            <img src="@/assets/enterpriseLibrary/legalperson.png" alt="法人信息">
            <span>法人信息</span>
        </div>
        <el-form :model="form" :rules="rules" ref="legalPersonForm" label-width="110px" label-position="top">
            <!-- 身份证人像面 -->
            <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-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-form-item label="法人姓名" prop="legalPersonName">
                <el-input v-model.trim="form.legalPersonName" placeholder="自动提取" clearable show-word-limit maxlength="32"></el-input>
            </el-form-item>
            <el-form-item label="法人身份证号" prop="legalPersonIdCard">
                <el-input v-model.trim="form.legalPersonIdCard" placeholder="自动提取" clearable show-word-limit maxlength="32"></el-input>
            </el-form-item>
            <el-form-item label="身份证有效期" prop="idCardStartDate">
                <el-input v-model.trim="form.idCardStartDate" placeholder="自动提取" clearable show-word-limit maxlength="32"></el-input>
            </el-form-item>
            <el-form-item label="法人职务" prop="legalPersonPosition">
                <el-input v-model.trim="form.legalPersonPosition" placeholder="请输入法人职务" clearable show-word-limit maxlength="32"></el-input>
            </el-form-item>
            <el-form-item label="法人联系方式" prop="legalPersonPhone">
                <el-input v-model.trim="form.legalPersonPhone" placeholder="请输入法人联系方式" clearable show-word-limit maxlength="11"></el-input>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import UploadFile from '@/views/common/UploadFile.vue'
import { validMobile,validIdCard } from '@/utils/validate'
export default {
    name: 'LegalPerson',
    components: { UploadFile },
    dicts: ['identification_tag'],
    props:{
        detailData: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        return {
            form: {
                legalPersonName: '',
                legalPersonIdCard: '',
                idCardStartDate: '',
                legalPersonPosition: '',
                legalPersonPhone: '',
                fileList: [],
                fileList2: [],
                delFileList: []
            },
            // OCR 识别规则
            ocrRuleList: ['face_id_card_portrait', 'national_emblem_id_card'],
            fileUploadList: [],
            // 根据返回的chat_res对象结构修改映射关系
            ocrResultParams: {
                "姓名": "legalPersonName",
                "公民身份号码": "legalPersonIdCard",
                "有效期限": "idCardStartDate",
            },
            rules: {
                fileList: [
                    { required: true, message: '请上传身份证人像面', trigger: 'change' }
                ],
                fileList2: [
                    { required: true, message: '请上传身份证国徽面', trigger: 'change' }
                ],
                legalPersonName: [
                    { required: true, message: '请输入法人姓名', trigger: 'blur' }
                ],
                legalPersonIdCard: [
                    { required: true, message: '请输入法人身份证号', trigger: 'blur' },
                    {
                        validator: this.validateIdCard, trigger: 'blur'
                    }
                ],
                idCardStartDate: [
                    { required: true, message: '请输入身份证有效期', trigger: 'blur' }
                ],
                legalPersonPhone: [
                    {
                        validator: this.validateMobile, trigger: 'blur'
                    }
                ],
            }
        }
    },
    methods: {
        // 身份证号校验
        validateIdCard(rule, value, callback) {
            if (!validIdCard(value)) {
                callback(new Error('请输入合法的身份证号码'))
            } else {
                callback()
            }
        },
        // 联系方式校验
        validateMobile(rule, value, callback) {
            if (!validMobile(value)) {
                callback(new Error('请输入合法的联系方式'))
            } else {
                callback()
            }
        },
        // 校验规则
        validate() {
            return new Promise((resolve, reject) => {
                this.$refs.legalPersonForm.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: 'main_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 => {
                            const formField = this.ocrResultParams[key];
                            if (formField && chat_res[key]) {
                                this.form[formField] = chat_res[key];
                            }
                        });
                    }
                }
                if (type == 'face_id_card_portrait') {
                    this.form.fileList = file;
                    this.$refs.legalPersonForm.validateField(['legalPersonName', 'legalPersonIdCard']);
                } else if (type == 'national_emblem_id_card') {
                    this.form.fileList2 = file;
                    this.$refs.legalPersonForm.validateField(['idCardStartDate']);
                }
                
            }
        },
        // 文件删除时触发
        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')
            this.form = {
                legalPersonName: this.detailData.legalPersonName || '',
                legalPersonIdCard: this.detailData.legalPersonIdCard || '',
                idCardStartDate: this.detailData.idCardStartDate || '',
                legalPersonPosition: this.detailData.legalPersonPosition || '',
                legalPersonPhone: this.detailData.legalPersonPhone || '',
                fileList: fileList,
                fileList2: fileList2,
                delFileList: []
            }
        },
        getFileList(businessType){
            return this.detailData.fileList.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] || {};
        }
    },
    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();
                }
            },
            immediate: true, // 立即执行一次
            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;
    }
}
</style>