<template>
  <el-dialog
    :title="title"
    append-to-body
    :modelValue="openShow"
    width="70%"
    @close="closeDialog"
    fullscreen
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="模板编码:" prop="code">
            <el-input v-model="ruleForm.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模板名称:" prop="name">
            <el-input v-model="ruleForm.name" @change="nameChange"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模板类型:" prop="templateType">
            <el-select v-model="ruleForm.templateType" placeholder="请选择" clearable filterable>
              <el-option
                v-for="(item, index) in processTemplateList"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="作业中心:" prop="workCenterId">
            <el-select v-model="ruleForm.workCenterId" placeholder="请选择" clearable filterable>
              <el-option v-for="item in workCenterList" :label="item.wcName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="镀种分类:" prop="platingType">
            <el-select v-model="ruleForm.platingType" placeholder="请选择" clearable filterable>
              <el-option
                v-for="(item, index) in platingTypeList"
                :label="item.plateType"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="优先级:" prop="priority">
            <el-input-number
              v-model="ruleForm.priority"
              controls-position="right"
              @change="handleChange"
              :min="1"
              :max="10"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注:" prop="remarks">
            <el-input v-model="ruleForm.remarks" type="textarea" :rows="3"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <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>
      <!-- 全局错误提示 -->
      <div v-if="formError" class="error-message" style="color: #f56c6c; margin-bottom: 10px">
        {{ formError }}
      </div>

      <el-table :data="ruleForm.tableData" style="width: 100%">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="processNo" label="工序号" align="left">
          <template #header>
            <span><i style="color: red">*</i>工序号</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].processNo`"
              :rules="rules.processNo"
              label-width="0"
            >
              <el-input v-model="scope.row.processNo" placeholder="请输入内容"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="processCode" label="工序代码" align="left">
          <template #header>
            <span><i style="color: red">*</i>工序代码</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].processCode`"
              :rules="rules.processCode"
              label-width="0"
            >
              <el-select
                v-model="scope.row.processCode"
                placeholder="请选择"
                @change="processChange(scope.row, scope.$index)"
                clearable
                filterable
              >
                <el-option v-for="(item, index) in processList" :label="item.code" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="processName" label="工序名称" align="left">
          <template #default="scope">
            <span>{{ scope.row.processName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="craftCode" label="工艺能力" align="left">
          <template #header>
            <span><i style="color: red">*</i>工艺能力</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].craftCode`"
              :rules="rules.craftCode"
              label-width="0"
            >
              <el-select v-model="scope.row.craftCode" placeholder="请选择" clearable filterable>
                <el-option v-for="item in craftCodeList" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="workHours" label="工时(分钟)" align="left">
          <template #header>
            <span><i style="color: red">*</i>工时(分钟)</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].workHours`"
              :rules="rules.workHours"
              label-width="0"
            >
              <el-input-number
                v-model="scope.row.workHours"
                controls-position="right"
                :min="1"
                :max="10"
              ></el-input-number>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="proDes" label="工序描述" align="left">
          <template #header>
            <span><i style="color: red">*</i>工序描述</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].proDes`"
              :rules="rules.proDes"
              label-width="0"
            >
              <el-input v-model="scope.row.proDes" placeholder="请输入内容"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="partName" label="主工序" align="left">
          <template #header>
            <span><i style="color: red">*</i>主工序</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].isMain`"
              :rules="rules.isMain"
              label-width="0"
            >
              <el-select v-model="scope.row.isMain" placeholder="请选择" clearable filterable>
                <el-option label="是" value="1"> </el-option>
                <el-option label="否" value="2"> </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">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { getDictionary } from '@/api/system/dict';
