<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>
                <el-col :span="8">
                    <el-form-item label="营业执照" prop="fileList">
                        <UploadFile :fileList="form.fileList" :fileUploadRule="fileUploadRule"
                            @file-change="handleFileChange" @del-file="handleDelFile" type="business_license" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="企业名称" prop="enterpriseName">
                        <el-input v-model.trim="form.enterpriseName" placeholder="自动提取" clearable show-word-limit
                            maxlength="64"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="统一社会信用代码" prop="enterpriseCode">
                        <el-input v-model.trim="form.enterpriseCode" placeholder="自动提取" clearable show-word-limit
                            maxlength="32"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="注册资本" prop="registeredCapital">
                        <el-input v-model.trim="form.registeredCapital" placeholder="自动提取" clearable show-word-limit
                            maxlength="16"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="成立日期" prop="establishedDate">
                        <el-date-picker class="form-item" v-model="form.establishedDate" 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="businessTerm">
                        <el-input v-model.trim="form.businessTerm" placeholder="自动提取" clearable show-word-limit
                            maxlength="32"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="住所" prop="residence">
                        <el-input v-model.trim="form.residence" placeholder="自动提取" clearable show-word-limit
                            maxlength="128"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="24">
                    <el-form-item label="经营范围" prop="businessScope">
                        <el-input :autosize="{ minRows: 3, maxRows: 5 }" clearable show-word-limit maxlength="255"
                            type="textarea" v-model.trim="form.businessScope" placeholder="自动提取"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import UploadFile from '@/views/common/UploadFile.vue'
import { formatDate } from '@/utils/bonus'
export default {
    name: 'BasicInfo',
    components: {
        UploadFile
    },
    props: {
        detailData: {
            type: Object,
            default: () => { }
        }
    },
    dicts: ['identification_tag'],
    data() {
        return {
            form: {
                enterpriseName: '',
                enterpriseCode: '',
                registeredCapital: '',
                establishedDate: null,
                businessTerm: '',
                residence: '',
                businessScope: '',
                fileList: [],
                delFileList: []
            },
            // OCR 识别规则
            ocrRuleList: ['business_license'],
            fileUploadList: [],
            // 根据返回的chat_res对象结构修改映射关系
            ocrResultParams: {
                "企业名称": "enterpriseName",
                "统一社会信用代码": "enterpriseCode",
                "注册资本": "registeredCapital",
                "成立日期": "establishedDate",
                "营业期限": "businessTerm",
                "住所": "residence",
                "经营范围": "businessScope",
            },
            rules: {
                fileList: [
                    { required: true, message: '请上传营业执照', trigger: 'change' }
                ],
                enterpriseName: [
                    { required: true, message: '请输入企业名称', trigger: 'blur' }
                ],
                enterpriseCode: [
                    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
                ],
                registeredCapital: [
                    { required: true, message: '请输入注册资本', trigger: 'blur' }
                ],
                establishedDate: [
                    { required: true, message: '请选择注册日期', trigger: 'change' }
                ],
                businessTerm: [
                    { required: true, message: '请输入营业期限', trigger: 'blur' },
                    { 
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback();
                                return;
                            }
                            const trimmedValue = value.trim();
                            // 检查是否为"永久"或"长期"
                            if (trimmedValue === '永久' || trimmedValue === '长期') {
                                callback();
                                return;
                            }
                            // 检查是否为日期格式
                            // 支持格式：yyyy-MM-dd, yyyy/MM/dd, yyyy年MM月dd日, yyyy.MM.dd
                            const datePatterns = [
                                /^\d{4}-\d{2}-\d{2}$/,           // yyyy-MM-dd
                                /^\d{4}\/\d{2}\/\d{2}$/,        // yyyy/MM/dd
                                /^\d{4}\.\d{2}\.\d{2}$/,        // yyyy.MM.dd
                                /^\d{4}年\d{1,2}月\d{1,2}日$/,   // yyyy年MM月dd日
                                /^\d{4}-\d{1,2}-\d{1,2}$/,       // yyyy-M-d
                                /^\d{4}\/\d{1,2}\/\d{1,2}$/      // yyyy/M/d
                            ];
                            const isDate = datePatterns.some(pattern => pattern.test(trimmedValue));
                            if (isDate) {
                                // 进一步验证日期是否有效
                                let dateStr = trimmedValue;
                                // 转换中文日期格式为标准格式
                                if (dateStr.includes('年')) {
                                    dateStr = dateStr.replace(/年/g, '-').replace(/月/g, '-').replace(/日/g, '');
                                }
                                dateStr = dateStr.replace(/\//g, '-').replace(/\./g, '-');
                                const dateParts = dateStr.split('-');
                                if (dateParts.length === 3) {
                                    const year = parseInt(dateParts[0]);
                                    const month = parseInt(dateParts[1]);
                                    const day = parseInt(dateParts[2]);
                                    const date = new Date(year, month - 1, day);
                                    if (date.getFullYear() === year && 
                                        date.getMonth() === month - 1 && 
                                        date.getDate() === day) {
                                        callback();
                                        return;
                                    }
                                }
                            }
                            callback(new Error('营业期限只能输入"永久"、"长期"或有效的日期格式（如：2024-01-01）'));
                        },
                        trigger: 'blur'
                    }
                ],
                residence: [
                    { required: true, message: '请输入住所', trigger: 'blur' }
                ],
                businessScope: [
                    { required: true, message: '请输入经营范围', trigger: 'blur' }
                ],
            }
        }
    },
    created() {
    },
    methods: {
        // 校验规则
        validate() {
            return new Promise((resolve, reject) => {
                this.$refs.basicInfoForm.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) {
            console.log(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]) {
                                if (formField === 'establishedDate') {
                                    this.form[formField] = formatDate(chat_res[key]);
                                } else {
                                    this.form[formField] = chat_res[key];
                                }
                            }
                        });
                    }
                }
                // 触发表单验证
                this.$refs.basicInfoForm.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('business_license');

            this.form = {
                enterpriseName: this.detailData.enterpriseName || '',
                enterpriseCode: this.detailData.enterpriseCode || '',
                registeredCapital: this.detailData.registeredCapital || '',
                establishedDate: this.detailData.establishedDate || null,
                businessTerm: this.detailData.businessTerm || '',
                residence: this.detailData.residence || '',
                businessScope: this.detailData.businessScope || '',
                fileList: fileList,
                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;
    }
}

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