<template>
  <el-dialog
    title="新增"
    append-to-body
    :modelValue="showDialog"
    width="100%"
    @close="closeDialog"
    @open="open"
    fullscreen
  >
    <div style="margin-bottom: 20px">
      <el-input
        placeholder="流程卡号"
        style="width: 220px; margin-right: 10px"
        v-model="cardNo"
        @keyup.enter="handleEnter"
        @keydown.enter.prevent
      ></el-input>
      <el-button plain type="danger" @click="handleDelete">删除选择行</el-button>
      <!-- <el-button type="primary" @click="handleSave">保存</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.beforePlatingEntryData"
        @selection-change="selectionChangeProject"
        @select="selectChange"
        v-loading="tableLoading"
      >
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column label="单号" prop="paCode" align="center"></el-table-column>
        <el-table-column label="车间订单" prop="woCode" align="center">
          <template #header>
            <span><i style="color: red">*</i>车间订单</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`beforePlatingEntryData[${scope.$index}].woCode`"
              :rules="formRules.woCode"
            >
              <el-input v-model="scope.row.woCode" placeholder="请输入车间订单"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="批单号" prop="batchNo" align="center"></el-table-column>
        <el-table-column label="流程卡号" prop="cardNo" align="center"></el-table-column>
        <el-table-column label="入库班组/供应商" prop="tsName" width="200" align="center">
        </el-table-column>
        <el-table-column label="入库工序号" prop="orders" align="center"> </el-table-column>
        <el-table-column label="入库工序名称" prop="ppsName" align="center"> </el-table-column>
        <el-table-column label="下序号" prop="nextOrders" align="center"> </el-table-column>
        <el-table-column label="下序名称" prop="nextPpsName" align="center"> </el-table-column>
        <el-table-column label="下序班组/供应商" prop="nextTsName" width="200" align="center">
        </el-table-column>
        <el-table-column label="入库数量" prop="quantity" align="center"> </el-table-column>
        <el-table-column label="入库人员" prop="userName" align="center">
          <template #header>
            <span><i style="color: red">*</i>入库人员</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`beforePlatingEntryData[${scope.$index}].userName`"
              :rules="formRules.userName"
            >
              <el-input v-model="scope.row.userName"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="入库时间" prop="createTime" align="center">
          <template #header>
            <span><i style="color: red">*</i>入库时间</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`beforePlatingEntryData[${scope.$index}].createTime`"
              :rules="formRules.createTime"
            >
              <el-input v-model="scope.row.createTime"></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="handleSave">保 存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {
  getList,
  getAfterPlatCardNo,
  savePlateAroundPlateAfterEnter,
} from '@/api/productionManagement/beforeAndAfterPlating';
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      tableLoading: false,
      formError: '',
      cardNo: '',
      form: {
        beforePlatingEntryData: [],
      },
      formRules: {
        beforePlatingEntryData: [
          {
            required: true,
            message: '请至少添加一行数据',
            trigger: 'submit',
            type: 'array', // 明确类型为数组
          },
          {
            validator: (rule, value, callback) => {
              if (value.length === 0) {
                callback(new Error('请至少添加一行数据'));
              } else {
                callback();
              }
            },
            trigger: 'submit',
          },
        ],
        woCode: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
          },
        ],
        userName: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
          },
        ],
        createTime: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  mounted() {},
  methods: {
    open() {
      this.cardNo = '';
      this.form.beforePlatingEntryData = [];
    },
    handleEnter() {
      this.tableLoading = true;
      getAfterPlatCardNo({ cardNo: this.cardNo })
        .then(res => {
          this.form.beforePlatingEntryData = res.data;
        })
        .catch(err => {
          this.tableLoading = false;
        });
    },
    handleDelete() {
      this.form.beforePlatingEntryData = this.form.beforePlatingEntryData.filter(
        row => !row._select
      );
    },
    handleSave() {
      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;
        }

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

        // 调用接口提交（实际项目替换）
        try {
          savePlateAroundPlateAfterEnter({ ...this.form.beforePlatingEntryData , paType: 3 }).then(
            res => {
              this.$message.success('提交成功');
              this.closeDialog();
              this.$emit('submitSuccess', submitData);
            }
          );

          // 演示用
        } catch (err) {
          this.$message.error('网络错误，请稍后重试');
          console.error('提交失败：', err);
        }
      });
    },
    selectionChangeProject() {},
    selectChange() {},
    closeDialog() {
      this.$emit('closeDialog');
    },
  },
};
</script>

<style></style>