import {
  getProcessesTeams,
  add,
  update,
  getDetail,
  getProcessAbilityList,
} from '@/api/processManagement/processTemplate';
import { getList } from '@/api/processManagement/basicProcesses';
import { getWorkCenterList } from '@/api/processManagement/addQuantity';
import pinyin from 'pinyin';
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    moldAddMore: {
      type: Boolean,
      default: false,
    },
    updateRow: {
      type: Object,
      default: {},
    },
    title: {
      type: String,
      default: '新增',
    },
  },
  data() {
    return {
      craftCodeList: [], //工艺能力列表
      formError: '', // 全局错误提示
      processTemplateList: [],
      platingTypeList: [],
      processList: [],
      openShow: false,
      //   tableData: [],

      ruleForm: {
        code: '',
        name: '',
        workCenterId: '',
        platingType: '',
        priority: '',
        tableData: [],
      },
      rules: {
        code: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        workCenterId: [{ required: true, message: '请选择', trigger: 'blur' }],
        platingType: [{ required: true, message: '请选择', trigger: 'blur' }],
        priority: [{ required: true, message: '请选择', trigger: 'blur' }],
        templateType: [{ required: true, message: '请选择', trigger: 'blur' }],
        tableData: [
          {
            required: true,
            message: '请至少添加一行数据',
            trigger: 'submit',
            type: 'array', // 明确类型为数组
          },
          {
            validator: (rule, value, callback) => {
              if (value.length === 0) {
                callback(new Error('请至少添加一行数据'));
              } else {
                callback();
              }
            },
            trigger: 'submit',
          },
        ],
        processNo: [{ required: true, message: '请输入工序号', trigger: 'blur' }],
        processCode: [{ required: true, message: '请选择工序代码', trigger: 'blur' }],
        craftCode: [{ required: true, message: '请选择工艺能力', trigger: 'blur' }],
        workHours: [{ required: true, message: '请输入工时(分钟)', trigger: 'blur' }],
        proDes: [{ required: true, message: '请输入工序描述', trigger: 'blur' }],
        isMain: [{ required: true, message: '请选择主工序', trigger: 'blur' }],
      },
      workCenterList: [], //作业中心列表
    };
  },
  mounted() {
    this.openShow = this.showDialog;

    this.getDictionary();
    this.getProcessesTeams();
    this.getProcessList();
    this.getWorkCenterList();
    this.getProcessAbilityList();
    if (this.title == '修改') {
      this.getDetail();
    }
  },
  methods: {
    nameChange() {},
    // 获取工序号
    getProcessNo(table) {
      const len = table;
      let processNo = (len.length + 1) * 5;

      if (processNo.toString().length === 1) {
        processNo = '000' + processNo;
      } else if (processNo.toString().length === 2) {
        processNo = '00' + processNo;
      } else if (processNo.toString().length === 3) {
        processNo = '0' + processNo;
      } else if (processNo.toString().length === 4) {
        processNo = '' + processNo;
      }
      return processNo;
    },
    // 获取工艺能力
    getProcessAbilityList() {
      getProcessAbilityList().then(res => {
        console.log('99999', res.data.data);
        this.craftCodeList = res.data.data;
      });
    },
    getWorkCenterList() {
      getWorkCenterList({ current: 1, size: 99999 }).then(res => {
        this.workCenterList = res.data.data;
      });
    },
    getDetail() {
      getDetail(this.updateRow.id).then(res => {
        this.ruleForm = res.data.data.dsProModelEntity;
        this.ruleForm.tableData = res.data.data.dsProDetailEntityList;
      });
    },
    getDictionary() {
      getDictionary({ code: 'processTemplateType' }).then(res => {
        this.processTemplateList = res.data.data;
      });
    },
    getProcessesTeams() {
      getProcessesTeams({ current: 1, size: 99999 }).then(res => {
        this.platingTypeList = res.data.data;
      });
    },
    getProcessList() {
      getList(1, 99999).then(res => {
        this.processList = res.data.data.records;
      });
    },
    closeDialog() {
      this.openShow = false;
      this.$emit('closeDialog');
    },
    // 插入一行
    addTable() {
      this.ruleForm.tableData.push({
        processNo: this.getProcessNo(this.ruleForm.tableData),
        processCode: null,
        processName: null,
        craftCode: null,
        workHours: null,
        proDes: null,
        isMain: null,
      });
    },
    // 删除一行
    delTable(row, index) {
      this.ruleForm.tableData.splice(index, 1);
    },

    // 工序代码选择
    processChange(row, index) {
      let selected = this.processList.find(item => item.id == row.processCode);
      row.processName = selected.name;
    },

    submit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const pinyinArr = pinyin(this.ruleForm.name, {
            style: pinyin.STYLE_NORMAL, // 无声调（STYLE_TONE 带声调）
            heteronym: false, // 不考虑多音字
          });
          let query = {
            ...this.ruleForm,
            modelNameStr: pinyinArr.flat().join(''),
            tableData: this.ruleForm.tableData,
          };

          // 修改
          if (!this.moldAddMore) {
            update(query).then(res => {
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
              this.$emit('closeDialog');
            });
          } else {
            // 新增
            add(query).then(res => {
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
              this.$emit('closeDialog');
            });
          }
        } else {
          // 校验失败：显示提示并滚动到第一个错误字段
          this.formError = '存在未完善的字段，请检查表格中的红色提示';

          this.$nextTick(() => {
            // 找到第一个错误字段并滚动到视图
            const firstError = document.querySelector('.el-form-item.is-error');
            if (firstError) {
              firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
          });
          return;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
// 优化表单字段样式
:deep(.el-table .el-form-item) {
  margin-bottom: 0; // 去掉默认边距
}

// 错误提示样式优化
:deep(.el-table .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>
