<template>
  <basic-container>
    <!-- 薪资维护标准 -->
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      v-model:page="page"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :span-method="spanMethod"
      :before-open="beforeOpen"
      @sort-change="sortChange"
    >
      <template #menu-left>
        <el-button type="danger" @click="handleDelete" v-if="permission.salaryStandard_delete"
          >删除</el-button
        >
      </template>
      <template #menu-right>
      <el-button type="primary"  @click="handleImport" v-if="permission.salaryStandard_import"
          >导入
        </el-button>
      </template>
      <template #standardType="scope">
        <el-tag v-if="scope.row.standardType == '2'" type="success">军品</el-tag>
        <el-tag v-if="scope.row.standardType == '3'" type="danger">非军品</el-tag>
        <el-tag v-if="scope.row.standardType == '1'">通用</el-tag>
      </template>
      <!-- 工序选择 -->
      <template #processId-form="{ type, disabled }">
        <el-select 
          v-model="form.processId"
          remote
          filterable
          :remote-method="getPpsList"
          placeholder="请选择工序"
          @change="changeProcess"
        >
          <el-option v-for="item in ppsData" :key="item.id"
            :label="`${item.code}-${item.name}`"
            :value="item.id"
          ></el-option>
        </el-select>
      </template>
      <!-- 零件号 -->
      <template #partNo-form="{ type, disabled}">
        <el-input v-model="form.partNo" placeholder="多个零件号以空格分隔"></el-input>
      </template>
      <!-- 阶梯上下限 -->
      <template #step-form="{type,disabled}">
        <el-select v-model="form.stepType" style="width:30%;" @change="changeType">
          <el-option label="无补贴金额" value="1"></el-option>
          <el-option label="固定补贴金额" value="2"></el-option>
          <el-option label="阶梯补贴金额" value="3"></el-option>
        </el-select>
        <el-input style="width:68%;margin-left:1%;" :disabled="form.stepType != 3" v-model="form.step" placeholder="阶梯以空格分隔，如：10 20 30"></el-input>
      </template>
      <!-- 阶梯结算价 -->
      <template #stepSettlementPrice-form="{type,disabled}">
        <!-- <el-select></el-select> -->
        <el-input v-model="form.stepSettlementPrice" :disabled="form.stepType == 1" placeholder="结算价以空格分隔,如:5 10 15 20"></el-input>
      </template>
      <!-- 阶梯结算单位 -->
      <template #stepSettlementUnit-form="{type,disabled}">
        <el-select v-model="form.stepSettlementUnit" placeholder="请选择阶梯结算单位" :disabled="form.stepType == 1">
          <el-option label="批" value="1"></el-option>
          <el-option label="倍" value="2"></el-option>
        </el-select>
      </template>
      <!-- 阶梯单位 -->
      <template #stepUnit-form="{type,disabled}">
        <el-select v-model="form.stepUnit" placeholder="请选择阶梯单位" :disabled="form.stepType == 1">
          <el-option label="件" value="1"></el-option>
          <el-option label="面积" value="2"></el-option>
        </el-select>
      </template>
    </avue-crud>
    <!-- 导入 -->
    <basic-import v-if="isShowImport" title="导入" :isShow="isShowImport"
      templateUrl="/blade-desk/bsSalaryStandard/download-excel-template"
      templateName="工资维护标准模板.xls"
      importUrl="/blade-desk/bsSalaryStandard/import-excel"
      @closeDialog="closeDialog"></basic-import>
  </basic-container>
</template>

