<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="6">
          <el-form-item label="模板编码:" prop="promodel.code">
            <el-input v-model="ruleForm.promodel.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="模板名称:" prop="promodel.name">
            <el-input v-model="ruleForm.promodel.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="模板类型:" prop="promodel.templateType">
            <el-select
              v-model="ruleForm.promodel.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="6">
          <el-form-item label="作业中心:" prop="promodel.workCenterId">
            <el-select
              v-model="ruleForm.promodel.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="6">
          <el-form-item label="镀种分类:" prop="promodel.platingType">
            <el-select
              v-model="ruleForm.promodel.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="6">
          <el-form-item label="优先级:" prop="promodel.priority">
            <el-input-number
              v-model="ruleForm.promodel.priority"
              controls-position="right"
              :min="1"
              :max="10"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注:" prop="promodel.remarks">
            <el-input v-model="ruleForm.promodel.remarks" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="process-box">
        <div class="process-left">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :default-expand-all="true"
            :expand-on-click-node="false"
            highlight-current-row
            :current-row-key="currentRowId"
          />
        </div>
        <div class="process-right">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="工序" name="1" v-if="treeLeave == 1"></el-tab-pane>
            <el-tab-pane label="项目" name="2" v-if="treeLeave == 2"></el-tab-pane>
          </el-tabs>
          <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 v-if="activeName == '1'" :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.tableData.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.tableData.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.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </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.tableData.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.tableData.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.tableData.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.tableData.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-table v-if="activeName == '2'" :data="ruleForm.tableData2" style="width: 100%">
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="trialNo" label="工序号">
              <template #header>
                <span><i style="color: red">*</i>工序号</span>
              </template>
              <template #default="scope">
                <el-form-item
                  :prop="`tableData2[${scope.$index}].trialNo`"
                  :rules="rules.tableData2.trialNo"
                  label-width="0"
                >
                  <el-input
                    v-model="scope.row.trialNo"
                    placeholder="请输入"
                    style="width: 100%"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="projectCode" label="检验项目">
              <template #header>
                <span><i style="color: red">*</i>检验项目</span>
              </template>
              <template #default="scope">
                <el-form-item
                  :prop="`tableData2[${scope.$index}].projectCode`"
                  :rules="rules.tableData2.projectCode"
                  label-width="0"
                >
                  <el-select
                    v-model="scope.row.projectCode"
                    placeholder="请选择"
                    clearable
                    filterable
                    @change="projectChange(scope.row, scope.$index)"
                  >
                    <el-option
                      v-for="(item, index) in projectOptions"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="projectStandard" label="检验标准">
              <template #header>
                <span><i style="color: red">*</i>检验标准</span>
              </template>
              <template #default="scope">
                <el-form-item
                  :prop="`tableData2[${scope.$index}].projectStandard`"
                  :rules="rules.tableData2.projectStandard"
                  label-width="0"
                >
                  <el-select
                    v-model="scope.row.projectStandard"
                    placeholder="请选择"
                    clearable
                    filterable
                    @change="standardChange(scope.row, scope.$index)"
                  >
                    <el-option
                      v-for="(item, index) in standardList"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="proHours" label="定额工时(分钟)">
              <template #header>
                <span><i style="color: red">*</i>定额工时(分钟)</span>
              </template>
              <template #default="scope">
                <el-form-item
                  :prop="`tableData2[${scope.$index}].proHours`"
                  :rules="rules.tableData2.proHours"
                  label-width="0"
                >
                  <el-input
                    v-model="scope.row.proHours"
                    placeholder="请输入"
                    style="width: 100%"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="prepareHours" label="准备工时(分钟)">
              <template #default="scope">
                <el-input
                  v-model="scope.row.prepareHours"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="formLoading">确 定</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 { getProject, getStandardList } from '@/api/processManagement/taskProcessing';
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 {
      currentRowId: '',

      treeData: [],
      defaultProps: {
        label: data => {
          // 父节点：显示 label
          if (data.label && data.processList) {
            return data.label;
          }
          // 工序节点：显示 processName
          if (data.processName) {
            return data.processName;
          }
          // 项目节点：显示 projectCode
          if (data.projectCode !== undefined) {
            return `项目-${data.projectCode}`;
          }
          return '未知节点';
        },
        children: data => {
          // 父节点 → 工序列表
          if (data.processList) {
            return data.processList;
          }
          // 工序节点 → 项目列表
          if (data.modelProjectList) {
            return data.modelProjectList;
          }
          return [];
        },
        isLeaf: data => {
          return !data.processList && !data.modelProjectList;
        },
      },
      activeName: '1',
      treeLeave: 1, //组织树选中层级
      formLoading: false,
      craftCodeList: [], //工艺能力列表
      formError: '', // 全局错误提示
      processTemplateList: [],
      platingTypeList: [],
      processList: [],
      openShow: false,
      //   tableData: [],

      ruleForm: {
        promodel: {
          code: '',
          name: '',
          workCenterId: '',
          platingType: '',
          priority: '',
        },

        // tableData: [],
        tableData2: [],
        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' }],
        promodel: {
          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',
          },
        ],
        tableData2: [
          {
            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: [], //作业中心列表
      projectOptions: [], //检验项目列表
      standardList: [], //检验标准列表
    };
  },
  mounted() {
    this.openShow = this.showDialog;

    // 加载所有数据
    Promise.all([
      this.getDictionary(),
      this.getProcessesTeams(),
      this.getProcessList(),
      this.getWorkCenterList(),
      this.getProcessAbilityList(),
      this.getProject(),
      this.getStandardList(),
    ])
      .then(() => {
        // 如果是修改模式，加载详情
        if (this.title == '修改') {
          return this.getDetail();
        }
      })
      .then(() => {
        this.treeData = [
          {
            label: '工序列表',
            processList: this.ruleForm.tableData,
          },
        ];
        // 默认选中第一个子节点
        this.$nextTick(() => {
          if (this.ruleForm.tableData.length > 0) {
            this.ruleForm.tableData = this.treeData[0].processList;
          }
        });
      });
  },
  methods: {
    // 获取检验项目名字
    projectChange(row, index) {
      let selectName = this.projectOptions.find(item => item.id == row.projectCode);
      this.form2.tableData2[index].projectName = selectName.name;
    },
    // 获取检验标准名字
    standardChange(row, index) {
      let selectName = this.standardList.find(item => item.id == row.projectStandard);
      this.form2.tableData2[index].projectStandardName = selectName.name;
    },
    getStandardList() {
      getStandardList().then(res => {
        this.standardList = res.data.data;
      });
    },
    getProject() {
      getProject({ size: 999999, current: 1 }).then(res => {
        this.projectOptions = res.data.data.records;
      });
    },

    // 组织树点击
    handleNodeClick(data) {
      if (data.label && data.processList) {
        // 点击父节点 "工序列表"
        this.activeName = '1';
        this.treeLeave = 1; // ← 关键修正
        this.ruleForm.tableData = [];
      } else if (data.processName && data.modelProjectList) {
        // 点击具体工序
        this.activeName = '2'; // 保持工序 Tab
        this.treeLeave = 2; // ← 关键修正
        this.ruleForm.tableData2 = data.modelProjectList;
      }
    },
    // 右侧tab切换
    handleClick(value) {
      console.log(999999, value);
      // this.form1.deleteIds = [];
      // this.form2.deleteIds = [];
      // this.form3.deleteIds = [];
      // this.form4.deleteIds = [];
    },
    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.promodel = res.data.data.dsProModelEntity;
        // 确保字段名匹配

        this.ruleForm.tableData = res.data.data.proDetailVOList;
        this.treeData = [{ label: '工序列表', processList: res.data.data.proDetailVOList }];
      });
    },
    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.tempId++;
      if (this.activeName == '1') {
        this.ruleForm.tableData.push({
          _tempId: this.tempId, // 临时唯一标识
          id: null,
          processNo: this.getProcessNo(this.ruleForm.tableData),
        });
      }
      if (this.activeName == '2') {
        this.ruleForm.tableData2.push({
          _tempId: this.tempId, // 临时唯一标识
          id: null,
          trialNo: this.getProcessNo(this.ruleForm.tableData2),
        });
      }
    },
    // 删除一行
    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) {
          this.formLoading = true;
          const pinyinArr = pinyin(this.ruleForm.name, {
            style: pinyin.STYLE_NORMAL, // 无声调（STYLE_TONE 带声调）
            heteronym: false, // 不考虑多音字
          });
          // / 1. 处理 promodel（仅保留基础字段）
          const promodel = {
            code: this.ruleForm.promodel.code,
            name: this.ruleForm.promodel.name,
            workCenterId: this.ruleForm.promodel.workCenterId,
            platingType: this.ruleForm.promodel.platingType,
            priority: this.ruleForm.promodel.priority,
            templateType: this.ruleForm.promodel.templateType,
            remarks: this.ruleForm.promodel.remarks,
            // 添加拼音字段
            modelNameStr: pinyin(this.ruleForm.promodel.name, {
              style: pinyin.STYLE_NORMAL,
              heteronym: false,
            })
              .flat()
              .join(''),
          };

          // 2. 处理工序表格数据（清理临时字段）
          const tableData = this.ruleForm.tableData.map(item => {
            const { _tempId, ...rest } = item; // 移除临时ID
            return rest;
          });

          let query = {
            promodel,
            tableData,
          };
          console.log('提交数据:', query);

          // 修改
          if (!this.moldAddMore) {
            // update(query)
            //   .then(res => {
            //     this.formLoading = false;
            //     this.$message({
            //       type: 'success',
            //       message: '操作成功!',
            //     });
            //     this.$emit('closeDialog');
            //   })
            //   .catch(err => {
            //     this.formLoading = false;
            //   });
          } else {
            // 新增
            // add(query)
            //   .then(res => {
            //     this.formLoading = false;
            //     this.$message({
            //       type: 'success',
            //       message: '操作成功!',
            //     });
            //     this.$emit('closeDialog');
            //   })
            //   .catch(err => {
            //     this.formLoading = false;
            //   });
          }
        } 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;
}
.process-box {
  display: flex;
  flex-direction: row;
  height: calc(100vh - 280px);
  .process-left {
    // padding: 20px;
    width: 240px;
    border: 1px solid #ccc;
  }
  .process-right {
    padding: 12px;
    flex: 1;
    border: 1px solid #ccc;
    border-left: 0;
    .table-btn {
      width: 100%;
      height: 50px;

      .table-btn-left {
        float: left;
      }

      .table-btn-right {
        float: right;
      }
    }
  }
}
</style>
