<template>
  <el-dialog title="新增" append-to-body :modelValue="openShow" width="70%" @close="closeDialog(false)">
    <div style="margin-bottom: 12px">
      <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"></el-table-column>
        
        <!-- 零件号（绑定数组字段） -->
        <el-table-column align="center" label="零件号" width="200">
          <template #header>
            <span><i style="color: red">*</i>零件号</span>
          </template>
          <template #default="scope">
            <!-- prop 格式：数组名[索引].字段名 -->
            <el-form-item :prop="`tableData[${scope.$index}].partId`" :rules="formRules.partId">
              <el-select 
                v-model="scope.row.partId" 
                placeholder="请选择"
                style="width: 100%"
                @change="(val) => changePart(val,scope.$index)"
              >
                <el-option
                  v-for="item in partData"
                  :key="item.id"
                  :value="item.id"
                  :label="item.partCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <!-- 零件名称 -->
        <el-table-column align="center" label="零件名称" width="200">
          <!-- <template #header>
            <span><i style="color: red">*</i>零件名称</span>
          </template> -->
          <template #default="scope">
            {{scope.row.partName}}
          </template>
        </el-table-column>

        <!-- 生产标识 -->
        <el-table-column align="center" label="生产标识" width="200">
          <template #header>
            <span><i style="color: red">*</i>生产标识</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].prodFlagText`" :rules="formRules.prodFlagText">
              <el-select 
                v-model="scope.row.prodFlagText" 
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option v-for="item in pqList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <!-- 子件编码 -->
        <el-table-column align="center" label="子件编码" width="200">
          <!-- <template #header>
            <span><i style="color: red">*</i>子件编码</span>
          </template> -->
          <template #default="scope">
            
            <el-form-item :prop="`tableData[${scope.$index}].subPartCode`" :rules="formRules.subPartCode">
              <el-select 
                v-model="scope.row.subPartCode" 
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option v-for="item in scope.row.subList" :key="item.partCode" :label="item.partCode" :value="item.partCode"></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}].remindContent`" :rules="formRules.remindContent">
              <el-input 
                v-model="scope.row.remindContent" 
                placeholder="请输入"
                style="width: 100%"
                type="textarea"
                :rows="2"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <!-- 热处理 -->
        <el-table-column align="center" label="热处理" width="100">
          <!-- <template #header>
            <span><i style="color: red">*</i>热处理</span>
          </template> -->
          <template #default="scope">
            
            <el-form-item :prop="`tableData[${scope.$index}].isHeatTreatment`" :rules="formRules.isHeatTreatment">
                <el-switch
                    v-model="scope.row.isHeatTreatment"
                    inline-prompt
                    active-text="开"
                    inactive-text="关"
                    style="margin: 0 auto;"
                />
              <!-- <el-select 
                v-model="scope.row.subPartId" 
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option v-for="item in pqList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select> -->
            </el-form-item>
          </template>
        </el-table-column>

        <!-- 镀后检验 -->
        <el-table-column align="center" label="镀后检验" width="100">
          <!-- <template #header>
            <span><i style="color: red">*</i>镀后检验</span>
          </template> -->
          <template #default="scope">
            
            <el-form-item :prop="`tableData[${scope.$index}].isAfterPlating`" :rules="formRules.isAfterPlating">
                <el-switch
                    style="margin: 0 auto;"
                    v-model="scope.row.isAfterPlating"
                    inline-prompt
                    active-text="开"
                    inactive-text="关"
                />
              <!-- <el-select 
                v-model="scope.row.subPartId" 
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option v-for="item in pqList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select> -->
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

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

<script>
// import { getWorkCenterList } from '@/api/processManagement/addQuantity.js';
import {getPqList,addBatch,getPartList,getSubPartList} from '@/api/qualityManagement/remindRedeem/remindRedeem'
// import { submitBatchData } from '@/api/processManagement/periodical.js'; // 实际提交接口

