<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>

        <!-- 单个 Form 包裹整个表格 -->
        <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 align="center" label="报废槽液类型" width="170">
                    <template #header>
                        <span><i style="color: red">*</i>报废槽液类型</span>
                    </template>
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].wasteType`" :rules="formRules.wasteType">
                            <el-select v-model="scope.row.wasteType" placeholder="请选择" style="width: 100%">
                                <el-option v-for="item in TankSol" :key="item.id" :label="item.dictValue"
                                    :value="item.dictKey" />                              
                            </el-select>
                          
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 排放班组 -->
                <el-table-column align="center" label="排放班组" width="170">
                    <template #header>
                        <span><i style="color: red">*</i>排放班组</span>
                    </template>
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].bsTeamSet`" :rules="formRules.bsTeamSet">
                            <el-select v-model="scope.row.bsTeamSet" placeholder="请选择" style="width: 100%">
                               <el-option v-for="item in teamList" :key="item.tsCode"
                                    :label="item.tsName" 
                                    :value="item.tsCode" 
                                    />
                            </el-select>
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 排放量 -->
                <el-table-column align="center" label="排放量(单位:L)" width="170">
                    <template #header>
                        <span><i style="color: red">*</i>排放量(单位:L)</span>
                    </template>
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].amount`" :rules="formRules.amount">
                            <el-input-number 
                                v-model="scope.row.amount" 
                                placeholder="请输入" 
                                controls-position="right"
                                :min="0.01"
                                :precision="2"
                                style="width: 100%" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <!-- 日期 -->
                <el-table-column align="center" label="日期" width="170">
                    <template #header>
                        <span><i style="color: red">*</i>日期</span>
                    </template>
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].dirDate`" :rules="formRules.dirDate">
                            <el-date-picker v-model="scope.row.dirDate" 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 align="center" label="水处理工" width="170">
                    <template #header>
                        <span><i style="color: red">*</i>水处理工</span>
                    </template>
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].handleMan`" :rules="formRules.handleMan">
                            <el-select v-model="scope.row.handleMan" placeholder="请选择" style="width: 100%">
                                <el-option v-for="item in handleManList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>

                        </el-form-item>
                    </template>
                </el-table-column>
                <!-- 备注 -->
                <el-table-column align="center" label="备注">
                    <template #default="scope">
                        <el-form-item :prop="`tableData[${scope.$index}].memo`" :rules="formRules.memo">
                            <el-input v-model="scope.row.memo" placeholder="请输入备注" />
                        </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, getType } from '@/api/safetyManagement/dischargeRec.js';

export default {
    props: {
        showDialog: { type: Boolean, default: false },
        moldAddMore: { type: Boolean, default: false },
        handleManList: { type: Array, default: () => [] },
        teamList: { type: Array, default: () => [] }

    },
    data() {
        return {
            TankSol:[],
            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'
                    }
                ],
                wasteType: [
                    { required: true, message: '请选择报废槽液类型', trigger: ['change', 'submit'] }
                ],
                bsTeamSet: [
                    { required: true, message: '请选择排放班组', trigger: ['change', 'submit'] }
                ],
                amount: [
                    { 
                        required: true, 
                        message: '请输入排放量', 
                        trigger: ['blur', 'submit'],
                        validator: (rule, value, callback) => {
                            // 处理空值或null的情况
                            if (value === null || value === undefined || value === '') {
                                callback(new Error('请输入排放量'));
                            } else if (isNaN(value) || typeof value !== 'number') {
                                callback(new Error('排放量必须为数字'));
                            } else if (value <= 0) {
                                callback(new Error('排放量必须大于0'));
                            } else {
                                callback();
                            }
                        }
                    }
                ],
                dirDate: [
                    { required: true, message: '请选择日期', trigger: ['change', 'submit'] }
                ],
                handleMan: [
                    { required: true, message: '请选择水处理工', trigger: ['change', 'submit'] }
                ],
                memo: [
                    { max: 200, message: '备注不能超过200个字符', trigger: ['input', 'submit'] }
                ]
            }
        };
    },
    mounted() {
        console.log("handleManList", this.handleManList)
        this.openShow = this.showDialog
        this.getTypeList()
    },
    watch: {
        showDialog(newVal) {
            this.openShow = newVal;
        }
    },
    methods: {
        selectChange(list, row) {
            row._select = !row._select;
        },
        getTypeList() {
            getType().then(res => {
                this.TankSol = res.data.data
            })
        },
        // 新增一行
        addTable() {
            this.form.tableData.push({
                _select: false,
                wasteType: '',
                bsTeamSet:'',
                amount: null,
                dirDate: '',
                handleMan:'',
                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, invalidFields) => {
                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();
                    this.$emit('submitData', submitData);
                    })
                    
                } catch (err) {
                    this.$message.error('网络错误，请稍后重试');
                    console.error('提交失败：', err);
                }
            });
        }
    },
};
</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>