<template>
    <div>
        <el-table
            :data="tableData"
            style="width: 100%"
            size="mini"
            border>
            <el-table-column
                prop="useQualificationType"
                align="center"
                label="资质类型">
                <template slot="header" slot-scope="scope">
                    <div><span class="required">*</span>资质类型</div>
                </template>
            </el-table-column>
            <el-table-column
                prop="useQualificationName"
                align="center"
                label="使用资质名称">
                <template slot="header" slot-scope="scope">
                    <div><span class="required">*</span>使用资质名称</div>
                </template>
            </el-table-column>
            <el-table-column
                prop="useQualificationRemark"
                align="center"
                label="资质使用事由">
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="90"
                 v-if="!view">
                <template slot-scope="scope">
                    <el-button @click="editRow(scope.row, scope.$index)" type="text" size="mini">编辑</el-button>
                    <el-button @click="deleteRow(scope.$index)" type="text" size="mini">删除</el-button>
                </template>
                </el-table-column>
        </el-table>
        <div v-if="!view" @click="addRow" style="text-align: center;">
            <el-button type="text" icon="el-icon-plus">添加</el-button>
        </div>
        <ele-modal
            title="明细"
            custom-class="ele-dialog-form long-dialog-form"
            :visible.sync="visible"
            :before-close="handleClose"
            :close-on-click-modal="false"
            top="5vh"
            :close-on-press-escape="false"
            append-to-body
            width="70%"
            :maxable="true"
            destroy-on-close
        >
            <el-card shadow="never">
                <el-form ref="form" :model="form">
                    <el-form-item
                        label="资质类型"
                        label-width="110px"
                        prop="useQualificationType"
                        :rules="{
                            required: true,
                            message: '选择资质类型',
                            trigger: 'change'
                        }"
                    >
                        <el-select
                            v-model="form.useQualificationType"
                            placeholder="请选择"
                            style="width: 100%"
                        >
                            <el-option
                                v-for="item in useQualificationTypeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item
                        label="使用资质名称"
                        label-width="110px"
                        prop="useQualificationName"
                        :rules="{
                            required: true,
                            message: '选择使用资质名称',
                            trigger: 'change'
                        }"
                    >
                        <el-select
                            v-model="form.useQualificationName"
                            placeholder="请选择"
                            style="width: 100%"
                        >
                            <el-option
                                v-for="item in useQualificationNameList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
        
                    <el-form-item
                        label="资质使用事由"
                        label-width="110px"
                        prop="useQualificationRemark"
                    >
                        <el-input
                            v-model="form.useQualificationRemark"
                            type="textarea"
                            placeholder="请输入"
                            :autosize="{ minRows: 2, maxRows: 4}"
                        ></el-input>
                    </el-form-item>
                </el-form>
            </el-card>

            <div slot="footer">
                <el-button type="primary" size="small" @click="save">保存</el-button>
                <el-button size="small" @click="handleClose">关闭</el-button>
            </div>
        </ele-modal>
    </div>
</template>
<script>
export default {
    props: {
        info: {
            type: Object,
            default: () => {}
        },
        generateForm: {
            type: Object,
            default: () => {}
        },
        id: {
            type: String,
            default: ''
        },
        view: {
            type: Boolean,
            default: false
        },
    },
    watch: {
        info: {
            handler(newVal, oldVal) {
                console.log('info', newVal);
                this.tableData = newVal[this.id] || [];
            },
            deep: true,
            immediate: true
        },
    },
    data() {
        const formItem = {
            useQualificationType: '',
            useQualificationRemark: '',
            useQualificationName: '',
        }
        return {
            form: {},
            formItem,
            useQualificationTypeList: [
                {
                    value: '原件',
                    label: '原件'
                },
                {
                    value: '复印件',
                    label: '复印件'
                },
                {
                    value: '扫描件',
                    label: '扫描件'
                },
                {
                    value: '无',
                    label: '无'
                },
            ],
            useQualificationNameList: [
                {
                    value: '营业执照正本（行政人事部）',
                    label: '营业执照正本（行政人事部）'
                },
                {
                    value: '营业执照副本（行政人事部）',
                    label: '营业执照副本（行政人事部）'
                },
                {
                    value: '第一类医疗器械生产备案凭证（行政人事部）',
                    label: '第一类医疗器械生产备案凭证（行政人事部）'
                },
                {
                    value: '开户许可证（行政人事部）',
                    label: '开户许可证（行政人事部）'
                },
                {
                    value: '医疗器械生产许可证（行政人事部）',
                    label: '医疗器械生产许可证（行政人事部）'
                },
                {
                    value: '医疗器械生产产品登记表（行政人事部）',
                    label: '医疗器械生产产品登记表（行政人事部）'
                },
                {
                    value: '专利证书（行政人事部）',
                    label: '专利证书（行政人事部）'
                },
                {
                    value: '二类注册证（注册法务部）',
                    label: '二类注册证（注册法务部）'
                },
                {
                    value: '无',
                    label: '无'
                },
            ],
            tableData: [],
            visible: false,
            currentItem: {},
            currentIndex: null,
            type: 'add'
        }
    },
    mounted() {
        // console.log('info~~~', this.info);
        // this.initForm();
    },
    methods: {
        async updateRowInfo() {
            let data = await this.generateForm.getData(false);
            this.generateForm.setData({
                [this.id]: this.tableData
            });
            console.log('updateRowInfo', this.tableData, data);
        },
        validateForm() {
            //开始表单校验
            return new Promise((resolve, reject) => {
                this.$refs.form.validate((valid) => {
                    if (!valid) {
                        reject(false);
                    } else {
                        resolve(true);
                    }
                });
            });
        },
        addRow() {
            this.type = 'add';
            this.visible = true;

        },
        handleClose() {
            this.visible = false;
        },
        editRow(row, index) {
            this.type = 'edit';
            console.log('编辑行', row, index);
            this.currentItem = row;
            this.currentIndex = index;
            this.visible = true;
            this.form = JSON.parse(JSON.stringify(row));
        },
        deleteRow(index) {
            this.tableData.splice(index, 1);
            this.updateRowInfo();
            // this.calculateTotalPrice();
        },
        async calculateTotalPrice() {
            let data = await this.generateForm.getData(false);
            let totalPrice = 0;
            this.tableData.forEach(item => {
                totalPrice += Number(item.price);
            });
            const price = Number(data.input_t2qmoggj);
            this.generateForm.setData({
                input_a1cnspuk: totalPrice + price
            });
        },
        async save() {
            try {
                await this.validateForm();
                console.log('表单验证通过');
                // 深拷贝form对象，避免引用问题
                const newForm = JSON.parse(JSON.stringify(this.form));
                console.log('newForm', newForm);
                if(this.type === 'add') {
                    this.tableData.push(newForm);
                } else {
                    this.tableData[this.currentIndex] = newForm;
                }
                console.log('this.tableData', this.tableData);
                this.updateRowInfo()
                // this.calculateTotalPrice()
                this.handleClose(); // 保存后关闭弹窗
                // 重置form
                this.form = {};
            } catch (error) {
                console.log('表单验证失败', error);
            }
        }
    }
}
</script>
<style scoped>
.header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
}
.blank_business_component {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}
.label {
    width: 80px;
}
.value {
    flex: 1;
    width: calc(100% - 80px);
}
:deep(.el-form-box .el-table .el-table__row .el-table__cell .cell) {
    padding-left: 10px;
    padding-right: 10px;
}
.required {
    color: red;
}
</style>