export default {
  props: {
    showDialog: { type: Boolean, default: false },
    moldAddMore: { type: Boolean, default: false },
    tabPosition: { type: String, default: '' },
  },
  data() {
    return {
        openShow: false,
        wcData: [],
        subList:[],
        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'
            }
            ],

            // 数组中每一项的 partId 字段校验
            // partId: [
            //   { required: true, message: '请选择零件号', trigger: ['change', 'submit'] }
            // ],

            // 数组中每一项的 partName 字段校验
            prodFlagText: [
              { 
                required: true, 
                message: '请选择生产标识', 
                trigger: ['change', 'submit'] 
              }
            ],

            // 数组中每一项的 remindContent 字段校验
            // remindContent: [
            //   { required: true, message: '请填写提醒内容', trigger: ['blur', 'submit'] },
            //   { max: 200, message: '提醒内容不能超过200个字符', trigger: ['input', 'submit'] }
            // ]
        },
        pqList:[],
        partData:[],
    };
  },
  mounted() {
    this.getPart()
    this.openShow = this.showDialog;
    // this.getWorkCenterList();
    this.getPqData()
    // this.partData = [
    //     {id:'001',code:'编号001',name:'零件名称1'},
    //     {id:'002',code:'编号002',name:'零件名称2'},
    //     {id:'003',code:'编号003',name:'零件名称3'},
    // ]
    // 初始添加一行（可选）
    if (this.moldAddMore && this.form.tableData.length === 0) {
      this.addTable();
    }
  },
  methods: {
    getPart(){
      getPartList().then(res =>{
        console.log('res----------------',res)
        this.partData = res.data.data
      })
    },
    getSubPartList(val,index){
      let tmp = this.partData.find(item => item.id === val)
      console.log('tmp----------------',tmp)
      getSubPartList({
        partCode:tmp && tmp.partCode
      }).then(res =>{
        console.log('res----------------',res)
        this.form.tableData[index].subList = res.data.data
      })
    },
    getPqData(){
        getPqList().then(res =>{
            this.pqList = res.data.data
        })
    },
    getWorkCenterList() {
      getWorkCenterList().then(res => {
        this.wcData = res.data.data || [];
      });
    },

    // 修改零件号
    changePart(val,index){
        let tmp = this.partData.find(item => item.id == val)
        this.form.tableData[index].partName = tmp.partName
        this.getSubPartList(val,index)
    },

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

    // 新增一行（直接push到表单模型的 tableData 中）
    addTable() {
      this.form.tableData.push({
        _select: false, // 选择状态
        partId: '', // 零件号ID
        partName: '', // 槽号/检查项
        remindContent: '' // 提醒内容
      });
    },

    // 删除选中行
    delTable() {
        this.$confirm('确定将选择数据删除?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() =>{
            this.form.tableData = this.form.tableData.filter(row => !row._select);
        })
    },

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

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

      if(this.form.tableData.length == 0){
        this.$message.error('请至少填写一条数据')
        return
      }

      // 调用单个 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;
        });
        console.log('submitData---------------',submitData)

        // 调用接口提交（实际项目替换）
        try {
          // const res = await submitBatchData(submitData);
          // if (res.code === 200) {
          //   this.$message.success('提交成功');
          //   this.closeDialog();
          //   this.$emit('submitSuccess', submitData);
          // } else {
          //   this.$message.error(res.msg || '提交失败');
          // }
        
        submitData.map(item =>{
            item.isHeatTreatment = item.isHeatTreatment ? 1 : 0,
            item.isAfterPlating = item.isAfterPlating ? 1 : 0
        })
        console.log('form----------------',submitData)
        addBatch(submitData).then(res =>{
            if(res.data.code == 200){
                this.$message.success('新增成功')
                this.closeDialog(true)
            }
        })
          // 演示用
        //   this.$message.success('提交成功');
        //   this.closeDialog();
        //   this.$emit('submitSuccess', 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;
}

// 表格行高适配 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>