<template>
  <el-dialog title="新增" append-to-body :modelValue="openShow" width="80%" @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>
        <el-table-column type="selection" width="55" v-if="moldAddMore"></el-table-column>

        <!-- 作业中心（绑定数组字段） -->
        <el-table-column align="center" label="作业中心">
          <template #header>
            <span><i style="color: red">*</i>作业中心</span>
          </template>
          <template #default="scope">
            <!-- prop 格式：数组名[索引].字段名 -->
            <el-form-item :prop="`tableData[${scope.$index}].wcId`" :rules="formRules.wcId">
              <el-select
                v-model="scope.row.wcId"
                placeholder="请选择"
                @change="workCenterChange"
                filterable
              >
                <el-option
                  v-for="item in wcData"
                  :key="item.id"
                  :value="item.id"
                  :label="item.wcName"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <!-- 设备检查项/槽号槽名 -->
        <el-table-column align="center" label="产线">
          <template #header>
            <span><i style="color: red">*</i>产线</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].equipmentId`"
              :rules="formRules.equipmentId"
            >
              <el-select
                v-model="scope.row.equipmentId"
                placeholder="请选择"
                :disabled="!scope.row.wcId"
                filterable
                @change="equipmentChange(scope.row, scope.$index)"
              >
                <el-option
                  v-for="item in equipmentData"
                  :key="item.id"
                  :value="item.id"
                  :label="item.deviceName"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="确认名称">
          <template #header>
            <span><i style="color: red">*</i>确认名称</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].proItem`" :rules="formRules.proItem">
              <el-input
                v-model="scope.row.proItem"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="确认编号">
          <template #header>
            <span><i style="color: red">*</i>确认编号</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].condition`"
              :rules="formRules.condition"
            >
              <el-input
                v-model="scope.row.condition"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="确认到期日期">
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].lastDueTime`">
              <el-date-picker
                v-model="scope.row.lastDueTime"
                placeholder="请输入"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="提醒天数">
          <template #header>
            <span><i style="color: red">*</i>提醒天数</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].remDays`" :rules="formRules.remDays">
              <el-input-number
                v-model="scope.row.remDays"
                controls-position="right"
                :min="1"
              ></el-input-number>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="工艺员">
          <template #header>
            <span><i style="color: red">*</i>工艺员</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].proMan`" :rules="formRules.proMan">
              <el-select
                v-model="scope.row.proMan"
                placeholder="请选择"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="item in userData"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id"
                ></el-option>
              </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}].remarks`">
              <el-input
                v-model="scope.row.remarks"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </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" :loading="loading">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { getWorkCenterList } from '@/api/processManagement/addQuantity.js';
// import { submitBatchData } from '@/api/processManagement/periodical.js'; // 实际提交接口
import { getEquipmentList, add } from '@/api/processManagement/specialProcess';
import { getRoleUserList } from '@/api/processManagement/taskDispatch';
export default {
  props: {
    showDialog: { type: Boolean, default: false },
    moldAddMore: { type: Boolean, default: false },
    tabPosition: { type: String, default: '' },
    itemData: { type: Array, default: () => [] },
  },
  data() {
    return {
      loading: false,
      openShow: false,
      wcData: [],
      userData:[],
      equipmentData: [],
      formError: '', // 全局错误提示

      // 单个表单模型：包含表格所有行数据
      form: {
        tableData: [], // 表格数据数组（直接绑定到 Form 模型）
      },

      // 统一校验规则：支持数组项校验
      formRules: {
        // 表格数据数组的整体校验（可选：如最少1行数据）
        tableData: [
          {
            required: true,
            message: '请至少添加一行数据',
            trigger: 'submit',
            type: 'array', // 明确类型为数组
          },
          {
            validator: (rule, value, callback) => {
              if (value.length === 0) {
                callback(new Error('请至少添加一行数据'));
              } else {
                callback();
              }
            },
            trigger: 'submit',
          },
        ],
        wcId: [{ required: true, message: '请选择作业中心', trigger: ['change', 'submit'] }],
        equipmentId: [{ required: true, message: '请选择产线', trigger: ['change', 'submit'] }],
        proItem: [{ required: true, message: '请输入确认名称', trigger: ['blur', 'submit'] }],
        condition: [{ required: true, message: '请输入确认编号', trigger: ['blur', 'submit'] }],
        remDays: [{ required: true, message: '请输入提醒天数', trigger: ['blur', 'submit'] }],
        proMan: [{ required: true, message: '请选择工艺员', trigger: ['change', 'submit'] }],
      },
    };
  },
  mounted() {
    this.openShow = this.showDialog;
    this.getWorkCenterList();
    this.getRoleUserList();
    // 初始添加一行（可选）
    if (this.moldAddMore && this.form.tableData.length === 0) {
      this.addTable();
    } else {
      console.log('this.itemData', this.itemData);
      this.form.tableData =
        this.itemData.length > 0 ? JSON.parse(JSON.stringify(this.itemData)) : [];
      if(this.form.tableData.length > 0){
        this.form.tableData.forEach(item => {
          item.lastDueTime = item.lastDueTime+' 00:00:00'
        })
      }
      this.workCenterChange()
    }
  },
  methods: {
    getRoleUserList() {
      getRoleUserList({ current: 1, size: 9999999 }).then(res => {
        this.userData = res.data.data.records || [];
      });
    },
    getWorkCenterList() {
      getWorkCenterList().then(res => {
        this.wcData = res.data.data || [];
      });
    },
    workCenterChange() {
      getEquipmentList({ wcId: this.form.wcId }).then(res => {
        this.equipmentData = res.data.data.records || [];
      });
    },
    equipmentChange(row, index) {
      let selectedEquipment = this.equipmentData.find(item => item.id === row.equipmentId);
      if (selectedEquipment) {
        row.equipmentName = selectedEquipment.deviceName;
        row.equipmentCode = selectedEquipment.deviceCode;
      }
    },

    selectChange(list, row) {
      row._select = !row._select;
    },

    // 新增一行（直接push到表单模型的 tableData 中）
    addTable() {
      this.form.tableData.push({
        _select: false, // 选择状态
        wcId: '', // 作业中心ID
      });
    },

    // 删除选中行
    delTable() {
      this.form.tableData = this.form.tableData.filter(row => !row._select);
    },

    closeDialog() {
      this.openShow = false;
      this.$emit('closeDialog', true);
      // 重置表单
      this.form.tableData = [];
      this.formError = '';
      this.$refs.tableForm?.resetFields();
    },

    // 提交表单（单次校验所有行）
    submitForm() {
      this.formError = '';

      // 调用单个 Form 的校验方法
      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;
        }
        this.loading = true;

        // 校验通过：准备提交数据（过滤无用字段）
        const submitData = this.form.tableData.map(row => {
          const { _select, ...validData } = row; // 剔除选择状态字段
          return validData;
        });

        // 调用接口提交（实际项目替换）
        try {
          console.log('提交数据：', submitData);
          add(submitData).then(res => {
            this.$message.success('操作成功');
            this.loading = false;
            this.closeDialog();
          });
        } catch (err) {
          this.loading = false;
          this.$message.error(err.message);
          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;
}

// 表格行高适配 textarea
.el-table__row {
  height: 80px !important;
}

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

.error-message {
  font-size: 14px;
  line-height: 1.5;
}
:deep(.el-table .el-table__cell) {
  height: 50px !important;
  padding: 0 !important;
  line-height: 50px !important;
}
</style>
