<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"
        :height="tableHeight"
      >
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column label="移交类型" prop="hrTypeBool" align="center" width="120">
          <template #default="scope">
            <!-- <el-input v-model="scope.row.woCode" placeholder="请输入"></el-input> -->
            <el-select v-model="scope.row.hrTypeBool" disabled placeholder="请选择" clearable>
              <el-option
                v-for="item in descriptionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="转交部门" prop="useDept" align="center" width="100">
          <template #header>
            <span><i style="color: red">*</i>转交部门</span>
          </template>
        </el-table-column>
        <el-table-column label="下级B号" prop="roamNoNext" align="center" width="120">
        </el-table-column>
        <!--<el-table-column label="下级B号名称" prop="paCode" align="center" width="120">
        </el-table-column> -->
        <!-- <el-table-column label="单号" prop="paCode" align="center" width="120"> </el-table-column> -->
        <el-table-column label="车间订单" prop="woCode" align="center" width="170">
        </el-table-column>
        <el-table-column label="批次号" prop="batchNo" align="center" width="120"></el-table-column>
        <el-table-column
          label="流程卡号"
          prop="cardNo"
          align="center"
          width="120"
        ></el-table-column>
        <el-table-column label="入库班组/供应商" prop="teamCode" width="200" align="center">
        </el-table-column>
        <el-table-column label="入库工序号" prop="processCode" align="center" width="100">
        </el-table-column>
        <el-table-column label="入库工序名称" prop="processName" align="center" width="120">
        </el-table-column>
        <el-table-column label="下序号" prop="nextProcessCode" align="center" width="120">
        </el-table-column>
        <el-table-column label="下序名称" prop="nextProcessName" align="center" width="120">
        </el-table-column>
        <el-table-column label="下序班组/供应商" prop="nextTeamCode" width="200" align="center">
        </el-table-column>
        <el-table-column label="入库数量" prop="inQuantity" align="center" width="120">
        </el-table-column>
        <el-table-column label="重量" prop="weight" align="center" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.weight" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog" :loading="sunmitLoading">取 消</el-button>
        <el-button type="primary" @click="handleSave" :loading="sunmitLoading">保 存</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 {
      tableHeight: 400,
      descriptionList: [
        {
          label: '入库',
          value: 1,
        },
        {
          label: '转工',
          value: 0,
        },
      ],
      sunmitLoading: false,
      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() {
    this.$nextTick(() => {
      this.calculateTableHeight();
    });
  },
  methods: {
    // 计算表格高度
    calculateTableHeight() {
      this.$nextTick(() => {
        const dialogContainer = document.querySelector('.el-dialog__body');
        if (!dialogContainer) return;

        const containerHeight = dialogContainer.clientHeight;

        // 减去其他元素高度
        const inputAreaHeight = 50;
        const errorHeight = 30;
        const formPadding = 40;
        const footerHeight = 10;

        const calculatedHeight =
          containerHeight - inputAreaHeight - errorHeight - formPadding - footerHeight;

        this.tableHeight = Math.max(300, Math.min(calculatedHeight, 800));
      });
    },
    open() {
      this.cardNo = '';
      this.form.beforePlatingEntryData = [];
    },
    handleEnter() {
      this.tableLoading = true;
      getAfterPlatCardNo({ cardNo: this.cardNo })
        .then(res => {
          this.form.beforePlatingEntryData.push(res.data.data);
          this.tableLoading = false;
        })
        .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.beforePlatingEntryData.map(row => {
          const { _select, ...validData } = row; // 剔除选择状态字段
          return validData;
        });

        this.sunmitLoading = true;

        // 调用接口提交（实际项目替换）
        try {
          let query = [];
          this.form.beforePlatingEntryData.forEach(item => {
            query.push({
              wpId: item.wpId,
              tsId: item.teamId,
              ocId: item.ocId ? item.ocId : null,
              quantity: item.inQuantity,
              hrTypeBool:item.hrTypeBool,
              useDept:item.useDept,
              weight:item.weight
            });
          });
          savePlateAroundPlateAfterEnter(query)
            .then(res => {
              this.$message.success('提交成功');
              this.closeDialog();
              this.$emit('submitSuccess', submitData);
              this.sunmitLoading = false;
            })
            .catch(err => {
              this.sunmitLoading = false;
            });
        } catch (err) {
          console.error('提交失败：', err);
          this.sunmitLoading = false;
        }
      });
    },
    selectionChangeProject() {},
    selectChange() {},
    closeDialog() {
      this.$emit('closeDialog');
    },
  },
};
</script>

<style></style>
