luckeySheet

<template>

  <div class="sheet-container">

      <div v-if="loadingForm" style="

          margin:0px;

          padding:0px;

          height: calc(100vh - 135px);

          width: 100%;

          position: absolute;

          background: rgba(211, 215, 218, 0.2);

      ">

      <a-spin class="spin-box" style="height: 100%;width: 85%;" size="large"  tip="数据计算中..." />

      <!-- <i class="el-icon-loading" style="font-size: 50px;color: #7ab8cf; text-align: center; position: absolute;left: 40%;

          top: 50%;

      "></i>

      <span style="font-size: 15px;text-align: center; position: absolute;left: 39%;top: 60%;">数据计算中...</span> -->

      </div>

      <div id="luckysheet"></div>

      <el-dialog title="申请描述(选填)" :visible.sync="dialogFormVisible" width="30%">

        <el-input v-model="applyInfo" placeholder="请输入内容" :rows="4"  type="textarea" autocomplete="off"/>

        <div slot="footer" class="dialog-footer">

          <el-button type="primary" @click="confirmSave">确 定</el-button>

        </div>

    </el-dialog>

  </div>

</template>

<script>

import { cloneDeep } from "lodash";

import TitleData from "./titleData/data.json";

import TitleData22 from "./titleData/data2.js";

import {

  getAnnualList,

  updateTableData,

  deleteRowList,

  saveBatchListNewToCheck,

  getCheckList

} from "@/api/ghssgl/ghssgl";

