<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      v-model:search="search"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @sort-change="sortChange"
    >
      <template #menu-left>
        <el-button type="primary" @click="handleAdd" v-if="permission.InspectionTemplate_add"
          >新 增</el-button
        >
        <el-button type="primary" @click="handleSet" v-if="permission.InspectionTemplate_setType"
          >批量设置分类</el-button
        >
      </template>
      <template #menu="{ row }">
        <el-button type="text" @click="editRow(row)" v-if="permission.InspectionTemplate_edit"
          >修改</el-button
        >
        <el-button type="text" @click="deleteRow(row)" v-if="permission.InspectionTemplate_delete"
          >删除</el-button
        >
      </template>
      <template #userName="{ row }">
        {{ row.updateMan.userName }}
      </template>
    </avue-crud>
    <el-dialog :title="title" append-to-body v-model="showDialog" width="60%">
      <el-form ref="addForm" :rules="formRules" :model="formData" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板编码" prop="inspectionTemplateCode">
              <el-input
                v-model="formData.inspectionTemplateCode"
                placeholder="请输入模板编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入模板名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-input v-model="formData.priority" placeholder="请输入优先级"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="formData.category" filterable clearable>
                <el-option
                  v-for="item in typeData"
                  :key="item.id"
                  :label="item.dictValue"
                  :value="item.dictKey"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="title == '新增' || title == '修改'">
        <el-button type="primary" @click="insertEvent()">插入一行</el-button>
        <el-button plain type="danger" @click="remove">删除选择行</el-button>
      </div>
      <div style="margin-top: 20px">
        <el-table :data="tidList" @selection-change="selectionChangeProject" @select="selectChange">
          <el-table-column type="selection" width="55px"></el-table-column>
          <el-table-column label="项目编号" prop="inspectionTemplateCode">
            <template #default="scope">
              <el-input v-model="scope.row.itemCode" @blur="validateRow(scope.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="项目" prop="inspectionItemId">
            <template #default="scope">
              <el-select
                v-model="scope.row.inspectionItemId"
                @change="value => changeProject(value, scope.$index)"
                filterable
                clearable
              >
                <el-option
                  v-for="item in projectArr"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
              <!-- <el-input v-if="scope.row.tidName" v-model="scope.row.tidName"></el-input> -->
            </template>
          </el-table-column>
          <el-table-column label="标准" prop="standardId">
            <template #default="scope">
              <el-select v-model="scope.row.standardId" filterable clearable>
                <el-option
                  v-for="item in standardList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="handleSave">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="批量设置分类" append-to-body v-model="setDialog" width="500px">
      <el-form ref="typeForm" :rules="setRules" :model="setData">
        <el-form-item label="分类" prop="category">
          <el-select v-model="setData.category" filterable clearable>
            <el-option
              v-for="item in typeData"
              :key="item.id"
              :label="item.dictValue"
              :value="item.dictKey"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setDialog = false">取 消</el-button>
          <el-button type="primary" @click="sunmitType">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  addTemplate,
  getStandard,
  editTemplate,
  getItem,
  getDetail,
  getCategory,
  setType,
  deleteItem,
} from '@/api/productionTesting/InspectionTemplate';
import { mapGetters } from 'vuex';
export default {
  data() {
    return {
      data: [],
      loading: false,
      form: {},
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      title: '新增',
      search: {},
      showDialog: false,
      setDialog: false,
      formData: {},
      tidList: [],
      selectionProjectList: [],
      projectArr: [],
      dialogData: [],
      selectId: null,
      deleteTidArr: [],
      trialItemList: [
        '常温绝缘电阻检测',
        '常温耐压检测',
        '泄漏率检测',
        '低温密封性检测',
        '高温密封性检测',
        '潮湿绝缘电阻检测',
        '高温绝缘电阻检测',
        '承压检测',
        '探伤检测',
        '液氮存储检测',
        '煤油绝缘检测',
        '常温密封性检测',
        '温冲试验检测',
        '其他检测',
      ],
      setRules: {
        category: [{ required: true, trigger: 'blur', message: '请选择分类' }],
      },
      standardList: [],
      formRules: {
        inspectionTemplateCode: [{ required: true, message: '请输入模板编码', trigger: 'blur' }],
        name: [{ required: true, trigger: 'blur', message: '请输入模板名称' }],
      },
      selectionList: [],
      typeData: [
        // {label:'A',value:'A',id:'001'}
      ],
      setData: {},
      option: {
        tip: false,
        height: 'auto',
        calcHeight: 32,
        align: 'center',
        // size: 'medium',
        searchLabelWidth: 120,
        simplePage: true,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        selection: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        editBtnText: '修改',
        viewBtnText: '详情',
        labelWidth: 120,
        menuWidth: 120,
        dialogWidth: 1200,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        excelBtn: true,
        index: false,
        showOverflowTooltip: true,
        searchLabelPosition: 'left',
        searchLabelPosition: 'left',
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: 'left',
        gridBtn: false,
        searchMenuPosition: 'right',
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        column: [
          {
            label: '模板编码',
            prop: 'inspectionTemplateCode',
            addDisplay: false,
            editDisplay: false,
            span: 24,
            search: true,
            sortable: 'custom',
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入模板编码',
                trigger: 'click',
              },
            ],
          },
          {
            label: '模板名称',
            prop: 'name',
            addDisplay: false,
            sortable: 'custom',
            editDisplay: false,
            span: 24,
            search: true,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入模板名称',
                trigger: 'click',
              },
            ],
          },
          {
            label: '工序数',
            prop: 'processNum',
            addDisplay: false,
            editDisplay: false,
            span: 24,
            sortable: 'custom',
            search: true,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入工序数',
                trigger: 'click',
              },
            ],
          },
          {
            label: '优先级',
            prop: 'priority',
            addDisplay: false,
            editDisplay: false,
            span: 24,
            sortable: 'custom',
            search: false,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入优先级',
                trigger: 'click',
              },
            ],
          },
          {
            label: '分类',
            prop: 'category',
            type: 'select',
            addDisplay: false,
            editDisplay: false,
            width: 150,
            span: 24,
            sortable: 'custom',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入分类',
                trigger: 'click',
              },
            ],
            dicUrl: '/api/blade-system/dict/dictionary?code=InspectionTemplate-Category',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
          },
          {
            label: '修改人',
            prop: 'updateUserName',
            addDisplay: false,
            editDisplay: false,
            span: 24,
            search: true,
            sortable: 'custom',
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入修改人',
                trigger: 'click',
              },
            ],
          },
          {
            label: '修改时间',
            prop: 'updateTime',
            type: 'date',
            sortable: 'custom',
            addDisplay: false,
            editDisplay: false,
            span: 24,
            // search:true,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入修改时间',
                trigger: 'click',
              },
            ],
          },
          {
            label: '修改时间',
            prop: 'updateTime',
            type: 'date',
            searchRange: true,
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            sortable: 'custom',
            addDisplay: false,
            editDisplay: false,
            span: 24,
            hide: true,
            search: true,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入修改时间',
                trigger: 'click',
              },
            ],
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['permission']),
  },
  mounted() {
    this.getItemList();
    this.getCategoryList();
    this.getStandardList();
  },
  methods: {
    // 字段排序
    sortChange({ prop, order }) {
      console.log('perop---------', prop);
      this.query.descs = undefined;
      this.query.ascs = undefined;
      const orderByField = prop.replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase();
      const orderByFieldKey = order === 'descending' ? 'descs' : 'ascs';
      this.query[orderByFieldKey] = !prop ? undefined : orderByField;
      console.log('query---------', this.query);
      this.onLoad(this.page, this.query);
    },
    getStandardList() {
      getStandard().then(res => {
        this.standardList = res.data.data;
      });
    },
    getCategoryList() {
      getCategory().then(res => {
        this.typeData = res.data.data;
      });
    },
    getItemList() {
      getItem().then(res => {
        this.projectArr = res.data.data;
      });
    },
    // 校验单行（与上一行比较）
    // 校验指定行（向上 + 向下）
    validateRow(index) {
      const digitOnly = /^\d+$/;
      const row = this.tidList[index];
      const id = (row?.itemCode || '').trim();

      // 清除当前行错误（先清后设）
      // this.$delete(this.errors, index);

      // 如果当前行为空，不校验（或根据需求设为必填）
      if (!id) return;

      // 格式校验
      if (!digitOnly.test(id)) {
        // this.$set(this.errors, index, '编号必须为纯数字');
        this.$message.error(`第【${index + 1}】行编号必须为纯数字`);
        return;
      }

      const currentNum = Number(id);

      // 🔼 向上校验：当前行 vs 上一行
      if (index > 0) {
        const prevId = (this.tidList[index - 1]?.itemCode || '').trim();
        if (prevId) {
          if (!digitOnly.test(prevId)) {
            // this.$set(this.errors, index, '上一行编号格式无效');
            this.$message.error(`第【${index + 1}】行编号格式无效`);
            return;
          }
          if (currentNum <= Number(prevId)) {
            // this.$set(
            //   this.errors,
            //   index,
            //   `必须大于上一行（${prevId}）`
            // );
            this.$message.error(`第【${index + 1}】行编号必须大于上一行`);
            return;
          }
        }
      }

      // 🔽 向下校验：下一行 vs 当前行
      if (index < this.tidList.length - 1) {
        const nextId = (this.tidList[index + 1]?.itemCode || '').trim();
        if (nextId) {
          if (!digitOnly.test(nextId)) {
            // 下一行格式错，但错误应标在下一行
            // this.$set(this.errors, index + 1, '编号必须为纯数字');
            this.$message.error(`第【${index + 1}】行编号必须为纯数字`);
          } else {
            const nextNum = Number(nextId);
            if (nextNum <= currentNum) {
              // this.$set(
              //   this.errors,
              //   index + 1,
              //   `必须大于上一行（${id}）`
              // );
              this.$message.error(`第【${index + 2}】行编号必须大于上一行`);
            } else {
              // 如果之前有错，现在合法了，清除下一行错误
              // this.$delete(this.errors, index + 1);
            }
          }
        } else {
          // 下一行为空，清除其可能的历史错误
          // this.$delete(this.errors, index + 1);
        }
      }
    },
    selectionChangeProject(list) {
      this.selectionProjectList = list;
    },
    selectChange(list, val) {
      val._select = !val._select;
    },
    insertEvent(row = -1) {
      const num = this.tidList.length;
      let tidCode = (num + 1) * 5;
      if (tidCode.toString().length == 1) {
        tidCode = '000' + tidCode;
      } else if (tidCode.toString().length == 2) {
        tidCode = '00' + tidCode;
      } else if (tidCode.toString().length == 3) {
        tidCode = '0' + tidCode;
      } else if (tidCode.toString().length == 4) {
        tidCode = '' + tidCode;
      }
      const record = { itemCode: tidCode, _select: false };
      this.tidList.push(record);
    },
    // 切换项目
    changeProject(value, index) {
      this.tidList[index].tidName = this.projectArr.find(item => item.oneData == value).twoData;
    },
    remove() {
      let arr = this.tidList.filter(item => item._select);
      if (arr.length != 0) {
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          if (this.selectId) {
            console.log('111111111111111');
            let deleteData = this.tidList.filter(item => item._select);
            console.log('deleteData---------------', deleteData);
            this.deleteTidArr = deleteData.filter(item => item.tidId);
          }
          let deleteArr = this.tidList.filter(item => !item._select);
          this.tidList = deleteArr;
        });
      } else {
        this.$message.error('请至少选择一条数据进行操作！');
      }
    },
    // 输入框失焦时触发校验
    handleIdBlur(index) {
      this.validateRow(index);
    },

    // 全量校验（提交用）
    validateAll() {
      const newErrors = {};
      const digitOnly = /^\d+$/;

      for (let i = 0; i < this.tidList.length; i++) {
        const id = (this.tidList[i]?.itemCode || '').trim();
        if (!id) continue; // 或设为必填

        if (!digitOnly.test(id)) {
          // newErrors[i] = '编号必须为纯数字';
          this.$message.error(`第【${i + 1}】行编号必须为纯数字`);
          break;
        }

        const num = Number(id);

        // 检查上一行
        if (i > 0) {
          const prevId = (this.tidList[i - 1]?.itemCode || '').trim();
          if (prevId) {
            if (!digitOnly.test(prevId)) {
              // newErrors[i] = '上一行编号格式无效';
              this.$message.error(`第【${i + 1}】行编号格式无效`);
              continue;
            }
            if (num <= Number(prevId)) {
              // newErrors[i] = `必须大于上一行（${prevId}）`;
              this.$message.error(`第【${i + 1}】行编号必须大于上一行`);
              continue;
            }
          }
        }

        // 检查下一行（其实全量校验只需检查“当前 > 上一行”即可保证全局有序）
        // 所以这里可简化：只校验 i > i-1 即可
      }

      // // 更简洁的全量校验：遍历一次，确保递增
      // let lastNum = -1;
      // for (let i = 0; i < this.tidList.length; i++) {
      //   const id = (this.tidList[i]?.id || '').trim();
      //   if (!id) continue;
      //   if (!digitOnly.test(id)) {
      //     // newErrors[i] = '编号必须为纯数字';
      //     this.$message.error(`第【${i + 1}】行编号必须为纯数字`)
      //     break;
      //   }
      //   const num = Number(id);
      //   if (num <= lastNum) {
      //     // newErrors[i] = i === 0 ? '编号无效' : `必须大于上一行（${this.tidList[i - 1].id}）`;
      //     this.$message.error(i === 0 ? '编号无效' : `第【${i + 1}】行编号必须为纯数字`)
      //     break;
      //   }
      //   lastNum = num;
      // }

      // this.errors = newErrors;
      return Object.keys(newErrors).length === 0;
    },
    handleSave() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.validateAll()) {
            let params = {
              inspectionTemplateCode: this.formData.inspectionTemplateCode,
              name: this.formData.name,
              priority: this.formData.priority,
              category: this.formData.category,
              detailList: this.tidList.length > 0 ? this.tidList : [],
            };
            if (this.title == '新增') {
              addTemplate(params).then(res => {
                if (res.data.code == 200) {
                  this.$message.success('新增成功');
                  this.showDialog = false;
                  this.onLoad();
                }
              });
            } else {
              params.id = this.formData.id;
              editTemplate(params).then(res => {
                if (res.data.code == 200) {
                  this.$message.success('修改成功');
                  this.showDialog = false;
                  this.onLoad();
                }
              });
            }
          }
          // // if(this.tidList)
          // const deleteIdArr = []
          // this.deleteTidArr.map(item =>{
          //   deleteIdArr.push(item.tidId)
          // })
          // console.log('dele----------------------',deleteIdArr)
          // console.log('tidList----------------------',this.tidList)
          // // let filteredObjArr = this.tidList.filter(item => !deleteIdArr.some(val => val === item.id));
          // // console.log('filteredObjArr====================',filteredObjArr)
          // let params = {
          //   deleteIds:deleteIdArr,
          //   dsTrialitemModel:this.formData,
          //   list:this.tidList
          // }

          // console.log('paramd--------------------',params)
        }
      });
    },

    sunmitType() {
      this.$refs.typeForm.validate(valid => {
        if (valid) {
          this.selectionList.map(item => {
            item.category = this.setData.category;
          });

          setType(this.selectionList).then(res => {
            if (res.data.code == 200) {
              this.$message.success('设置成功');
              this.setDialog = false;
              this.onLoad();
            }
          });
          console.log('slee=================', this.selectionList);
        }
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    deleteRow(val) {
      this.$confirm('确定删除该条数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteItem({ ids: val.id }).then(res => {
          if (res.data.code == 200) {
            this.$message.success('删除成功');
            this.onLoad();
          }
        });
      });
    },
    handleAdd() {
      this.showDialog = true;
      this.title = '新增';
      this.formData = {};
      this.tidList = [];
      this.deleteTidArr = [];
    },
    handleSet() {
      if (this.selectionList.length == 0) {
        this.$message.error('请至少选择一条数据');
      } else {
        this.setDialog = true;
      }
    },
    editRow(row) {
      getDetail({ id: row.id }).then(res => {
        this.formData = res.data.data;
        this.title = '修改';
        this.tidList = res.data.data.detailList;
        if (this.tidList.length > 0) {
          this.tidList.map(item => {
            item.inspectionItemId = item.inspectionItemId?item.inspectionItemId+'':item.inspectionItemId
            item.standardId = item.standardId?item.standardId+'':item.standardId
          });
        }
        this.showDialog = true;
      });
    },
    onLoad() {
      this.loading = true;
      getList({
        current: this.page.currentPage,
        size: this.page.pageSize,
        ...this.query,
        inspectionTemplateCode: this.query.inspectionTemplateCode,
        name: this.query.name,
        processNum: this.query.processNum,
        category: this.query.category,
        updateUserRealName: this.query.updateUserRealName,
        updateTimeStart:
          this.query.updateTime && this.query.updateTime.length > 0 && this.query.updateTime[0],
        updateTimeEnd:
          this.query.updateTime && this.query.updateTime.length > 0 && this.query.updateTime[1],
      }).then(res => {
        this.data = res.data.data.records;
        this.page.total = res.data.data.total;
        this.loading = false;
      });
    },
  },
};
</script>

<style>
</style>