<template>
  <div class="template-table" v-if="com!=null">
    <!-- <div class="menus" v-if="isActive">
      <span @click="onExport">导出</span>

    </div> -->
    <div class="table">
      <hot-table ref="hotTable" :settings="settings" licenseKey="non-commercial-and-evaluation"
        style="width:100%;"></hot-table>
    </div>

  </div>
</template>

<script>
  import Handsontable from "handsontable";

  import {
    HotTable
  } from '@handsontable/vue';
  import {
    ContextMenu
  } from 'handsontable/plugins/contextMenu'
  import {
    registerAllModules
  } from 'handsontable/registry'
  import {
    HyperFormula
  } from 'hyperformula';
  import "handsontable/dist/handsontable.full.css";

  // define options
  const hyperformulaInstance = HyperFormula.buildEmpty({
    licenseKey: 'internal-use-in-handsontable',
    precisionRounding: 10,
    nullDate: {
      year: 1900,
      month: 1,
      day: 1
    },
  });


  function customRenderer(instance, td) {
    Handsontable.renderers.TextRenderer.apply(this, arguments);
    td.style.backgroundColor = 'yellow';
  }


  import "handsontable/languages/zh-CN";
  import 'handsontable/dist/handsontable.full.css';
  export default {
    name: "table",
    components: {
      HotTable
    },
    emits: ['onUploadAttr', 'onUploadItemIndex'],
    props: {
      isActive: {
        type: Boolean,
        default: false,
      },
      currentIndex: {
        type: Number,
        default: 0,
      },
      com: {
        type: Object,
        default: null,
      },
      insertCmd: {
        type: Object,
        default: null,
      }
    },
    watch: {
      'com': {
        handler(val) {
          if (val == null || val == undefined) return;
          let _this = this;

          console.log("watch com", val);
          // _this.dataAttr=JSON.parse(JSON.stringify(val));
          _this.initSetting();
        },
        immediate: true, //立即执行
        deep: true
      },
      'isActive': {
        handler(val) {
          if (val == undefined && val != null) return;
          this.settings.readOnly = !val;
          this.settings.colHeaders = val;
          this.settings.rowHeaders = val;
        },
        immediate: true, //立即执行
        deep: true
      },

      'insertCmd': {
        handler(val) {
          if (val == null || !this.isActive) return;
          console.log("insertCmd table val", val);

        },
        immediate: true,
        deep: true,
      },
    },

    data() {
      return {
        cellStyle:[],
        settings: {
          language: "zh-CN",
          startRows: 5,
          startCols: 3
        },
        currentFocus: {
          row: 0,
          col: 0,
        },

      }
    },
    created() {

    },
    methods: {

      //导出
      onExport(e) {
        const exportPlugin = this.$refs.hotTable.hotInstance.getPlugin('exportFile');
        let str = exportPlugin.exportAsString('csv', {
          filename: 'MyFile'
        });

        console.log("str", str);
      },
      //初始化设置
      initSetting() {
        let _this = this;
        _this.settings = {
          language: "zh-CN",
          startRows: 1,
          startCols: 6,
          // readOnly: true,
          height: 'auto',
          stretchH: 'all',
          customBorders: true,
          licenseKey: 'non-commercial-and-evaluation',
          comments: true,
          mergeCells: true,
          allowRemoveColumn:true,
          allowRemoveRow:true,
          copyPaste: {
            columnsLimit: 25,
            rowsLimit: 50,
            pasteMode: 'shift_down',
            uiContainer: document.body,
          },
          cell:_this.cellStyle,
          contextMenu: {
            callback(key, selection, clickEvent) {
              // Common callback for all options
              console.log("callback", key, selection, clickEvent);
              // console.log("selection",selection);
              if(_this.cellStyle==undefined)_this.cellStyle=[];
              if(key=="importExcel"){
                //导入excel

                return;
              }

              if(key=="clearColor"){
                //清除样式
                 for(var i=selection[0].start.col;i<=selection[0].end.col;i++){
                   for(var j=selection[0].start.row;j<=selection[0].end.row;j++){
                     _this.cellStyle=_this.cellStyle.filter(o=>o.col!=i  && o.row!=j)
                   }
                 }
                 _this.initSetting();
                 return;
              }
              if(key.length>=8){
                if(key.substr(0,7)=='bgColor'){
                    let subKey=key.replace("bgColor:","");
                    let bgClass="whiteBg";
                    switch(subKey){
                        case "red":
                          bgClass="redBg";
                          break;
                        case "gray":
                          bgClass="grayBg";
                          break;
                    }

                    for(var i=selection[0].start.col;i<=selection[0].end.col;i++){
                      for(var j=selection[0].start.row;j<=selection[0].end.row;j++){
                        let item=_this.cellStyle.filter(o=>o.col==i && o.row==j);
                        if(item.length>0){
                          if(item[0].className.indexOf(bgClass)<0){
                            item[0].className+=" "+bgClass;
                          }
                        }else{
                          _this.cellStyle.push({
                            col:i,
                            row:j,
                            className:bgClass,
                          })
                        }
                      }
                    }
                  return;
                }
                if(key.substr(0,9)=="fontColor"){
                  //修改字体颜色
                  let subKey=key.replace("fontColor:","");
                  let fontClass="blackFont";
                    switch(subKey){
                        case "white":
                          fontClass="whiteFont";
                          break;
                        case "black":
                          fontClass="blackFont";
                          break;
                    }

                    if(_this.cellStyle==undefined)_this.cellStyle=[];
                    for(var i=selection[0].start.col;i<=selection[0].end.col;i++){
                      for(var j=selection[0].start.row;j<=selection[0].end.row;j++){
                        let item=_this.cellStyle.filter(o=>o.col==i && o.row==j);
                        if(item.length>0){
                          if(item[0].className.indexOf(fontClass)<0){
                            item[0].className+=" "+fontClass;
                          }
                        }else{
                          _this.cellStyle.push({
                            col:i,
                            row:j,
                            className:fontClass,
                          })
                        }
                      }
                    }
                    return;
                }
              }
            },
            items: {
              row_above: {
                name: "上方插入行",
                disabled() { // `disabled` can be a boolean or a function
                  // Disable option when first row was clicked
                  return this.getSelectedLast()[0] === 0; // `this` === hot
                }
              },
              row_below: {
                name: "下方插入行",
              },
              col_left: {
                name: "左侧插入列",
              },
              col_right: {
                name: "右侧插入列",
              },
              remove_row: {
                name: "删除行"
              },
              remove_col: {
                name: "删除列"
              },
              sp1: '---------',
              mergeCells: {
                name: "合并单元格"
              },
              alignment: {
                name: '对齐'
              },
              borders: {
                name: "边框"
              },
              sp2: '---------',
              importExcel:{
                name:"导入Excel",
                key:"importExcel"
              },
              sp3: '---------',
              clearColor:{
                name:"清除样式",
                key:"clearColor"
              },
              bgColor: { // Own custom option
                name: '背景颜色',
                submenu: {
                  // Custom option with submenu of items
                  items: [{
                      // Key must be in the form 'parent_key:child_key'
                      key: 'bgColor:red',
                      name: '红色',
                    },
                    {
                        // Key must be in the form 'parent_key:child_key'
                        key: 'bgColor:gray',
                        name: '灰色',
                      },
                  ],

                }
              },
              fontColor: { // Own custom option
                name: '文字颜色',
                submenu: {
                  // Custom option with submenu of items
                  items: [
                    {
                      // Key must be in the form 'parent_key:child_key'
                      key: 'fontColor:white',
                      name: '白色',
                    },
                    {
                      // Key must be in the form 'parent_key:child_key'
                      key: 'fontColor:black',
                      name: '黑色',
                    },
                  ],

                }
              },

            }
          },
          colHeaders: true,
          rowHeaders: true,
          width: '100%',
          height: 'auto',
          colWidths: 'auto',
          allowHtml: true,
          filters: true,
          manualRowResize: true, // 行高调整
          manualColumnResize: true, // 列宽调整
          manualRowMove: true, // 行移动
          manualColumnMove: true, // 列移动
          formulas: {
            engine: HyperFormula,
          },
          tableClassName: "tb-class",
          afterOnCellMouseDown: (event, coords, Td) => {
            this.currentFocus = coords
          }
        }
        registerAllModules()
      },

    }
  }
</script>

<style lang="scss">
  @import './index.scss';
</style>
