<template>
    <div>
        <div class="basic-info-title">
            <img src="@/assets/enterpriseLibrary/legalperson.png" alt="开户证明">
            <span>开户证明</span>
        </div>
        <el-form :model="form" :rules="rules" ref="accountOpeningCertificateForm" 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="account_opening_license" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="开户银行" prop="openingBank">
                        <el-input v-model.trim="form.openingBank" placeholder="自动提取" clearable show-word-limit
                            maxlength="64"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="开户账号" prop="openingAccount">
                        <el-input v-model.trim="form.openingAccount" placeholder="自动提取" clearable show-word-limit
                            maxlength="32"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>



        </el-form>
    </div>
</template>

<script>
import UploadFile from '@/views/common/UploadFile.vue'
export default {
    name: 'AccountOpeningCertificate',
    components: { UploadFile },
    dicts: ['identification_tag'],
    props: {
        detailData: {
            type: Object,
            default: () => { }
        }
    },
    data() {
        return {
            form: {
                fileList: [],
                openingBank: '',
                openingAccount: '',
                delFileList: []
            },
            // OCR 识别规则
            ocrRuleList: ['account_opening_license'],
            fileUploadList: [],
            // 根据返回的chat_res对象结构修改映射关系
            ocrResultParams: {
                "开户银行": "openingBank",
                "账号": "openingAccount",
                "开户账号": "openingAccount",
            },
            rules: {
                fileList: [
                    { required: true, message: '请上传开户许可证', trigger: 'change' }
                ],
                openingBank: [
                    { required: true, message: '请输入开户银行', trigger: 'blur' }
                ],
                openingAccount: [
                    { 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: 'main_database'
            } : null;

            this.fileUploadList.push(item)
        },
        // 添加ocr文件识别规则
        addOcrRule() {
            this.ocrRuleList.forEach(item => {
                this.ocrRule(item)
            })
        },
        // 文件变化
        handleFileChange(file) {
            this.form.fileList = file;
            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]) {
                                this.form[formField] = chat_res[key].replace(/\s/g, '');
                            }
                        });
                    }
                }
                // 触发表单验证
                this.$refs.accountOpeningCertificateForm.validate();
            }
        },
        // 文件删除时触发
        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('account_opening_license');
            this.form = {
                fileList: fileList,
                openingBank: this.detailData.openingBank || '',
                openingAccount: this.detailData.openingAccount || '',
                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] || {};
        }
    },
    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>