<template>
  <el-dialog
    title="新增"
    append-to-body
    :modelValue="openShow"
    width="90%"
    @close="closeDialog"
    fullscreen
  >
    <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>

    <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.moldPlan" @select="selectChange" style="width: 100%" border>
        <el-table-column type="selection" width="55" v-if="moldAddMore"></el-table-column>
        <el-table-column type="index" width="80" label="序号" align="center"></el-table-column>
        <el-table-column prop="partCode" label="零件编码" align="center">
          <template #header>
            <span><i style="color: red">*</i>零件编码</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`moldPlan[${scope.$index}].partCode`" :rules="formRules.partCode">
              <el-select
                v-model="scope.row.partCode"
                :filterable="true"
                allow-create
                :disabled="scope.row.disabled"
                @change="partCodeChange(scope.row.partCode, scope.$index)"
              >
                <el-option
                  v-for="(item, index) in partCodeList"
                  :key="index"
                  :label="item.partCode"
                  :value="item.partCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="partName" label="零件名称" align="center">
          <template #default="scope">
            <span>{{ scope.row.partName }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="moCode" label="工装号" align="center">
          <template #header>
            <span><i style="color: red">*</i>工装号</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`moldPlan[${scope.$index}].moCode`" :rules="formRules.moCode">
              <el-select
                v-model="scope.row.moCode"
                :filterable="true"
                :disabled="scope.row.disabled"
                allow-create
                @change="frockChange(scope.row.moCode, scope.$index)"
              >
                <el-option
                  v-for="(item, index) in moCodeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="moName" label="工装名称" align="center">
          <template #default="scope">
            <span>{{ scope.row.moName }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="quantity" label="数量" align="center">
          <template #header>
            <span><i style="color: red">*</i>数量</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`moldPlan[${scope.$index}].quantity`" :rules="formRules.quantity">
              <el-input-number
                v-model="scope.row.quantity"
                :min="1"
                controls-position="right"
                style="width: 90%"
                @change="handleChange"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="planType" label="计划类型" align="center">
          <template #header>
            <span><i style="color: red">*</i>计划类型</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`moldPlan[${scope.$index}].planType`" :rules="formRules.planType">
              <el-select v-model="scope.row.planType" :filterable="true" allow-create>
                <!-- ，，2、仓库 -->
                <el-option label="热表/烧结" :value="12001" />
                <el-option label="仓库" :value="12002" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="needDate" label="需求日期" align="center">
          <template #header>
            <span><i style="color: red">*</i>需求日期</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`moldPlan[${scope.$index}].needDate`" :rules="formRules.needDate">
              <el-date-picker
                v-model="scope.row.needDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
                style="width: 90%"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="quaLevel" label="生产标识" align="center">
          <template #header>
            <span><i style="color: red">*</i>生产标识</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`moldPlan[${scope.$index}].quaLevel`" :rules="formRules.quaLevel">
              <!-- <el-input v-model="scope.row.quaLevel" /> -->
              <el-select v-model="scope.row.quaLevel">
                <el-option
                  v-for="(item, index) in quaLevelList"
                  :key="index"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="keeper" label="保管员" align="center">
          <template #header>
            <span><i style="color: red">*</i>保管员</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`moldPlan[${scope.$index}].keeper`" :rules="formRules.keeper">
              <el-select v-model="scope.row.keeper" :filterable="true" allow-create>
                <el-option v-for="item in keeperList" :key="item.id" :label="item.realName" :value="item.id" />
                <!-- <el-option label="人员二" value="2" /> -->
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="memo" label="备注" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.memo" />
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="100" align="left" v-if="moldAddMore">
          <template #default="scope">
            <el-button type="text" @click.prevent="delTable(scope.row, scope.$index)"
              >删除</el-button
            >
          </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,getPartList,getProdIdentList,getUserByRoleAlias } from '@/api/orderManagement/moldPlan';
import { index } from '@/views/plugin/workflow/api/statistics';

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    moldAddMore: {
      type: Boolean,
      default: false,
    },
    list:{
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      moCodeList: [
        { label: '工装一', value: 1 },
        {
          label: '工装二',
          value: 2,
        },
      ],
      partCodeList: [],
      quaLevelList:[],
      keeperList:[],
      openShow: false,
      formError: '',
      form: {
        moldPlan: [],
      },
      formRules: {
        moldPlan: [
          {
            required: true,
            message: '请至少添加一行数据',
            trigger: 'submit',
            type: 'array',
          },
          {
            validator: (rule, value, callback) => {
              if (value.length === 0) {
                callback(new Error('请至少添加一行数据'));
              } else {
                callback();
              }
            },
            trigger: 'submit',
          },
        ],
        partCode: [{ required: true, message: '请选择零件编码', trigger: ['change', 'submit'] }],
        // moCode: [{ required: true, message: '请选择工装号', trigger: ['change', 'submit'] }],
        quantity: [
          { required: true, message: '请输入数量', trigger: ['change', 'submit'] },
          { type: 'number', min: 1, message: '数量不能小于1', trigger: ['change', 'submit'] },
        ],
        planType: [{ required: true, message: '请选择计划类型', trigger: ['change', 'submit'] }],
        needDate: [{ required: true, message: '请选择需求日期', trigger: ['change', 'submit'] }],
        quaLevel: [{ required: true, message: '请输入生产标识', trigger: ['blur', 'submit'] }],
        keeper: [{ required: true, message: '请选择保管员', trigger: ['change', 'submit'] }],
      },
    };
  },
  mounted() {
    this.openShow = this.showDialog;
    if (this.moldAddMore && this.form.moldPlan.length === 0 && this.list.length === 0) {
      this.addTable();
    }else{
      let list = JSON.parse(JSON.stringify(this.list))
      list.map(item =>{
        item.disabled = true
      })
      this.form.moldPlan = list
    }
    this.getPart();
    this.getQuaLevel()
    this.getUser()
  },
  watch: {
    showDialog(newVal) {
      this.openShow = newVal;
      if (newVal && this.moldAddMore && this.form.moldPlan.length === 0) {
        this.addTable();
      }
    },
  },
  methods: {
    getPart(){
      getPartList().then(res =>{
        this.partCodeList = res.data.data
      })
    },
    getQuaLevel(){
      getProdIdentList().then(res =>{
        this.quaLevelList = res.data.data
      })
    },
    getUser(){
      getUserByRoleAlias({roleAlias:'保管员'}).then(res =>{
        this.keeperList = res.data.data
      })
    },
    closeDialog(val) {
      this.openShow = false;
      this.$emit('closeDialog',val);
      this.form.moldPlan = [];
      this.formError = '';
      this.$refs.tableForm?.resetFields();
    },
    selectChange(list, row) {
      row._select = !row._select;
    },
    addTable() {
      this.form.moldPlan.push({
        _select: false,
        partCode: '',
        partName: '',
        moCode: '',
        moName: '',
        quantity: 1,
        planType: '',
        needDate: '',
        quaLevel: '',
        userName: '',
        memo: '',
      });
    },
    delTable(row, index) {
      if (index !== undefined) {
        this.form.moldPlan.splice(index, 1);
      } else {
        this.form.moldPlan = this.form.moldPlan.filter(item => !item._select);
      }
    },
    partCodeChange(val, i) {
      this.form.moldPlan[i].partName =
        this.partCodeList.find(item => item.partCode === val)?.partName || '';
    },
    frockChange(val, i) {
      // 保留原逻辑，可根据实际需求完善
      this.form.moldPlan[i].moName = this.moCodeList.find(item => item.value === val)?.label || '';
    },
    handleChange() {
      // 数量变化处理
    },
    submitForm() {
      // 快照打印
      this.formError = '';
      this.$refs.tableForm.validate(isValid => {
        if (!isValid) {
          this.formError = '存在未完善的字段，请检查表格中的红色提示';
          this.$nextTick(() => {
            const firstError = document.querySelector('.el-form-item.is-error');
            if (firstError) {
              firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
          });
          return;
        } else {
          console.log('submitForm after validate', JSON.parse(JSON.stringify(this.form)));
          add(this.form.moldPlan).then(res => {
            if (res.data.code === 200) {
              this.$message.success('新增成功');
              this.closeDialog(true);
            }
          });
        }

        // 处理提交数据
        // const submitData = this.form.moldPlan.map(row => {
        //   const { _select, ...validData } = row;
        //   return validData;
        // });

        // 验证通过后再打印一次快照，便于对比
      

        // 实际提交逻辑

        // this.$emit('submitSuccess', submitData);
      });
    },
  },
};
</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;
}

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