<script>
import basicImport from '@/components/basic-import/main.vue'
import {getProcessList,getList,deleteTable,addTable } from "@/api/performanceManagement/salaryManagement"
import { mapGetters } from 'vuex';
export default {
  components: {
    basicImport,
  },
  data() {
    return {
      isShowImport:false,
      loading: false,
      data: [],
      form: {},
      query:{},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      ppsData:[],
      spanArr: [
        { prop: "standardType", span: [] },
        { prop: "processName", span: [] },
        { prop: "partNo", span: [] },
        { prop: "settlementPrice", span: [] },
        { prop: "settlementUnit", span: [] },
      ],
      selectionList: [],
      option: {
        height: "auto",
        calcHeight: 32,
        tip: false,
        simplePage: true,
        searchShow: true,
        searchMenuSpan: 18,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        editBtnText: "修改",
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        viewBtnText: "详情",
        labelWidth: 120,
        searchLabelWidth: 'auto',
        menuWidth: 80,
        dialogWidth: 1200,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        columnSort: true,
        excelBtn: true,
        columnSort: true,
        index: false,
        showOverflowTooltip: true,
        searchLabelPosition: "left",
        searchLabelPosition: "left",
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: "center",
        gridBtn: false,
        searchMenuPosition: "right",
        align: "center",
        column: [
          {
            label: "规则类型",
            prop: "standardType",
            type: "select",
            search: false,
            sortable: 'custom',
            overHidden: true,
            width: 100,
            rules: [
              {
                required: true,
                message: "请输入是否军品",
                trigger: "blur",
              },
            ],
            dicData: [
              { label: "军品", value: '2' },
              { label: "非军品", value: '3' },
              { label: "通用", value: '1' },
            ],
          },
          {
            label: "工序",
            prop: "processName",
            search: true,
            sortable: 'custom',
            overHidden: true,
            addDisplay: false,
            editDisplay: false,
            width: 100,
            rules: [
              {
                required: true,
                message: "请输入工序",
                trigger: "blur",
              },
            ],
          },
          {
            label: "工序",
            prop: "processId",
            search: false,
            sortable: 'custom',
            hide:true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            width: 100,
            rules: [
              {
                required: true,
                message: "请选择工序",
                trigger: "blur",
              },
            ],
          },
          {
            label: "零件号",
            prop: "partNo",
            search: false,
            sortable: 'custom',
            overHidden: true,
            minWidth: 160,
            // rules: [
            //     {
            //         required: true,
            //         message: '请输入其他',
            //         trigger: 'blur',
            //     },
            // ],
          },
          {
            label: "工人结算价",
            prop: "settlementPrice",
            type: "number",
            search: false,
            sortable: 'custom',
            overHidden: true,
            width: 110,
            rules: [
              {
                required: true,
                message: "请输入工人结算价",
                trigger: "blur",
              },
            ],
          },
          {
            label: "工人结算单位",
            prop: "settlementUnit",
            type: "select",
            search: false,
            sortable: 'custom',
            overHidden: true,
            width: 120,
            rules: [
              {
                required: true,
                message: "请输入工人结算单位",
                trigger: "blur",
              },
            ],
            dicData: [
              { label: "件", value: '1' },
              { label: "批", value: '2' },
              { label: "面积", value: '3' },
            ],
          },
          {
            label: "阶梯上下限",
            prop: "step",
            hide:true,
            search: false,
            sortable: 'custom',
            overHidden: true,
            width: 100,
            addDisplay: true,
            editDisplay: true,
            rules: [
                {
                    required: false,
                    message: '请填写阶梯上下限',
                    trigger: 'blur',
                },
            ],
          },
          {
            label: "阶梯下限",
            prop: "minStep",
            type: "number",
            search: false,
            sortable: 'custom',
            overHidden: true,
            width: 95,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: "阶梯上限",
            prop: "maxStep",
            search: false,
            type: "number",
            sortable: 'custom',
            overHidden: true,
            addDisplay: false,
            editDisplay: false,
            width: 95,
          },
          {
            label: "阶梯单位",
            prop: "stepUnit",
            type: "select",
            search: false,
            sortable: 'custom',
            overHidden: true,
            width: 100,
            dicData: [
              { label: "件", value: '1' },
              { label: "面积", value: '2' },
            ],
            rules: [
                {
                    required: false,
                    message: '请选择阶梯单位',
                    trigger: 'blur',
                },
            ],
          },
          {
            label: "阶梯结算价",
            prop:"stepSettlementPrice",
            search: false,
            sortable: 'custom',
            overHidden: true,
            hide: true,
            width: 110,
            addDisplay: true,
            editDisplay: true,
            rules: [
                {
                    required: false,
                    message: '请输入阶梯结算价',
                    trigger: 'blur',
                },
            ],
          },
          {
            label: "阶梯结算价",
            prop: "price",
            type: "number",
            search: false,
            sortable: 'custom',
            overHidden: true,
            addDisplay: false,
            editDisplay: false,
            width: 110,
          },
          {
            label: "阶梯结算单位",
            prop: "stepSettlementUnit",
            type: "select",
            search: false,
            sortable: 'custom',
            overHidden: true,
            width: 120,
            dicData: [
              { label: "批", value: '1' },
              { label: "倍", value: '2' },
            ],
            rules: [
                {
                    required: false,
                    message: '请选择阶梯结算单位',
                    trigger: 'blur',
                },
            ],
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['permission']),
  },
  mounted() {
    this.option.addBtn = this.permission.salaryStandard_add ? true : false;
    this.option.editBtn = this.permission.salaryStandard_edit ? true : false;
  },
  methods: {
    // 表格排序
    sortChange({ prop, order }) {
      console.log('prop-------------',prop)
      if (!prop) {
        // 如果取消排序，清空排序参数
        this.query.orderByField = undefined;
        // this.query.isAsc = undefined;
        this.query.asc = undefined;
      } else {
        const orderByField = prop.replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase();
        console.log('orderByField-------------',orderByField)

        this.query.orderByField = orderByField == 'MIN_STEP' ? 'minstep' : orderByField == 'MAX_STEP' ? 'maxstep' : orderByField;
        // this.query.isAsc = order === 'ascending' ? true : false;
        this.query.asc = order === 'ascending' ? true : false;
      }
      // // 重新加载数据
      this.onLoad(this.page, this.query);
    },
    getPpsList(query){
      console.log('form============',this.form)
      getProcessList({
        current:1,
        size:300,
        name:query
      }).then(res =>{
        this.ppsData = res.data.data.records
        if(this.form.processId){
          let tmp = this.ppsData.find(item => item.id == this.form.processId)
          if(!tmp){
            this.ppsData.unshift({
              name:this.form.processName,
              code:this.form.ppsCode,
              id:this.form.processId
            })
          }
        }
      })
    },
    changeProcess(val){
      this.form.processName = this.ppsData.find(item => item.id == val).name
      this.form.ppsCode = this.ppsData.find(item => item.id == val).code
    },
    changeType(val){
      if(val == 1){
        this.form.step = ''
        this.form.stepSettlementPrice = ''
        this.form.stepSettlementUnit = ''
        this.form.stepUnit = ''
        this.option.column.find(item => item.prop == "stepUnit").rules[0].required = false
        this.option.column.find(item => item.prop == "step").rules[0].required = false
        this.option.column.find(item => item.prop == "stepSettlementPrice").rules[0].required = false
        this.option.column.find(item => item.prop == "stepSettlementUnit").rules[0].required = false
      }else if(val == 2){
        this.form.step = 0
        this.option.column.find(item => item.prop == "step").rules[0].required = false
        this.option.column.find(item => item.prop == "stepUnit").rules[0].required = true
        this.option.column.find(item => item.prop == "stepSettlementPrice").rules[0].required = true
        this.option.column.find(item => item.prop == "stepSettlementUnit").rules[0].required = true
      }else{
        this.option.column.find(item => item.prop == "step").rules[0].required = true
        this.option.column.find(item => item.prop == "stepUnit").rules[0].required = true
        this.option.column.find(item => item.prop == "stepSettlementPrice").rules[0].required = true
        this.option.column.find(item => item.prop == "stepSettlementUnit").rules[0].required = true
      }
    },
    rowCalc() {
      console.log('spanArr===========',this.spanArr)
      this.spanArr.forEach((ele, index) => {
        let parent;
        if (index !== 0) parent = this.spanArr[ele.parent || index - 1].span;
        ele.span = this.rowSpan(ele.prop, parent);
      });
    },
    rowSort(list) {
      let propList = this.spanArr.map((ele) => ele.prop);
      this.spanArr.forEach((ele, index) => {
        let key = ele.prop;
        console.log('data------------',this.data)
        this.data = this.data.sort((a, b) => {
          let flag = true;
          for (let i = 0; i < index; i++) {
            let prop = this.spanArr[i].prop;
            flag = flag && a[prop] == b[prop];
          }
          if (flag) {
            if (a[key] < b[key]) {
              return 1;
            } else if (a[key] > b[key]) {
              return -1;
            }
            return 0;
          }
          return 0;
        });
      });
    },
    rowSpan(key, parent) {
       let list = [];
      let position = 0;
      
      // 遍历数据进行合并计算
      this.data.forEach((item, index) => {
        if (index === 0) {
          // 第一行，初始化合并数为1
          list.push(1);
          position = 0; 
        } else {
          const prevItem = this.data[index - 1];
          const currentItem = item;

          // 核心修改点：
          // 1. 判断当前列的值是否相同: currentItem[key] === prevItem[key]
          // 2. 判断是否属于同一个分组(即ID是否相同): currentItem.id === prevItem.id
          //    注意：请确保你的数据对象中有 'id' 字段，如果没有，请替换为实际的分组字段名
          const isSameValue = currentItem[key] === prevItem[key];
          const isSameGroup = currentItem.id === prevItem.id; 

          // 只有当【值相同】且【属于同一组(ID相同)】时，才尝试合并
          if (isSameValue && isSameGroup) {
            // 如果有父级合并逻辑（多列联动合并），需检查父级是否在同一合并块中
            if (parent && parent[index] !== 0) {
              // 父级断开了，子级也必须断开
              list.push(1);
              position = index;
            } else {
              // 继续合并
              list[position] += 1;
              list.push(0);
            }
          } else {
            // 值不同 或 ID不同，断开合并，重新开始计数
            list.push(1);
            position = index;
          }
        }
      });
      return list;

      // let list = [];
      // let position = 0;
      // this.data.forEach((item, index) => {
      //   if (index === 0) {
      //     list.push(1);
      //     let position = 0;
      //   } else {
      //     if (this.data[index][key] === this.data[index - 1][key]) {
      //       if (parent && parent[index] !== 0) {
      //         list.push(1);
      //         position = index;
      //       } else {
      //         list[position] += 1;
      //         list.push(0);
      //       }
      //     } else {
      //       list.push(1);
      //       position = index;
      //     }
      //   }
      // });
      // return list;
    },
    spanMethod({ row, column, rowIndex, columnIndex }) {
      for (let i = 0; i < this.spanArr.length; i++) {
        const ele = this.spanArr[i];
        if (column.property == ele.prop) {
          const _row = ele.span[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col,
          };
        } else if (columnIndex == 0) {
          const _row = ele.span[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col,
          };
        } else if (columnIndex == 11) {
          const _row = ele.span[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col,
          };
        }
      }
    },
    selectionChange(val) {
      this.selectionList = val;
    },
    beforeOpen(done, type){
      if(type == 'add'){
        this.form = {
          ...this.form,
          settlementUnit:'1'
        }
        done()
      }else{
        done()
      }
    },
    // 新增数据
    rowSave(row, done, loading) {
      console.log('row---------------',row)
      if(row.stepType == 2){
        let stepSettlementPriceArr = row.stepSettlementPrice.split(' ')
        if(stepSettlementPriceArr.length > 1){
          this.$message.error('阶梯结算价与阶梯不一致')
          loading()
          return
        }
      }else if(row.stepType == 3){
        let stepArr = row.step.split(' ')
        let stepSettlementPriceArr = row.stepSettlementPrice.split(' ')
        stepArr = stepArr.filter(item => item != '')
        stepSettlementPriceArr = stepSettlementPriceArr.filter(item => item != '')
        console.log('stepArr',stepArr)
        console.log('stepSettlementPriceArr',stepSettlementPriceArr.length)
        if(stepArr.length > 0 && stepSettlementPriceArr.length > 0 && stepSettlementPriceArr.length - stepArr.length != 1){
          this.$message.error('阶梯结算价与阶梯不一致')
          loading()
          return
        }
        // 2. 新增校验：阶梯值必须递增
        for (let i = 0; i < stepArr.length - 1; i++) {
          if (stepArr[i+1] <= stepArr[i]) {
            this.$message.error('【阶梯上下限】配置错误：后一个阶梯值必须大于前一个阶梯值');
            loading();
            return;
          }
        }
      }
      addTable(row).then(res =>{
        if(res.data.code == 200){
          this.$message.success('新增成功')
          this.onLoad()
          done()
        }
      }).catch(err =>{
        loading()
        // done();
      })
    },
    // 修改数据
    rowUpdate(row, index, done, loading) {
      console.log('row---------------',row)
      if(row.stepType == 2){
        let stepSettlementPriceArr = row.stepSettlementPrice.split(' ')
        if(stepSettlementPriceArr.length > 1){
          this.$message.error('【固定补贴金额】时,阶梯结算价应只有一个')
          loading()
          return
        }
      }else if(row.stepType == 3){
        let stepArr = row.step.split(' ')
        let stepSettlementPriceArr = row.stepSettlementPrice.split(' ')
        console.log('stepArr',stepArr.length)
        console.log('stepSettlementPriceArr',stepSettlementPriceArr.length)
        if(stepArr.length > 0 && stepSettlementPriceArr.length > 0 && stepSettlementPriceArr.length - stepArr.length != 1){
          this.$message.error('【阶梯补贴金额】时,阶梯结算价应比阶梯上下限数量多一个')
          loading()
          return
        }
        // 2. 新增校验：阶梯值必须递增
        for (let i = 0; i < stepArr.length - 1; i++) {
          if (stepArr[i+1] <= stepArr[i]) {
            this.$message.error('【阶梯上下限】配置错误：后一个阶梯值必须大于前一个阶梯值');
            loading();
            return;
          }
        }
      }
      addTable(row).then(res =>{
        if(res.data.code == 200){
          this.$message.success('修改成功')
          this.onLoad()
          done()
        }
      }).catch(err =>{
        loading()
        // done();
      })
    },
    // 批量删除
    handleDelete() {
      if (this.selectionList.length == 0) {
        this.$message.error("请先选择数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteTable({
          ids:this.selectionList.map(item => item.id).join(",")
        }).then(res =>{
          if(res.data.code == 200){
            this.$message.success('删除成功')
            this.onLoad()
          }
        })
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    searchReset() {
      this.query = {};
      this.treeDeptId = "";
      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();
    },
     // 点击导入按钮
    handleImport() {
      this.isShowImport = true
    },
    closeDialog(val){
      this.isShowImport = false
      if(val){
        this.onLoad()
      }
    },
    onLoad() {
      this.loading = true
      getList({
        current:this.page.currentPage,
        size:this.page.pageSize,
        ...this.query
      }).then(res =>{
        res.data.data.records.forEach(item => {
          item.minStep = item.minStep == -1 ? '' : item.minStep
          item.maxStep = item.maxStep == -1 ? '' : item.maxStep
          item.stepSettlementPrice = item.stepSettlementPrice == -1 ? '' : item.stepSettlementPrice
          item.price = item.price == -1 ? '' : item.price
        })
        this.data = res.data.data.records
        this.page.total = res.data.data.total
        // this.$nextTick(() =>{
          this.rowSort();
          this.rowCalc();
        // })
        this.loading = false
      })

      // this.data = [
      //   {
      //     countUnit: 1,
      //     stepUnit: "件",
      //     createTime: "2023-12-07 20:57:12",
      //     keyValue: 2,
      //     maxStep: 10,
      //     standardType: 1,
      //     minStep: 0,
      //     settlementUnit: 1,
      //     stepSettlementUnit: "批",
      //     bound: "10,20",
      //     stepSettlementPrice: "10,20,30",
      //     twlId: 2,
      //     partNo: "21E8-0041",
      //     twlType: 2,
      //     twlTypeTitle: "异性壳体",
      //     twlUnit: 1,
      //     settlementUnit: "件(根)",
      //     settlementPrice: 3.0,
      //     xplSettlement: 10.0,
      //   },
      //   {
      //     bsProcedureSet: null,
      //     countUnit: 1,
      //     stepUnit: "件",
      //     createTime: "2023-12-07 20:57:12",
      //     keyValue: 2,
      //     maxStep: 20,
      //     standardType: 1,
      //     minStep: 10,
      //     settlementUnit: 1,
      //     stepSettlementUnit: "批",
      //     twlId: 2,
      //     partNo: "21E8-0041",
      //     twlType: 2,
      //     bound: "10,20",
      //     stepSettlementPrice: "10,20,30",
      //     twlTypeTitle: "异性壳体",
      //     twlUnit: 1,
      //     settlementUnit: "件(根)",
      //     settlementPrice: 3.0,
      //     xplSettlement: 20.0,
      //   },
      //   {
      //     bsProcedureSet: null,
      //     countUnit: 1,
      //     stepUnit: "件",
      //     createTime: "2023-12-07 20:57:12",
      //     keyValue: 2,
      //     maxStep: null,
      //     standardType: 1,
      //     minStep: 20,
      //     settlementUnit: 1,
      //     stepSettlementUnit: "批",
      //     twlId: 2,
      //     partNo: "21E8-0041",
      //     bound: "10,20",
      //     stepSettlementPrice: "10,20,30",
      //     twlType: 2,
      //     twlTypeTitle: "异性壳体",
      //     twlUnit: 1,
      //     settlementUnit: "件(根)",
      //     settlementPrice: 3.0,
      //     xplSettlement: 30.0,
      //   },
      //   {
      //     countUnit: null,
      //     stepUnit: null,
      //     createTime: "2023-12-07 20:23:57",
      //     keyValue: 3,
      //     maxStep: null,
      //     standardType: 2,
      //     minStep: null,
      //     settlementUnit: null,
      //     stepSettlementUnit: null,
      //     twlId: 3,
      //     partNo: null,
      //     twlType: 1,
      //     twlTypeTitle: "工序",
      //     twlUnit: 2,
      //     settlementUnit: "批",
      //     settlementPrice: 22.0,
      //     xplSettlement: null,
      //   },
      //   {
      //     countUnit: null,
      //     stepUnit: null,
      //     createTime: "2023-12-07 20:23:57",
      //     keyValue: 3,
      //     maxStep: null,
      //     standardType: 3,
      //     minStep: null,
      //     settlementUnit: null,
      //     stepSettlementUnit: null,
      //     twlId: 4,
      //     partNo: null,
      //     twlType: 1,
      //     twlTypeTitle: "工序",
      //     twlUnit: 2,
      //     settlementUnit: "批",
      //     settlementPrice: 22.0,
      //     xplSettlement: null,
      //   },
      // ];
      // this.page.total = this.data.length;
    },
  },
};
</script>

<style></style>