export default {

  props: {

     roleFlag:{

      required:true,

      type:Number

    },

    index: {

      type: Number,

      required: true,

    },

    type: {

      type: String,

      required: true,

    },

    searchValue: {

      type: Object,

      required: true,

    },

    setCompleteState: {

      type: Function,

      required: true

    },

     departMnun: {

      type: String,

      required: true,

    },

    userId: {

      type: Number|String,

      required: true,

    },

    userName: {

      type: String,

      required: true,

    },

  },

  data() {

    return {

      allFormData: [],

      luckysheet: null,

      isCheckSheet: false,

      firstUpdate:false,

      updateArrList:[],

      falseList:[],

      loadingForm:true,

      currentRow: 5,

      originOptions: {},

      saveState: false,

      xmAddTopRow :false,

      xmAddBottomRow :false,

      bottomAddRow:false,


 

      addRowsNum:0,

      addNewRows:[],

      cacheDelList:[],

      options: {

        container: "luckysheet", // luckysheet为容器id

        lang: "zh",

        column: 10, //空表格默认的列数量

        row: 5, //空表格默认的行数据量

        showsheetbar: false, // 底部sheet页

        // showtoolbar: false,  // 隐藏工具栏

        showsheetbarConfig: {

          add: false, //新增sheet

          menu: true, //sheet管理菜单

          sheet: true, //sheet页显示

        },

        showtoolbarConfig: {

          undoRedo: true, //撤销重做,注意撤消重做是两个按钮,由这一个配置决定显示还是隐藏

          paintFormat: true, //格式刷

          currencyFormat: true, //货币格式

          percentageFormat: true, //百分比格式

          numberDecrease: true, // '减少小数位数'

          numberIncrease: true, // '增加小数位数

          moreFormats: true, // '更多格式'

          font: true, // '字体'

          fontSize: true, // '字号大小'

          bold: true, // '粗体 (Ctrl+B)'

          italic: true, // '斜体 (Ctrl+I)'

          strikethrough: true, // '删除线 (Alt+Shift+5)'

          underline: true, // '下划线 (Alt+Shift+6)'

          textColor: true, // '文本颜色'

          fillColor: true, // '单元格颜色'

          border: true, // '边框'

          mergeCell: false, // '合并单元格'

          horizontalAlignMode: true, // '水平对齐方式'

          verticalAlignMode: true, // '垂直对齐方式'

          textWrapMode: true, // '换行方式'

          textRotateMode: false, // '文本旋转方式'

          image: false, // '插入图片'

          link: false, // '插入链接'

          chart: false, // '图表'(图标隐藏,但是如果配置了chart插件,右击仍然可以新建图表)

          postil: false, //'批注'

          pivotTable: false, //'数据透视表'

          function: false, // '公式'

          frozenMode: true, // '冻结方式'

          sortAndFilter: true, // '排序和筛选'

          conditionalFormat: false, // '条件格式'

          dataVerification: false, // '数据验证'

          splitColumn: false, // '分列'

          screenshot: false, // '截图'

          findAndReplace: false, // '查找替换'

          protection: false, // '工作表保护'

          print: false, // '打印'

        },

        pager: {

          pageIndex: 1, //当前的页码

          pageSize: 1000, //每页显示多少行数据

          total: 0, //数据总行数

          showTotal: true,

          // selectOption: [10, 20] //允许设置每页行数的选项

        },

        title: "",

        hook: {

          cellDragStop: function (cell, postion, sheetFile, ctx, event) {},

          rowTitleCellRenderBefore: function (rowNum, postion, ctx) {},

          rowTitleCellRenderAfter: function (rowNum, postion, ctx) {},

          columnTitleCellRenderBefore: function (columnAbc, postion, ctx) {},

          columnTitleCellRenderAfter: function (columnAbc, postion, ctx) {},

          cellRenderBefore: function (cell, postion, sheetFile, ctx) {},

          cellRenderAfter: function (cell, postion, sheetFile, ctx) {},

          cellHover: function (cell, postion, sheetFile, ctx) {},

          cellMousedownBefore: function (cell, postion, sheetFile, ctx) {},

          cellMousedown: function (cell, postion, sheetFile, ctx) {},

          sheetMousemove: function (

            cell,

            postion,

            sheetFile,

            moveState,

            ctx

          ) {},

          sheetMouseup: function (cell, postion, sheetFile, moveState, ctx) {},

          cellAllRenderBefore: function (data, sheetFile, ctx) {},

          updated: function (operate) {

            console.log(operate, "updated");

          },

          cellUpdateBefore: function (r, c, value, isRefresh) {},

          cellUpdated: function (r, c, oldValue, newValue, isRefresh) {

            // console.log(r, c, oldValue, newValue, isRefresh, "cellUpdated");

          },

          sheetActivate: function (index, isPivotInitial, isNewSheet) {},

          sheetDeactivateBefore: function (

            index,

            isPivotInitial,

            isNewSheet

          ) {},

          sheetDeactivateAfter: function (index, isPivotInitial, isNewSheet) {},

          commentInsertBefore: function (r, c) {},

          commentInsertAfter: function (r, c, cell) {},

          commentDeleteBefore: function (r, c, cell) {},

          commentDeleteAfter: function (r, c, cell) {},

          commentUpdateBefore: function (r, c, value) {},

          commentUpdateAfter: function (r, c, oldCell, newCell) {},

          cellEditBefore: function (range) {},

          rangeEditBefore: function (range, data) {},

          rangeEditAfter: function (range, data) {},

          rangeSelect: function (range, data) {

            // window.luckysheet.exitEditMode()

          },

          rangePasteBefore: function (range, data) {

            // return false; //Can intercept paste

          },

          rangePasteAfter: function (range, data) {

            // return false; //Can intercept paste

          },

          rangeDeleteBefore: function (range, data) {},

          rangeDeleteAfter: function (range, data) {},

          rangeClearBefore: function (range, data) {},

          rangeClearAfter: function (range, data) {},

          workbookCreateAfter: function (json) {},

          onTogglePager: function (page) {

            console.log(arguments, "-0", page, "onTogglePager");

          },

          xmbottomAddRowClicked: function (value) {

            console.log(value, "xmbottomAddRowClicked");

          },

          rightClickUpload: function (value,data) {

            console.log(value,data, "rightClickUpload");

          },

          xmAddTopRowClicked: function (value) {

            console.log(value, "xmAddTopRowClicked");

          },

          xmAddBottomRowClicked: function (value) {

            console.log(value, "xmAddBottomRowClicked");

          },

        },

      },

      dialogFormVisible:false,

      applyInfo:''

    };

  },

  watch: {

    index: {

      handler: "watchIndex",

    },

    searchValue: {

      handler: "watchSearchValue",

      deep: true,

    },

    roleFlag: {

      handler: "watchroleFlagChange",

      immediate: true,

    },

  },

  created() {

    this.luckysheet = window.luckysheet;

  },

  mounted() {

    console.log(this.index,this.searchValue,this.type, TitleData, "组件初始化接收");

    // 获取初始化数据

  },

  beforeDestroy() {

    this.luckysheet.destroy();

    this.setCompleteState(false)

  },

  methods: {

    initgetData(){

      console.log('初始化获取表格数据')

       let params = {

        sys: this.type,

         mnun: this.departMnun,   //登陆用户的部门

         provinceNm: this.searchValue.provinceNm,

         basin: this.searchValue.basin,

         name: this.searchValue.name,

         pageNum: this.options.pager.pageIndex,

         pageSize: !this.departMnun ? this.options.pager.pageSize : 500,

         rvName:this.searchValue.rvName

       };

      this.setFormData(params);

    },

     watchroleFlagChange(value) {

      console.log(value, "监听角色的值");

      this.saveState = false;

      switch (value) {

        case 0:

          // 管理员

          this.saveState = true;

          break;

        case 1:

          // 汇总

          this.saveState = false;

          break;

        case 2:

          // 填报

          this.saveState = false;

          break;

        case 3:

          // 流域负责人

          this.saveState = false;

          break;

        case 4:

          // 领域负责人

           this.saveState = false;

          break;

        case 5:

          // 规计司

          this.saveState = false

          break;

        default:

          break;

      }

    },

    watchIndex(val) {



 

      this.isCheckSheet = true

      console.log(this.departMnun,'this.departMnun')

      this.options.pager.pageIndex=1

      let params = {

        sys: this.type,

         mnun: this.departMnun,   //登陆用户的部门

         provinceNm: this.searchValue.provinceNm,

         basin: this.searchValue.basin,

         name: this.searchValue.name,

         pageNum: this.options.pager.pageIndex,

         pageSize: !this.departMnun ? this.options.pager.pageSize : 500,

         rvName:this.searchValue.rvName

       };

      this.setFormData(params);

    },

    async watchSearchValue(value) {

         let numSize = !this.departMnun ? this.options.pager.pageSize : 500

      this.options.pager.pageIndex=1

      console.log(numSize,'numSIze')

      console.log(value, "监听搜索的值");

      if( this.isCheckSheet) {

          console.log( "刚进页面多余触发监听");

          return

      }

      let params = {

        sys: this.type,

        mnun: this.departMnun,   //登陆用户的部门

        provinceNm: value.provinceNm,

        basin: value.basin,

        name: value.name,

        pageNum: this.options.pager.pageIndex,

        pageSize: !this.departMnun ? this.options.pager.pageSize : 500,

        rvName:value.rvName

      };

       this.setFormData(params);

    },

    async setFormData(params) {

      console.log(this.index,'序号变化')


 

      this.luckysheet.destroy();

      let data = {};

      this.loadingForm = true

      let indexData = TitleData22[this.index];

      this.options = this.setFormTitle(indexData);

      console.log(indexData,'indexDataindexData')

      switch (this.index) {

        case 1:

          this.currentRow = 5;

          break;

        case 2:

          this.currentRow = 5;

          break;

        case 3:

          this.currentRow = 5;

          break;

        case 4:

          this.currentRow = 5;

          break;

        case 5:

          this.currentRow = 3;

          break;

        case 6:

          this.currentRow = 7;

          break;

        case 7:

          this.currentRow = 6;

          break;

        case 8:

          this.currentRow = 5;

          break;

        case 9:

          this.currentRow = 5;

          break;

        case 10:

          this.currentRow = 6;

          break;

        case 11:

          this.currentRow = 5;

          break;

        case 12:

          this.currentRow = 5;

          break;

        case 13:

          this.currentRow = 5;

          break;

        case 14:

          this.currentRow = 5;

          break;

        case 15:

          this.currentRow = 5;

          break;

        case 16:

          this.currentRow = 5;

          break;

        case 17:

          this.currentRow = 5;

          break;

        case 18:

          this.currentRow = 4;

          break;

        case 19:

          this.currentRow = 5;

          break;

        case 20:

          this.currentRow = 5;

          break;

        case 21:

          this.currentRow = 5;

          break;

        case 22:

          this.currentRow = 5;

          break;

        case 23:

          this.currentRow = 5;

          break;

        case 24:

          this.currentRow = 5;

          break;

        default:

          this.currentRow = 5;

          break;

      }

      // 设置表头

      this.originOptions = cloneDeep(this.options);

      console.log(this.options,this.originOptions,'this.originOptions,设置表头')

      data = await this.getList(params);

      this.dealListData(data, this.currentRow);

    },

    /**

     *  获取表格数据

     *  @param {object} params

     *  @param {string} params.sys 类型

     *  @param {string} params.mnun 省份

     *  @param {string} params.basin 流域

     *  @param {string} params.name 河流

     *  @param {string} params.pageNum 页码

     *  @param {string} params.pageSize 每页条数

     */

    async getList(params) {

      console.log(params, "获取数据入参");

      this.resetupdateChange()

      let listData = {};

      this.setCompleteState(true)

      try {

        let res = await getAnnualList(params);

        listData = !!res.data.data ? res.data.data : {};

        console.log(listData, "listData-获取到的表结果");

        console.log(listData.records.length,this.currentRow,'数据量,起始行' )

        if(listData && listData.records && listData.records.length >= 0) {

          let currentDataRow = listData.records.length + this.currentRow

          if(currentDataRow  < 36) {

            console.log('数据不够,小于36行')

            let newRow = 36 - listData.records.length - this.currentRow

            console.log(currentDataRow,newRow,'newRow')

            for(let i = 0; i < newRow; i++) {

              let num = currentDataRow + i

              this.addNewRows.push(num)

            }

            console.log(this.addNewRows,'初始化添加的行')

          }

        } else {

          let newRow = 36 - this.currentRow

            for(let i = 0; i < newRow; i++) {

              let num = this.currentRow + i

              this.addNewRows.push(num)

            }

            console.log(this.addNewRows,'没有数据初始化添加的行')

        }

        return listData;

      } catch (err) {

        console.log(err, "获取表格数据失败");

        let newRow = 36 - this.currentRow

        for(let i = 0; i < newRow; i++) {

          let num = this.currentRow + i

          this.addNewRows.push(num)

        }

        console.log(this.addNewRows,'接口错误没有数据初始化添加的行')

        return listData;

      }

    },


 

    /**

     * @param {value} 序号的值

     *   不含. 不是合计小计 靠左

     *   含. 不是合计 小计 靠右

     *   空 合计 小计 不处理

     *   例如

     *   1 靠左

     *   1.1 靠右

     *   1.1.1 靠右

     *   合计 默认

     *   小计 默认

     *   空 默认

     *  @return {htValue}  水平对齐的位置  0 居中、1 左、2右   默认返回 '0'

     */

    isCloseLeft(value) {

      let htValue = "0"

      let index = 3

      if(this.index !== 5 && this.index !== 6 && this.index !== 7 && this.index !== 8 && this.index !== 9 && this.index !== 18 ){

        if(value !== null && value !== undefined && value !== '') {

          let order = value + ''

          if(Number.isInteger(Number(order))){

              htValue = '1'

          } else {

            if(order && order.indexOf('.') > -1) {

              htValue = '2'

            }

          }

        }

        if(this.index === 10) {

          index = 5

        }

        if(this.index === 11) {

          index = 6

        }

        if(this.index === 12) {

          index = 4

        }

        if(this.index === 13) {

          index = 4

        }

        if(this.index === 14) {

          index = 4

        }

      }

      return {htValue,index}

    },

    isgrayBgColor(list){

      let bg =  '#fff'

      let value = '特殊标记xmmmm'

      switch (this.index) {

        case 1:

            value = list[54]

          break;

        case 2:

            value = list[7]

          break;

        case 3:

          value = list[9]

          break;

        case 4:

            value = list[47]

          break;

        case 5:

          break;

        case 6:

          break;

        case 7:

          break;

        case 8:

          break;

        case 9:

          break;

        case 10:

          break;

        case 11:

            value = list[23]

          break;

        case 12:

          break;

        case 13:

          break;

        case 14:

          break;

        case 15:

            value = list[33]

          break;

        case 16:

            value = list[54]

          break;

        case 17:

            value = list[7]

          break;

        case 18:

          break;

        case 19:

            value = list[53]

          break;

        case 20:

            value = list[57]

          break;

        case 21:

            value = list[46]

          break;

        case 22:

            value = list[48]

          break;

        case 23:

            value = list[47]

          break;

        case 24:

            value = list[9]

          break;

        case 25:

            value = list[57]

          break;

        default:

          break;

      }

      // console.log(value,list)

      if(value !== 'A' && value !== 'B' && value !== 'C'&& value !== '特殊标记xmmmm') {

        bg = '#cccccc'

      }

      return bg

    },


 

    /**

     *

     * @param {object} data   请求获取的所有数据,包括了分页的信息和records

     * @param {number} index  要放进表格内容的行数,从哪一行开始放入数据,

     */

    dealListData(data, currentRow) {

      this.options = cloneDeep(this.originOptions);

      console.log(data, "方法里拿到的数据", currentRow, this.options,this.options.data[0]);

      if (data && data.records && data.records.length > 0) {

        let list = data.records;

        // <!-- r代表行,c代表列,v代表该单元格的值,值可以是字符、数字或者对象。 -->

        for (let i = 0; i < list.length; i++) {

          let outArr = list[i];


 

          // 根据序号来让项目名称这一项靠左靠右

          let orderValue = outArr[2]

          const order = this.isCloseLeft(orderValue)

          // 根据 项目建设优先级 是否为不纳入,来判断一整行得背景色是否置为灰色

          const bgColor = this.isgrayBgColor(outArr)

          // console.log(bgColor,'每一行背景色')


 

          for (let j = 2; j < outArr.length; j++) {

            let value = outArr[j];

            let id = outArr[0]   // 这里可以存每个单元格的id,不进行展示

            let item = {

              r: currentRow + i,

              c: j -2,

              v: {

                ct: { fa: "General", t: "g" },

                v: value, //原始值

                m: value, //显示值

                id: id,  //用来存储单元格的id

                vt: "0", //垂直对齐 0 中间、1 上、2下

                ht: j === order.index ? order.htValue :  "0" , //水平对齐 0 居中、1 左、2右

                // ht: "0", //水平对齐  0 居中、1 左、2右

                bl: 0, //粗体 0 常规 、 1加粗

                tr: 0, //竖排文字 3

                tb: 2, //文本换行 0 截断、1溢出、2 自动换行

                bg:bgColor, //背景色

              },

            };

            this.options.data[0].celldata.push(item);

          }

        }

        if(this.index==1){

          this.options.data[0].filter_select.row[1]= data.size + (currentRow - 1)||0;

          console.log(this.options.data[0].filter_select.row,'拿到shaixuan筛选的数据')

        }

        this.options.pager.total = data.total;

        this.options.pager.totalTxt = `总共数据:${data.total}条`;

        this.options.pager.pageIndex = data.current;

        this.options.pager.pageSize = data.size;

        console.log(this.options, "生成表格初始化拿到的options配置信息");


 

        this.isCheckSheet = false

        setTimeout(() => {

          this.luckysheet.create(this.options);

        },0)

      } else {

      this.isCheckSheet = false

        this.originOptions.pager.total =0;

        this.originOptions.pager.totalTxt = `总共数据:0条`;

        console.log(this.options,this.originOptions, "没有请求到数据生成表格初始化拿到的options配置信息22");

        setTimeout(() => {

          this.luckysheet.create(this.originOptions);

        },0)

      }




 

      setTimeout(() => {


 

        this.loadingForm = false

        this.setCompleteState(false)

      },200)

    },

    // 设置表头

    setFormTitle(TitleData) {

      if (this.options.data) {

        delete this.options.data;

      }

      console.log(TitleData, "解析的表头");

      const options = cloneDeep(this.options);

      options.data = TitleData;

      // 修改分页调用方法

      options.hook.onTogglePager = this.sizeChange;

      // 修改更新调用方法

      options.hook.updated = this.updatedSheetData;

      options.hook.xmbottomAddRowClicked = this.xmAddRowClicked;

      options.hook.xmAddTopRowClicked = this.xmAddTopRowClicked;

      options.hook.xmAddBottomRowClicked = this.xmAddBottomRowClicked;

      options.hook.cellEditBefore = this.cellUpdateBefore;

      //上传

      options.hook.rightClickUpload= this.rightClickUpload;


 

      console.log(options,'设置表头options')

      return options;

    },

    cellUpdateBefore(range) {

      console.log(range, "cellUpdateBefore");

      let state = true

      let column = range[0].column

      let first  = column[0]

      let end  = column[1]

      if(first !== end){

        return state

      }

      /**

       * @param {Array} disableList  禁用得列号

       * @param {Number} columnNumber  当前得列号

       * @returns {Boolean} true:不禁用  false:禁用

       */

      const ruleIsTrue = (disableList,columnNumber)=>{

        const isContain = disableList.findIndex(item => item == columnNumber)

        if(isContain === -1){

          return true

        } else {

          return false

        }

      }

      let list = []

      switch(this.index){

        case 1:

          list = [52,54]

          break;

        case 2:

          break;

        case 3:

          break;

        case 4:

          break;

        case 5:

          break;

        case 6:

          break;

        case 7:

          break;

        case 8:

          break;

        case 9:

          break;

        case 10:

          break;

        case 11:

          break;

        case 12:

          break;

        case 13:

          break;

        case 14:

          break;

        case 15:

          break;

        case 16:

          break;

        case 17:

          break;

        case 18:

          break;

        case 19:

          break;

        case 20:

          break;

        case 21:

          break;

        case 22:

          break;

        case 23:

          break;

        case 24:

          break;

        case 25:

          break;

        default:

          break;

      }

      return ruleIsTrue(list,first)

    },

    async sizeChange(page) {

      console.log(arguments, "-0", page, "sizeChange");

      this.$message('正在切换到下一页,请稍后')

      this.loadingForm = true

      this.options.pager.pageIndex = page.pageIndex;

      let params = {

        sys: this.type,

        mnun: this.departMnun,   //登陆用户的部门

        provinceNm: this.searchValue.provinceNm,

        basin: this.searchValue.basin,

        name: this.searchValue.name,

        pageNum: page.pageIndex,

        pageSize: !this.departMnun ? this.options.pager.pageSize : 500,

        rvName:this.searchValue.rvName

      };

      this.luckysheet.destroy()

      let data = await this.getList(params);

      this.dealListData(data, this.currentRow);

    },

    xmAddRowClicked(value){

      console.log(value,'xmAddRowClicked新增了行数')

      this.addRowsNum = value

      this.bottomAddRow = true

      this.xmAddTopRow = false

      this.xmAddBottomRow = false

    },

    xmAddTopRowClicked(value){

      console.log(value,'xmAddTopRowClicked新增了行数')

      this.addRowsNum = value

      this.bottomAddRow = false

      this.xmAddTopRow = true

      this.xmAddBottomRow = false

    },

    xmAddBottomRowClicked(value){

      console.log(value,'xmAddBottomRowClicked新增了行数')

      this.addRowsNum = value

      this.bottomAddRow = false

      this.xmAddTopRow = false

      this.xmAddBottomRow = true

    },

    rightClickUpload(row,data){

      console.log(row,data,'上传')

    },

    dealaddRc(operate){

      if(this.bottomAddRow){

        let startRow = operate.data.length - 1

        console.log(startRow,this.addRowsNum,'startRow')

        let addRows = this.addRowsNum

        for(let i = 1;i <= addRows;i++){

          let num = startRow + i

          this.addNewRows.push(num)

        }

        console.log(this.addNewRows,'this.addNew--rows')

        this.bottomAddRow = false

      } else {

        console.log('标志位为false')

        console.log(this.addRowsNum,this.addNewRows,operate,'新增行数')

      }

    },

    deleteRow(operate){

      if(this.saveState==false){ //没有保存权限

          this.firstUpdate = true

          this.luckysheet.undo()

          setTimeout(()=>{

             this.firstUpdate = false

             this.$message({

               type: 'warning',

               message:'您没有此功能操作权限,不能删除数据'

             })

          },150)

          return

      }

      let list=[]

      let allRow =Array.from(new Set(operate.dataRange[0].row)).sort((a, b) => a - b)

      let startRow = allRow[0]

      let endRow = allRow[1] !== undefined ? allRow[1] : allRow[0]

      console.log(allRow,startRow,endRow,this.currentRow,operate,this.addNewRows,'删除的起始行,结束行')

      let length = endRow - startRow

      if(startRow < this.currentRow){

        this.firstUpdate = true

        this.$alert('不能删除表头行', '提示', {

          confirmButtonText: '确定',

          callback: () => {

            this.luckysheet.undo()

            this.firstUpdate = false

            setTimeout(()=>{

              this.$message({

                type: 'success',

                message:'撤销成功'

              })

            },150)

          }

        });

        return

      }

      let cacheUpdataList = cloneDeep(this.updateArrList)

      this.cacheDelList = cloneDeep(this.updateArrList)

      for(let i = 0;i <= length;i++){

        let num = startRow + i

        console.log(num,this.addNewRows,'当前行号')

        let ownId = false

        let single = operate.data[num]

        if(!this.addNewRows.includes(num)){

          if (single && single.some(item => item &&  item.id !== undefined && item.id !== null )) {

            ownId = true;

          }

        }

        if(!ownId){

          console.log(num,'删除的是新增行')

          const index = this.updateArrList.findIndex( item => item[0] == num)

          if (index !== -1) {

            // 如果找到了重复项,则删除原有项

            console.log(index,cacheUpdataList.length - 1,cacheUpdataList,'zai删除里找到了重复项,删除原有项')

            cacheUpdataList.splice(cacheUpdataList.length - 1, 1);

          }


 

          this.$message.success('删除成功')

        }else{

          console.log('删除的是原有行')

          const id = single.find(item => item && item.id !== undefined && item.id !== null).id;

          console.log(id,'删除行的id')

          list.push(id)

          this.firstUpdate = true

        }

      }

      if(list.length>0){

        this.$confirm('当前数据已存入数据库,如果确认将会从数据库中删除当前行数据', '提示', {

            confirmButtonText: '确定',

            cancelButtonText: '取消',

          }).then(() => {

            this.firstUpdate = false

            this.deleteRowData(list)

          }).catch(() => {

            this.luckysheet.undo()

            this.firstUpdate = false

            setTimeout(()=>{

              this.$message({

                type: 'success',

                message:'撤销成功'

              })

            },150)

            console.log(this.updateArrList.length,this.updateArrList,'撤销之后的修改数据的')

          });

          }

      this.updateArrList = cloneDeep(cacheUpdataList)

      console.log(this.updateArrList, this.addNewRows,'缓存修改数据')

    },

    deleteRowData(id){

    let params={

      type:this.type,

      idList:id

    }

    deleteRowList(params).then(async(res)=>{

          this.$message({

          type: 'success',

          message:'删除成功'

          })

           let params = {

            sys: this.type,

            mnun: this.departMnun,   //登陆用户的部门

            provinceNm: this.searchValue.provinceNm,

            basin: this.searchValue.basin,

            name: this.searchValue.name,

            pageNum:this.options.pager.pageIndex,

            pageSize: !this.departMnun ? this.options.pager.pageSize : 500,

            rvName:this.searchValue.rvName

          };

          this.luckysheet.destroy()

          let data = await this.getList(params);

          this.dealListData(data, this.currentRow);

    })

      console.log(id,'调用删除行数据接口')

    },

    resetupdateChange(){

      this.updateArrList = []

      this.falseList = []

      this.addNewRows = []

      this.addRowsNum = 0

      this.firstUpdate = false

      this.$emit('geterrorReason',[])

    },


 

    resetID(row,allColumn,value,refresh){

      console.log(row,allColumn,value,'重置id的方法')

      let isLast = false

      for(let column = 0;column < allColumn ;column++){

        console.log(row,column,'-----')

        if(column === allColumn - 1){

          isLast = true

        }

        let doRefresh = isLast && refresh ? true : false

        this.luckysheet.setCellValue(row, column, {id: value}, {isRefresh: doRefresh,success:(data) =>{

          console.log(data[row][column],'重置id的方法成功')

        }})

      }

    },

    checkIdIsRight(operate){

      console.log(operate,'重置id的方法')

      let allRow =Array.from(new Set(operate.range[0].row)).sort((a, b) => a - b)

      let startRow = allRow[0]

      let endRow = allRow[1] !== undefined ? allRow[1] : allRow[0]

      let refresh = false

      // 存在复制粘贴的时候重复id的情况

      for(let i = 0;i <= endRow - startRow;i++){

        if(i === endRow - startRow){

          refresh = true

        }

        const originData = operate.data[startRow + i]

        const newData = operate.curdata[startRow + i]

        console.log(startRow + i,originData,newData,'行号是多少,原始数据是什么')

        let originId = null

        let newId = null

        if(originData && originData.some(item => item &&  item.id !== undefined && item.id !== null )){

          originId = originData.find(item => item && item.id !== undefined && item.id !== null).id

          console.log(originId,'originId --id是什么')

        }

        if(newData && newData.some(item => item &&  item.id !== undefined && item.id !== null )){

          newId = newData.find(item => item && item.id !== undefined && item.id !== null).id

          console.log(newId,'newId --id是什么')

        }


 

        if(originId !== newId){

          let currentRow = startRow + i

          let allColumn = newData.length

          console.log(originId,newId,currentRow,allColumn,'id不同,要进行重置id的操作')

          this.resetID(currentRow,allColumn,originId,refresh)

        }

      }


 

    },

    updatedSheetData(operate) {

      console.log(operate,'updated11111')


 

      if (this.firstUpdate) {

        // 如果标志位为 true,直接返回,不执行钩子函数逻辑

        return

      }


 

      if(operate.type === "addRC"){

        if(operate.data){

          this.dealaddRc(operate)

        } else {

        }

      }


 

      if(operate.type === "delRC"){

        if(operate.data){

          this.deleteRow(operate)

        } else {

          this.updateArrList = cloneDeep(this.cacheDelList)

          console.log(this.updateArrList,'撤销删除里的删除数据')

        }

      }

      if(operate.type === "datachange"){




 

        this.firstUpdate = true

        if(operate.range.length >= 2){

            this.$alert('请勿拖拽修改数据,将撤销此次拖拽', '提示', {

            confirmButtonText: '确定',

            callback: () => {

              this.luckysheet.undo()

              this.firstUpdate = false

              setTimeout(()=>{

                this.$message({

                  type: 'success',

                  message:'撤销成功'

                })

              },150)

            }

          });

          return

        }


 

        const changeRowList =  operate.range[0].row

        if(changeRowList[0] !== changeRowList[1]){

            this.$alert('为了保证数据的准确性,只能单行的复制修改数据,请勿复制多行数据进行修改,将撤销此次操作', '提示', {

            confirmButtonText: '确定',

            callback: () => {

              this.luckysheet.undo()

              this.firstUpdate = false

              setTimeout(()=>{

                this.$message({

                  type: 'success',

                  message:'撤销成功'

                })

              },150)

            }

          });

          return

        }



 

        this.checkIdIsRight(operate)


 

        this.getValueAndId(operate)

        console.log(this.updateArrList,'缓存修改数据')

        setTimeout(()=>{

          this.firstUpdate = false

        },200)



 

      } else if(operate.type === "pasteCut"){

          let source = operate.source.range

          let target = operate.target.range

          if(source.row[0] !== target.row[0] || source.row[1] !== target.row[1] || source.column[0] !== target.column[0] || source.column[1] !== target.column[1]) {

            this.firstUpdate = true

            // 修改区域与当前选中区域不一样,修改内容将无法提交,将撤销此修改

            this.$alert('不支持通过剪切修改', '提示', {

              confirmButtonText: '确定',

              callback: () => {

                this.luckysheet.undo()

                this.firstUpdate = false

                setTimeout(()=>{

                  this.$message({

                    type: 'success',

                    message:'撤销成功'

                  })

                },150)

              }

            });

            return

          } else {

            console.log(source,target,'修改区域')

          }

      }

    },

    getValueAndId(operate){

      let allRow =Array.from(new Set(operate.range[0].row)).sort((a, b) => a - b)

      let startRow = allRow[0]

      let endRow = allRow[1] !== undefined ? allRow[1] : allRow[0]

      console.log(allRow,startRow,endRow,operate,this.addNewRows,'起始行,结束行')






 

      let currentLast = this.addNewRows[this.addNewRows.length - 1]

      if(endRow > currentLast){

        let newLength = endRow - currentLast

        console.log(currentLast,newLength,'新增行超过了添加的空白行')

        for(let i = 1;i <= newLength;i++){

          let num = currentLast + i

          const rowIndex = this.addNewRows.findIndex( item => item[0] == num)

          if (rowIndex !== -1) {

            // 如果找到了重复项,则删除原有项

            console.log(rowIndex,'getValue--找到了重复项,删除原有项')

            this.addNewRows.splice(rowIndex, 1);

          }

          this.addNewRows.push(num)

          this.addNewRows.sort((a, b) => a - b)

        }

      }

      console.log(this.addNewRows,'this.addNewRows新增的行号数组')

      let length = endRow - startRow

      let changeId = false

      let cacheId = null

      for(let i = 0;i <= length;i++){

        let num = startRow + i

        console.log(num,'当前的num')

        let ownId = false

        let single = operate.data[num]

        if(!this.addNewRows.includes(num)){

          if (single && single.some(item => item &&  item.id !== undefined && item.id !== null )) {

            ownId = true;

          } else {

            const item = this.updateArrList.find( item => item[0] === num)

            console.log(item,'item项')

            if(item){

              cacheId = item[1]

              ownId = true;

            }

          }

        }

        if(!ownId){

          console.log('是新增行')

          let list = operate.curdata[num]

          console.log(list,num,'list不带id')

          let updateList = [num,'',this.departMnun]

          if(list){

            list.forEach(item=>{

              let value = ''

              if(!item){

                updateList.push(value)

              } else {

                let m = ''

                if(item.v && item.v !== undefined && item.v !== null){

                  m = item.v

                } else if(item.ct && item.ct.s && item.ct.s !== undefined && item.ct.s !== null && item.ct.s.length > 0){

                  if(Array.isArray(item.ct.s)){

                    item.ct.s.forEach(val=>{

                      if(val.v !== undefined && val.v !== null){

                        m = m + val.v

                      }

                    })

                  }

                }

                updateList.push(m)

              }

            })

            this.pushUpdateItem(updateList,true)

          } else {

              const index = this.updateArrList.findIndex( item => item[0] === num)

              if (index !== -1) {

                // 如果找到了重复项,则删除原有项

                console.log(index,'undefined的else里找到了重复项,删除原有项')

                this.updateArrList.splice(index, 1);

              }

            }

        } else {

          console.log('不是新增行')

          let list = operate.curdata[num]

          let idList = operate.data[num]

          console.log(list,num,'list带id')

          let updateList = [num,'',this.departMnun]

          if(list){

            list.forEach((item,index)=>{

              let value = ''

              if(!item){

                updateList.push(value)

              } else {

                if(!changeId){

                  let id = ''

                  if(idList[index] && idList[index].id){

                    id = idList[index].id

                  }

                  if(id === '') {

                    changeId = false

                  }else {

                    console.log(id,'id')

                    updateList[1] = id

                    changeId = true

                  }

                }

                let m = ''

                if(item.v && item.v !== undefined && item.v !== null){

                  m = item.v

                } else if(item.ct && item.ct.s && item.ct.s !== undefined && item.ct.s !== null && item.ct.s.length > 0){

                  if(Array.isArray(item.ct.s)){

                    item.ct.s.forEach(val=>{

                      if(val.v !== undefined && val.v !== null){

                        m = m + val.v

                      }

                    })

                  }

                }

                updateList.push(m)

              }

            })

            if(updateList[1] == ''){

              if(cacheId){

                console.log(cacheId,'没有读到id')

                updateList[1] = cacheId

              }

            }

            cacheId = null

            changeId = false

            this.pushUpdateItem(updateList,false)

          } else {

            const index = this.updateArrList.findIndex( item => item[0] === num)

            if (index !== -1) {

              // 如果找到了重复项,则删除原有项

              console.log(index,'undefined的else里找到了重复项,删除原有项')

              this.updateArrList.splice(index, 1);

            }

          }

        }

      }


 

      if(this.updateArrList.length > 100){

        console.log(this.updateArrList.length,'修改数据的长度')

      }

      console.log(this.updateArrList,'修改数据的数组')

    },

    pushUpdateItem(newItem,isNewRow){

      const index = this.updateArrList.findIndex( item => item[0] == newItem[0])

      // if(isNewRow){

      //   let isEmpty = false

      //   let emptyNum = 0

      //   for(let i = 3;i < newItem.length;i++){

      //     if(newItem[i] === '' || newItem[i] === null || newItem[i] === undefined){

      //       emptyNum ++

      //     }

      //   }

      //   if(emptyNum === newItem.length - 3){

      //     isEmpty = true

      //   }

      //   if(isEmpty){

      //     if (index !== -1) {

      //       // 如果找到了重复项,则删除原有项

      //       console.log(index,'isEmpty-找到了重复项,删除原有项')

      //       this.updateArrList.splice(index, 1);

      //     }

      //     return

      //   }

      // }

      // if (index !== -1) {

      //   // 如果找到了重复项,则删除原有项

      //   console.log(index,newItem,'找到了重复项,删除原有项')

      //   this.updateArrList[index] = newItem

      // } else {

      //   // 将新项添加到数组

      //   this.updateArrList.push(newItem);

      // }


 

      if (index !== -1) {

        // 如果找到了重复项,则删除原有项

        console.log(index,'找到了重复项,删除原有项')

        this.updateArrList.splice(index, 1);

      }

      if(isNewRow){

        let isEmpty = false

        let emptyNum = 0

        for(let i = 3;i < newItem.length;i++){

          if(newItem[i] === '' || newItem[i] === null || newItem[i] === undefined){

            emptyNum ++

          }

        }

        if(emptyNum === newItem.length - 3){

          isEmpty = true

        }

        if(isEmpty){

          return

        }

      }

      // 将新项添加到数组

      this.updateArrList.push(newItem);

    },

  updateChange(params){

    this.$message({

      showClose: true,

      type: 'info',

      duration:0,

      message: '保存中...  请勿修改表格内容'

    });

    updateTableData(params).then( async (res) =>{

      console.log(res,'修订')

      this.$message.closeAll()

      if(!res.data.data || res.data.data.length === 0 ){

        this.firstUpdate = true

          this.$emit('geterrorReason',[])

        this.falseList.forEach((item,index) =>{

          let refresh = index === this.falseList.length - 1 ? true :false

          this.falseToRule(true,item.row,item.column,item.msg,refresh)

        })

        // // // 修改保存成功之后,缺少了主键,回导致每次修改都会认为是新增数据,目前做法先重新查询一遍


 

        let params = {

          sys: this.type,

          mnun: this.departMnun,   //登陆用户的部门

          provinceNm: this.searchValue.provinceNm,

          basin: this.searchValue.basin,

          name: this.searchValue.name,

          pageNum: this.options.pager.pageIndex,

          pageSize: !this.departMnun ? this.options.pager.pageSize : 500,

          rvName:this.searchValue.rvName

        };

        this.setFormData(params);

        // // 后端接口加了新增的主键返回值之后,把主键添加到数据里的逻辑

        // let addIdList = []

        // addIdList.forEach((item,index) =>{

        //   let refresh = index === addIdList.length - 1 ? true :false

        //   this.luckysheet.setCellValue(item.row, item.column, {id: item.id}, {isRefresh: refresh})

        // })


 

        setTimeout(()=>{

          this.firstUpdate = false

          this.updateArrList = []

          this.falseList = []

          this.$message({

              type: 'success',

              message: '保存成功'

          });

        },100)

      } else  {

        this.$message({

            type: 'warning',

            message: '有修改内容不符合规范,请检查修正后再保存'

        })

        // 先清除上一次的批注

        this.falseList.forEach((item,index) =>{

          let refresh = index === this.falseList.length - 1 ? true :false

          this.falseToRule(true,item.row,item.column,item.msg,refresh)

        })

        // 再重新添加批注

        if(res.data.data && res.data.data.length > 0 ){

          console.log(res.data.data,'格式有问题的数据')

          this.falseList = res.data.data

          this.$emit('geterrorReason',res.data.data)

          this.firstUpdate = true

          this.falseList.forEach((item,index) =>{

            let refresh = index === this.falseList.length - 1 ? true :false

            this.falseToRule(false,item.row,item.column,item.msg,refresh)

          })

          setTimeout(()=>{

            this.firstUpdate = false

          },100)

        }

      }

    }).catch(err =>{

      console.log(err,'修订失败')

      this.$message.closeAll()

      this.$message({

          type: 'warning',

          message: '保存失败,请重新提交'

      });

    })

  },

      //   校验失败给出响应的提示方案

  falseToRule(state,row,column,tip,refresh = false){

    if (!state){

      let ps = { //批注

        left: 92, //批注框左边距

        top: 10, //批注框上边距

        width: 100, //批注框宽度

        height: 50, //批注框高度

        value: tip, //批准内容

        isshow: false //批注框为显示状态

      }

      this.luckysheet.setCellValue(row, column,{fc: "#ff0000",ps:ps}, { isRefresh: refresh })

      // #E6681A    #ff0000   #000000

    } else {

      this.luckysheet.setCellValue(row, column, {fc: "#000000"}, {isRefresh: refresh,success:(data) =>{

        console.log(data[row][column],'回调')

        delete data[row][column].ps

      }})

    }

  },

  saveUpdateData(){

      console.log(this.updateArrList,'保存修改数据')

        if(this.updateArrList.length === 0) {

            this.$message({

              type: 'info',

              message: '当前没有修改内容'

            });

            return

          }

      let params = {

        type: this.type,

        objs: this.updateArrList

      }

      this.updateChange(params)

  },

  saveReverse(){

    console.log(this.updateArrList,'保存修订审核数据')

    if(this.updateArrList.length === 0) {

      return  this.$message('当前没有修改内容');

    }else{

      // 先验证是否能提交审核

      let params = {

        userInfo:{

          userId:this.userId,

          mnun:this.departMnun,

          userName:this.userName

        },

        applyInfo:this.applyInfo,

        type: this.type,

        objs: this.updateArrList

      }

      getCheckList(params).then(res =>{

        console.log(res,'验证是否能提交审核接口返回')

        if(res.data && res.data.data){

          this.dialogFormVisible=true

        } else {

          this.$message({

            type: 'info',

            message: '您部门的当前数据表存在待审核的数据,请审核完成后再提交',

            duration:3000

          })

        }

      }).catch(err =>{

        console.log(err,'验证失败')

        this.$message.warning('查询是否存在审核数据失败,请重试')

      })

    }

  },

  confirmSave(){

    let params = {

      userInfo:{

        userId:this.userId,

        mnun:this.departMnun,

        userName:this.userName

      },

      applyInfo:this.applyInfo,

      type: this.type,

      objs: this.updateArrList

    }

    this.saveUpdateChange(params)

  },

  saveUpdateChange(params){

    this.$message({

      showClose: true,

      type: 'info',

      duration:0,

      message: '提交审核中...  请勿修改表格内容'

    });

    saveBatchListNewToCheck(params).then( res =>{

      console.log(res,'保存提交审核')

      this.$message.closeAll()

      if(!res.data.data || res.data.data.length === 0 ){

        this.firstUpdate = true

        this.$emit('geterrorReason',[])

        this.falseList.forEach((item,index) =>{

          let refresh = index === this.falseList.length - 1 ? true :false

          this.falseToRule(true,item.row,item.column,item.msg,refresh)

        })

        let params = {

          sys: this.type,

          mnun: this.departMnun,   //登陆用户的部门

          provinceNm: this.searchValue.provinceNm,

          basin: this.searchValue.basin,

          name: this.searchValue.name,

          pageNum: this.options.pager.pageIndex,

          pageSize: !this.departMnun ? this.options.pager.pageSize : 500,

          rvName:this.searchValue.rvName

        };

        this.setFormData(params);

        setTimeout(()=>{

          this.dialogFormVisible=false

          this.applyInfo=""

          this.firstUpdate = false

          this.updateArrList = []

          this.falseList = []

          this.$message({

              type: 'success',

              duration:4000,

              message: '数据已提交,整理入库将会花费一定时间,稍后可查看您的提交记录'

          });

        },100)

      } else  {

        this.dialogFormVisible=false

        this.applyInfo=""

        this.$message({

            type: 'warning',

            message: '有修改内容不符合规范,请检查修正后再保存'

        })

        // 先清除上一次的批注

        this.falseList.forEach((item,index) =>{

          let refresh = index === this.falseList.length - 1 ? true :false

          this.falseToRule(true,item.row,item.column,item.msg,refresh)

        })

        // 再重新添加批注

        if(res.data.data && res.data.data.length > 0 ){

          console.log(res.data.data,'格式有问题的数据')

          this.falseList = res.data.data

          this.$emit('geterrorReason',res.data.data)

          this.firstUpdate = true

          this.falseList.forEach((item,index) =>{

            let refresh = index === this.falseList.length - 1 ? true :false

            this.falseToRule(false,item.row,item.column,item.msg,refresh)

          })

          setTimeout(()=>{

            this.firstUpdate = false

          },100)

        }

      }

    }).catch(err =>{

      this.dialogFormVisible=false

      this.applyInfo=""

      console.log(err,'提交审核失败')

      this.$message.closeAll()

      this.$message.warning('提交审核失败,请重新提交');

    })

  },

 }

};

</script>

<style lang="scss" scoped>

#luckysheet {

  width: 100%;

  height: 100%;

  position: relative;

}

.sheet-container{

  width: 100%;

  height: 100%;

}

</style>

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值