<template>
    <el-dialog title="新增" append-to-body :modelValue="openShow" width="70%" @close="closeDialog">
        <div style="margin-bottom: 12px" v-if="moldAddMore">
            <el-button type="primary" @click="addTable">插入一行</el-button>
            <el-button type="danger" @click="delTable">删除选中行</el-button>
        </div>

        <el-form ref="tableForm" :model="form" :rules="formRules" label-width="0px">
            <div v-if="formError" class="error-message" style="color: #f56c6c; margin-bottom: 10px;">
                {{ formError }}
            </div>

            <el-table :data="form.tableData" @select="selectChange" border :cell-style="{ padding: '5px' }">
                <el-table-column type="selection" width="55"></el-table-column>

                <!-- 设施 -->
                <el-table-column prop="device" label="设施" align="center" width="150">
                    <template #header>
                        <span><i style="color: red">*</i>设施</span>
                    </template>
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].device`" :rules="formRules.device">
                            <el-input v-model="scope.row.device" placeholder="请输入" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 化验时间 -->
                <el-table-column prop="dosingTime" label="化验时间" align="center" width="150">
                    <template #header>
                        <span><i style="color: red">*</i>化验时间</span>
                    </template>
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].dosingTime`" :rules="formRules.dosingTime">
                            <el-date-picker v-model="scope.row.dosingTime" format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="选择时间"
                                style="width: 100%" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 化验人 -->
                <el-table-column prop="dosingMan" label="化验人" align="center" width="150">
                    <template #header>
                        <span><i style="color: red">*</i>化验人</span>
                    </template>
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].dosingMan`" :rules="formRules.dosingMan">
                            <el-select v-model="scope.row.dosingMan" placeholder="请选择" style="width: 100%">
                                <el-option label="崔殿龙" value="541" />
                            </el-select>
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 镍 -->
                <el-table-column prop="itNi" label="镍" align="center" width="100">
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].itNi`">
                            <el-input v-model="scope.row.itNi" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 铜 -->
                <el-table-column prop="itCu" label="铜" align="center" width="100">
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].itCu`">
                            <el-input v-model="scope.row.itCu" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 六价铬 -->
                <el-table-column prop="itCr" label="六价铬" align="center" width="100">
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].itCr`">
                            <el-input v-model="scope.row.itCr" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 氰化物 -->
                <el-table-column prop="itCn2" label="氰化物" align="center" width="100">
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].itCn2`">
                            <el-input v-model="scope.row.itCn2" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- PH -->
                <el-table-column prop="itPh" label="PH" align="center" width="80">
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].itPh`">
                            <el-input v-model="scope.row.itPh" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 备注 -->
                <el-table-column prop="memo" label="备注" align="center">
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].memo`">
                            <el-input v-model="scope.row.memo" />
                        </el-form-item>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
 import { add } from '@/api/safetyManagement/testRecord.js';
export default {
    props: {
        showDialog: {
            type: Boolean,
            default: false,
        },
        moldAddMore: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            openShow: false,
            formError: '',
            form: {
                tableData: []
            },
            formRules: {
                tableData: [
                    {
                        required: true,
                        message: '请至少添加一行数据',
                        trigger: 'submit',
                        type: 'array'
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (value.length === 0) {
                                callback(new Error('请至少添加一行数据'));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'submit'
                    }
                ],
                device: [
                    { required: true, message: '请输入设施', trigger: ['blur', 'submit'] }
                ],
                dosingTime: [
                    { required: true, message: '请选择化验时间', trigger: ['change', 'submit'] }
                ],
                dosingMan: [
                    { required: true, message: '请选择化验人', trigger: ['change', 'submit'] }
                ]
            }
        };
    },
    mounted() {
        this.openShow = this.showDialog;
        if (this.moldAddMore && this.form.tableData.length === 0) {
            this.addTable();
        }
    },
    methods: {
        selectChange(list, row) {
            row._select = !row._select;
        },
        addTable() {
            this.form.tableData.push({
                _select: false,
                device: null,
                dosingTime: null,
                dosingMan: null,
                itNi: null,
                itCu: null,
                itCr: null,
                itCn2: null,
                itPh: null,
                memo: '',
            });
        },
        delTable() {
            this.form.tableData = this.form.tableData.filter(row => !row._select);
        },
        closeDialog() {
            this.openShow = false;
            this.$emit('closeDialog');
            this.form.tableData = [];
            this.formError = '';
            this.$refs.tableForm?.resetFields();
        },
        submitForm() {
            this.formError = '';
            this.$refs.tableForm.validate((isValid) => {
                if (!isValid) {
                    this.formError = '存在未完善的字段，请检查表格中的红色提示';
                    this.$nextTick(() => {
                        const firstError = document.querySelector('.el-form-item.is-error');
                        if (firstError) {
                            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    });
                    return;
                }

                const submitData = this.form.tableData.map(row => {
                    const { _select, ...validData } = row;
                    return validData;
                });

                try {
                    add(submitData).then(res => {
                        // this.$message.success('提交成功');
                        this.closeDialog();
                    });
                } catch (err) {
                    this.$message.error('网络错误，请稍后重试');
                    console.error('提交失败：', err);
                }
            });
        }
    },
    watch: {
        showDialog: {
            handler(newVal) {
                this.openShow = newVal;
            },
            immediate: true
        }
    }
};
</script>

<style lang="scss" scoped>
:deep(.el-table .el-form-item) {
    margin-bottom: 0;
}

:deep(.el-form-item__error) {
    font-size: 12px;
    white-space: nowrap;
    z-index: 10;
    background: #fff;
    padding: 2px 4px;
    border: 1px solid #f56c6c;
    border-radius: 4px;
}

.el-table__row {
    height: 80px !important;
}

.el-table__cell {
    vertical-align: middle !important;
}

.error-message {
    font-size: 14px;
    line-height: 1.5;
}
</style>