<template>
  <div class="table">
    <div style="z-index:999;" class="cent" v-if="!option.isCross">
      <el-popover
        style="height: 500px;"
        placement="bottom-end"
        width="70%"
        v-model="visible"
        trigger="visible">
        <el-row :gutter="3" style="width: 100%;padding:0.5% 0.5%">
          <el-col :span="8">
            <div class="" style="padding: 10px">
              <span>行维度：</span>
            </div>
            <div class="" style="margin-right: 2%">
              <el-select filterable clearable size="mini" placeholder="输入关键词搜索" @change="rowchange"
                         @visible-change="rowchangevisible">
                <el-option
                  v-for="item in newrowParamList"
                  :key="item.id"
                  :label="item.columnTitle || item.columnComment"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <el-card class="box-card" style="height: 30vh" :body-style="{ padding: '1px !important' }">
              <draggable v-model="rowParamListCheckList" animation="300" :scroll="true" @start="drag=true"
                         @end="drag=false">
                <li v-for="(item,index) in rowParamList" :key="item.id" class="text item">
                  <el-checkbox v-model="rowParamListCheckList" :label="item.id" :disabled="item.disabled">
                    {{ item.columnTitle ? item.columnTitle : item.columnComment }}
                  </el-checkbox>
                </li>
              </draggable>
            </el-card>
          </el-col>
          <el-col :span="8">
            <div class="" style="padding: 10px">
              <span>列维度：</span>
            </div>
            <div class="" style="margin-right: 2%">
              <el-select filterable clearable size="mini" placeholder="输入关键词搜索" @change="columnchange"
                         @visible-change="columnchangevisible">
                <el-option
                  v-for="item in newcolumnParamList"
                  :key="item.id"
                  :label="item.columnTitle || item.columnComment"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <el-card class="box-card" style="height: 30vh" :body-style="{ padding: '1px !important' }">
              <draggable v-model="columnParamListCheckList" animation="300" :scroll="true">
                <li v-for="(item,index) in columnParamList" :key="index" class="text item">
                  <el-checkbox v-model="columnParamListCheckList" :label="item.id" :disabled="item.disabled">
                    {{ item.columnTitle ? item.columnTitle : item.columnComment }}
                  </el-checkbox>
                </li>
              </draggable>
            </el-card>
          </el-col>
          <el-col :span="8">
            <div class="" style="padding: 10px">
              <span>指标：</span>
              <span style="float: right"><el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox></span>
            </div>
            <div class="" style="margin-right: 2%">
              <el-select filterable clearable size="mini" placeholder="输入关键词搜索" @change="indexchange"
                         @visible-change="indexchangevisible">
                <el-option
                  v-for="item in newindexParamList"
                  :key="item.id"
                  :label="item.columnTitle || item.columnComment"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <el-card class="box-card" style="height: 30vh" :body-style="{ padding: '1px !important' }">
              <draggable v-model="indexParamListCheckList" animation="300" :scroll="true">
                <li v-for="(item,index) in indexParamList" :key="index" class="text item">
                  <el-checkbox v-model="indexParamListCheckList" :label="item.id" :disabled="item.disabled">
                    {{ item.columnTitle || item.columnComment }}
                  </el-checkbox>
                </li>
              </draggable>
            </el-card>
          </el-col>
        </el-row>
        <el-button style="background: #409EFF;color: #fff;border-radius: 5px;float: right" size="mini"
                   type="primary"
                   @click="iszizhu=true,isPageLoad=false, deskinit()" :loading="loading">
          查询
        </el-button>
        <el-button style="color: #fff;border-radius: 5px;float: right;margin-right: 10px" size="mini" type="success"
                   @click="jiegou(true)">
          重置
        </el-button>
        <el-button style="background: #a60906;color: #fff;border-radius: 5px;float: right;"
                   size="mini" type="" @click="visible=false">
          关闭
        </el-button>
        <el-button v-if="!option.closejiegou" size="mini"
                   :style="`color: ${option.headerFontColor || '#fff'};margin-right: 10px;background: ${option.headerBackground || '#3471F9'}`"
                   :class="{'edit':$route.name == 'yewu' ? false : true}" @click="visible = !visible" slot="reference">
          结构筛选
        </el-button>
      </el-popover>
      <!--      <el-button v-if="!option.closeSearch" style="background: #409EFF;color: #fff;border-radius: 5px; "-->
      <!--                 @click="drawer = true" type="primary"-->
      <!--                 :class="{'edit':$route.name == 'yewu' ? false : true}">-->
      <!--        条件筛选-->
      <!--      </el-button>-->
      <el-button v-if="!option.closeSearch" size="mini"
                 :style="`color: ${option.headerFontColor || '#fff'};margin-right: 10px;background: ${option.headerBackground || '#3471F9'}`"
                 @click="exportExcel" type="primary"
                 :class="{'edit':$route.name == 'yewu' ? false : true}">
        导出
      </el-button>
    </div>
    <div style="display: flex;align-items: center;justify-content: space-between;">
      <div :style="{textAlign:'left',color:option.chartTitleColor,fontSize:option.chartTitleSize+'px'}">
        <span v-if="option.showChartTitle">{{ attrs.name }}</span>
      </div>
      <div v-if="option.isCross && !option.closeSearch">
        <template v-if="$attrs.unusedParamList.length > 0">
          <el-button size="mini" type="success" @click="onSubmit()" :loading="loading">查询</el-button>
          <el-button size="mini" type="success" @click="reset()">重置</el-button>
        </template>
        <el-popover
          style="height: 500px;margin-left: 10px"
          placement="bottom-end"
          width="70%"
          v-model="visible"
          trigger="visible">
          <div>
            <el-row :gutter="3" style="width: 100%;padding:0.5% 0.5%">
              <el-col :span="8">
                <div class="" style="padding: 10px">
                  <span>行维度：</span>
                </div>
                <div class="" style="margin-right: 48px">
                  <el-select filterable clearable size="mini" placeholder="输入关键词搜索" @change="rowchange"
                             @visible-change="rowchangevisible">
                    <el-option
                      v-for="item in newrowParamList"
                      :key="item.id"
                      :label="item.dimensionTitle ? item.dimensionTitle : item.dimensionComments"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
                <el-card class="box-card" style="height: 30vh" :body-style="{ padding: '1px !important' }">
                  <draggable v-model="rowParamListCheckList" animation="300" :scroll="true" @start="drag=true"
                             @end="drag=false">
                    <li v-for="(item,index) in rowParamList" :key="item.id" class="text item">
                      <el-checkbox v-model="rowParamListCheckList" :label="item.id" :disabled="item.disabled">
                        {{ item.dimensionTitle ? item.dimensionTitle : item.dimensionComments }}
                      </el-checkbox>
                    </li>
                  </draggable>
                </el-card>
              </el-col>
              <el-col :span="8">
                <div class="" style="padding: 10px">
                  <span>列维度：</span>
                </div>
                <div class="" style="margin-right: 48px">
                  <el-select filterable clearable size="mini" placeholder="输入关键词搜索" @change="columnchange"
                             @visible-change="columnchangevisible">
                    <el-option
                      v-for="item in newcolumnParamList"
                      :key="item.id"
                      :label="item.dimensionTitle ? item.dimensionTitle : item.dimensionComments"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
                <el-card class="box-card" style="height: 30vh" :body-style="{ padding: '1px !important' }">
                  <draggable v-model="columnParamListCheckList" animation="300" :scroll="true">
                    <li v-for="(item,index) in columnParamList" :key="index" class="text item">
                      <el-checkbox v-model="columnParamListCheckList" :label="item.id" :disabled="item.disabled">
                        {{ item.dimensionTitle ? item.dimensionTitle : item.dimensionComments }}
                      </el-checkbox>
                    </li>
                  </draggable>
                </el-card>
              </el-col>
              <el-col :span="8">
                <div class="" style="padding: 10px">
                  <span>指标：</span>
                </div>
                <div class="" style="margin-right: 48px">
                  <el-select filterable clearable size="mini" placeholder="输入关键词搜索" @change="indexchange"
                             @visible-change="indexchangevisible">
                    <el-option
                      v-for="item in newindexParamList"
                      :key="item.id"
                      :label="item.dimensionTitle ? item.dimensionTitle : item.dimensionComments"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
                <el-card class="box-card" style="height: 30vh" :body-style="{ padding: '1px !important' }">
                  <draggable v-model="indexParamListCheckList" animation="300" :scroll="true">
                    <li v-for="(item,index) in indexParamList" :key="index" class="text item">
                      <el-checkbox v-model="indexParamListCheckList" :label="item.id" :disabled="item.disabled">
                        {{ item.dimensionTitle ? item.dimensionTitle : item.dimensionComments }}
                      </el-checkbox>
                    </li>
                  </draggable>
                </el-card>
              </el-col>
            </el-row>
            <el-button style="background: #409EFF;color: #fff;border-radius: 5px;float: right" size="mini"
                       type="primary"
                       @click="iszizhu=true,isPageLoad=false, deskinit()" :loading="loading">
              查询
            </el-button>
            <el-button style="background: #a60906;color: #fff;border-radius: 5px;float: right;margin-right: 10px"
                       size="mini" type="" @click="visible=false">
              关闭
            </el-button>
          </div>
          <el-button type="success" v-if="!option.closejiegou" size="mini" @click="visible = !visible" slot="reference">
            结构筛选
          </el-button>
        </el-popover>
        <el-button size="mini" type="success" v-if="!option.closeSearch" @click="openExport" style="margin-left: 10px">
          导出
        </el-button>
      </div>
    </div>
    <div style="clear:both;"></div>
    <div style="height: 30px;line-height: 30px;" v-if="text">
      当前筛选:({{ text }})
    </div>
    <div style="height: 30px;line-height: 30px;" v-if="config.zuanLevel > 0">
      <el-link v-for="item in breadcrumb" @click.native="breadcrumbClick(item)"
               :style="`color: ${option.zuanFontColor}`"> {{ item.field }}-{{ item.name }}
        {{ option.zuanFenge }}
      </el-link>
    </div>
    <div :id="'xGrid'+index"></div>

    <vxe-modal v-if="showCololrSet" v-model="showCololrSet" title="设置单元格颜色" width="20%" :mask="false" :lock-view="false"
               resize :position="{top:colDialogTop,left:colDialogLeft}">
      <el-form style="padding: 10px" size="mini">
        <el-form-item label="背景颜色">
          <avue-input-color
            v-model="cellColor"
            show-alpha
          ></avue-input-color>
        </el-form-item>
        <el-form-item label="字体颜色">
          <avue-input-color
            v-model="cellFontColor"
            show-alpha
          ></avue-input-color>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="colorSetOnSubmit">确定</el-button>
          <el-button @click="showCololrSet = false">取消</el-button>
        </el-form-item>
      </el-form>
    </vxe-modal>
  </div>
</template>
<script>
    import React from 'react';
    import {copyData, copyToClipboard, download} from '@antv/s2'
    import '@antv/s2-react/dist/style.min.css';
    import {filter} from 'lodash';
    import {param} from "../../option/config";
    import {cubeFieldList} from "../../api/newbi/dataset";

    export default {
  name: "new-table",
  props: ["option", 'config', "modalSet", "index", "site", 'scale', 'ext', 'contentH'],
  data() {
    return {
      originData: [],
      screenLoadTimmer: null,
      currentScreenIndex: 0,
      attrs: this.$attrs,
      drawer: false,
      param: JSON.parse(JSON.stringify(param)),
      data: [],
      column: [],
      tabledata: [],
      paramsList: [],
      list: [],
      merge: [],
      area: [],
      form: {},
      ismonth: false,
      showTime1a: false,
      year: new Date().getFullYear(),
      fullMonth: ['第一季度', '第二季度', '第三季度', '第四季度'],
      choseQuarter: '',
      loading: false,
      text: '',
      iszizhu: false,
      gridOptions: {},
      newrowParamList: [],
      rowParamList: [],
      columnParamList: [],
      rowParamListCheckList: [],
      columnParamListCheckList: [],
      newcolumnParamList: [],
      indexParamList: [],
      newindexParamList: [],
      indexParamListCheckList: [],
      visible: false,
      intervalInvorkTimmer: null,
      week: '',
      colProperties: [],
      colColors: [],
      tableExport: {
        // 默认选中类型
        type: 'xlsx',
        // 自定义类型
        types: ['xlsx', 'csv'],
        mode: 'current',
        isMerge: true,
        modes: ['current']
      },
      showCololrSet: false,
      colDialogTop: 0,
      colDialogLeft: 0,
      cellColor: '',
      cellFontColor: '',
      currentColColors: [],
      isPageLoad: true,
      autoResize: true,
      zoom: 1,
      width: '',
      height: '',

      zuanIndex: -1,
      breadcrumb: [{'name': '首页', 'field': '全部', 'index': 0}],

      checkAll: false,
      isIndeterminate: true
    };
  },
  watch: {
    site: {
      handler() {
        this.s2util();
      },
      deep: true,
    },
    option: {
      handler() {
        this.s2util();
      },
      deep: true,
    },
    visible(val) {
      if (val) {
        this.config.zuanLevel = 0
        this.breadcrumbClick({'name': '首页', 'field': '全部', 'index': 0})
      }
    },
    rowParamListCheckList: {
      handler(newValue) {
        console.log(newValue)
        this.rowParamListCheck = []
        this.rowParamList = []
        let rowParamList = []
        XEUtils.arrayEach(newValue, (value) => {
          let dimensionitem = XEUtils.find(this.oldlist, itemm => itemm.id === value)
          this.rowParamListCheck.push(dimensionitem)
        })
        XEUtils.arrayEach(this.oldlist, (item) => {
          if (item.dimensionType === 'WEIDU') {
            item.disabled = false
            rowParamList.push(item)
          }
        })
        newValue.forEach(v=>{
          if (this.columnParamListCheckList.includes(v)){
            let indexrow = this.columnParamListCheckList.findIndex(val=>val === v)
            this.columnParamListCheckList.splice(indexrow,1)
          }
        })
        let newrowParamList = g.subtract(rowParamList, this.rowParamListCheck, function (a, b) {
          if (a.id == b.id) {
            return true;
          }
        });
        this.rowParamList = XEUtils.uniq(this.rowParamListCheck.concat(newrowParamList)).filter(i => i)
      },
      deep: true
    },
    columnParamListCheckList: {
      handler(newValue) {
        this.columnParamListCheck = []
        this.columnParamList = []
        let columnParamList = []
        XEUtils.arrayEach(newValue, (value) => {
          let dimensionitem = XEUtils.find(this.oldlist, itemm => itemm.id === value)
          this.columnParamListCheck.push(dimensionitem)
        })
        XEUtils.arrayEach(this.oldlist, (item) => {
          if (item.dimensionType === 'WEIDU') {
            item.disabled = false
            columnParamList.push(item)
          }
        })
        newValue.forEach(v=>{
          if (this.rowParamListCheckList.includes(v)){
            let indexrow = this.rowParamListCheckList.findIndex(val=>val === v)
            this.rowParamListCheckList.splice(indexrow,1)
          }
        })
        let newcolumnParamList = g.subtract(columnParamList, this.columnParamListCheck, function (a, b) {
          if (a.id == b.id) {
            return true;
          }
        });
        this.columnParamList = XEUtils.uniq(this.columnParamListCheck.concat(newcolumnParamList)).filter(i => i)
      },
      deep: true
    },
    indexParamListCheckList: {
      handler(newValue) {
        this.indexParamListCheck = []
        this.indexParamList = []
        let indexParamList = []
        XEUtils.arrayEach(newValue, (value) => {
          let dimensionitem = XEUtils.find(this.oldlist, itemm => itemm.id === value)
          this.indexParamListCheck.push(dimensionitem)
        })
        XEUtils.arrayEach(this.oldlist, (item) => {
          if (item.dimensionType === 'ZHIBIAO') {
            item.disabled = false
            indexParamList.push(item)
          }
        })
        let newrowParamList = g.subtract(indexParamList, this.indexParamListCheck, function (a, b) {
          if (a.id == b.id) {
            return true;
          }
        });
        this.indexParamList = [...this.indexParamListCheck, ...newrowParamList]
      },
      deep: true
    },
  },
  computed: {},
  mounted() {
    this.oldconfigrowParamList = JSON.parse(JSON.stringify(this.config.rowParamList))
    this.oldconfigcolumnParamList = JSON.parse(JSON.stringify(this.config.columnParamList))
    this.oldconfigindexParamList = JSON.parse(JSON.stringify(this.config.indexParamList))
    this.jiegou()
  },
  methods: {
    rowchangevisible(e) {
      let newrowParamList = []
      if (e) {
        this.rowParamList.forEach(item => {
          if (XEUtils.indexOf(this.rowParamListCheckList, item.id) == -1 && XEUtils.indexOf(this.columnParamListCheckList, item.id) == -1) {
            newrowParamList.push(item)
          }
        })
        this.newrowParamList = newrowParamList
      }
    },
    rowchange(e) {
      this.rowParamListCheckList.push(e)
    },
    columnchangevisible(e) {
      let newcolumnParamList = []
      if (e) {
        this.rowParamList.forEach(item => {
          if (XEUtils.indexOf(this.columnParamListCheckList, item.id) == -1 && XEUtils.indexOf(this.rowParamListCheckList, item.id) == -1) {
            newcolumnParamList.push(item)
          }
        })
        this.newcolumnParamList = newcolumnParamList
      }
    },
    columnchange(e) {
      this.columnParamListCheckList.push(e)
    },
    indexchangevisible(e) {
      let newindexParamList = []
      if (e) {
        this.indexParamList.forEach(item => {
          if (XEUtils.indexOf(this.indexParamListCheckList, item.id) == -1) {
            newindexParamList.push(item)
          }
        })
        this.newindexParamList = newindexParamList
      }
    },
    jiegou(isReset = false) {
      let {dataId, zuan} = this.config;
      if (isReset) {
        this.rowParamListCheckList = []
        this.columnParamListCheckList = []
        this.indexParamListCheckList = []
        this.config.rowParamList = JSON.parse(JSON.stringify(this.oldconfigrowParamList))
        this.config.columnParamList = JSON.parse(JSON.stringify(this.oldconfigcolumnParamList))
        this.config.indexParamList = JSON.parse(JSON.stringify(this.oldconfigindexParamList))
        XEUtils.arrayEach(this.config.rowParamList, (value) => {
          this.rowParamListCheckList.push(value.cubeColumnId)
        })
        XEUtils.arrayEach(this.config.columnParamList, (value) => {
          this.columnParamListCheckList.push(value.cubeColumnId)
        })
        XEUtils.arrayEach(this.config.indexParamList, (value) => {
          this.indexParamListCheckList.push(value.cubeColumnId)
        })
      } else {
        cubeFieldList({cubeDataId: dataId}).then((res) => {
          this.oldlist = res.data.data
          this.rowParamList = res.data.data
            .filter((i) => i.id && i.dimensionType === "WEIDU")
            .sort((a, b) => a.sortNum - b.sortNum).map(v => {
              v.extJson = {hidden: false}
              return v
            });
          if (this.config.zuanFlag) {
            let newZuan = zuan.filter((item) => item.zuan)[0]
            this.rowParamList.map(item => {
              if (item.id === newZuan.cubeColumnId) {
                return item.zuan = true
              }
            })
          }
          this.columnParamList = JSON.parse(JSON.stringify(this.rowParamList)).map(v => {
            v.extJson = {hidden: false}
            return v
          })
          this.indexParamList = res.data.data
            .filter((i) => i.dimensionType === "ZHIBIAO")
            .sort((a, b) => a.sortNum - b.sortNum).map(v => {
              v.extJson = {hidden: false}
              return v
            });
          this.oldrowParamList = g.toHash(this.rowParamList, 'columnName');
          this.oldcolumnParamList = g.toHash(this.columnParamList, 'columnName');
          this.oldindexParamList = g.toHash(this.indexParamList, 'columnName');
          if (this.rowParamListCheckList.length < 1) {
            XEUtils.arrayEach(this.config.rowParamList, (value) => {
              this.rowParamListCheckList.push(value.cubeColumnId)
            })
            XEUtils.arrayEach(this.config.columnParamList, (value) => {
              this.columnParamListCheckList.push(value.cubeColumnId)
            })
            XEUtils.arrayEach(this.config.indexParamList, (value) => {
              this.indexParamListCheckList.push(value.cubeColumnId)
            })
          }
        });
      }
    },
    handleCheckAllChange(val) {
      this.indexParamListCheckList.length = 0
      if (val) {
        XEUtils.arrayEach(this.indexParamList, (value) => {
          this.indexParamListCheckList.push(value.id)
        })
      } else {
        XEUtils.arrayEach(this.oldconfigindexParamList, (value) => {
          if (value.cubeColumnId) {
            this.indexParamListCheckList.push(value.cubeColumnId)
          }
        })
      }
    },
    colorSetOnSubmit() {
      if(XEUtils.isUndefined(this.option.conditions)){
        this.option.conditions = []
      }
      let columnAliasName = this.config.indexParamList.find(item => item.columnTitle === this.valueField).columnAliasName
      this.option.conditions.push({
        bgcolor: this.cellColor || '#fff',
        color: this.cellFontColor || '#fff',
        field: columnAliasName,
        maxExpress: "<",
        maxValue: "",
        minExpress: "===",
        minValue: this.fieldValue,
        operatorn: "&&",
      })
      this.showCololrSet = false
    },
    s2util() {
      const getTargetColor = (value, v) => {
        let color = '#000'
        let bgcolor = ''
        let minExpress = ''
        v.forEach(item => {
          value = parseFloat(value)
          let minValue = +item.minValue
          let maxValue = +item.maxValue
          if (!maxValue) {
            minExpress = `${value} ${item.minExpress} ${minValue}`;
          } else {
            minExpress = `${value} ${item.minExpress} ${minValue} ${item.operatorn} ${value} ${item.maxExpress} ${maxValue}`;
          }
          if (eval(minExpress)) {
            color = item.color
            bgcolor = item.bgcolor
          }
        })
        return {'bgcolor': bgcolor, 'color': color}
      }
      const onColCellDouble = (e) => {
        let indexParamList = this.config.indexParamList.find(v=>v.columnTitle === e.viewMeta.value)
        this.$bus.$emit('newTableOption',indexParamList)
      }
      const onContextMenu = (e) => {
        this.colDialogLeft = e.event.clientX;
        this.colDialogTop = e.event.clientY;
        this.showCololrSet = false;
        setTimeout(() => {
          this.showCololrSet = true;
          this.valueField = e.viewMeta.valueField
          this.fieldValue = e.viewMeta.fieldValue
        }, 10)
      }
      let {rowParamList, columnParamList, indexParamList} = this.config;
      rowParamList = [...rowParamList].filter((i) => !i.extJson.hidden);
      columnParamList = [...columnParamList].filter((i) => !i.extJson.hidden);
      indexParamList = [...indexParamList].filter((i) => !i.extJson.hidden);
      let weidu = JSON.parse(JSON.stringify(rowParamList))
      if (this.config.zuanLevel < 1) {
        this.zuanIndex = weidu.findIndex(item => {
          return item.zuan
        })
      }
      if (this.config.zuanFlag) {
        let zuanField = this.config.zuan[this.config.zuanLevel];
        weidu.splice(this.zuanIndex, 1, zuanField);
      }
      let rows = []
      let columns = []
      let values = []
      let meta = []
      let conditions = {
        text: [],
        background: [],
      }
      let conditionsgroup = XEUtils.groupBy(this.option.conditions, 'field')
      let sheetType = this.option.ismerge ? 'pivot' : 'table'
      weidu.forEach((item) => {
        rows.push(item.columnTitle)
        meta.push({field: item.columnTitle, name: item.columnTitle})
      })
      columnParamList.forEach((item) => {
        columns.push(item.columnTitle)
        meta.push({field: item.columnTitle, name: item.columnTitle})
      })

      let {unifiedMinExpress,unifiedValue,unifiedFontColor,unifiedBgColor} = this.option
      indexParamList.forEach((item) => {
        values.push(item.columnTitle)
        meta.push({
          field: item.columnTitle,
          name: item.columnTitle,
          formatter: (val) => {
            return val
          },
        })
        if(unifiedMinExpress){
          if (unifiedFontColor){
            conditions.text.push({
              'field': item.columnTitle,
              mapping(value) {
                value = parseFloat(value)
                let unifiedMinExpresss = `${value} ${unifiedMinExpress} ${unifiedValue}`;
                if (eval(unifiedMinExpresss) && value) {
                  return {
                    fill: unifiedFontColor,
                  };
                }else{
                  return {
                    fill: '#000',
                  };
                }
              },
            })
          }
          if (unifiedBgColor){
            conditions.background.push({
              'field': item.columnTitle,
              mapping(value) {
                value = parseFloat(value)
                let unifiedMinExpresss = `${value} ${unifiedMinExpress} ${unifiedValue}`;
                if (eval(unifiedMinExpresss) && value) {
                  return {
                    fill: unifiedBgColor,
                  };
                }else{
                  return {
                    fill: 'rgba(255, 0, 0, 0)',
                  };
                }
              },
            })
          }
        }
        let key = item.columnAliasName;
        if (this.option.conditions && conditionsgroup[key]) {
          conditionsgroup[key].forEach(v => {
            conditions.text.push({
              'field': item.columnTitle,
              mapping(value) {
                const {color} = getTargetColor(value, conditionsgroup[key]);
                return {
                  fill: color,
                };
              },
            })
            conditions.background.push({
              'field': item.columnTitle,
              mapping(value) {
                const {bgcolor} = getTargetColor(value, conditionsgroup[key]);
                return {
                  fill: bgcolor,
                };
              },
            })
          })
        }
      })
      this.s2DataConfig = {
        fields: {
          rows: rows,
          columns: columns,
          values: values,
          valueInCols: true
        },
        meta: meta,
        data: this.originData,
      }
      if (!this.option.ismerge) {
        this.s2DataConfig = {
          fields: {
            columns: [...rows, ...columns, ...values],
          },
          meta: meta,
          data: this.originData,
        };
      }
      if (this.contentH) {
        this.height = this.site.h * 48
      } else {
        this.width = this.site.w * this.scale / 100
        this.height = this.site.h - 15
      }
      this.s2options = {
        height: this.height,
        hierarchyType: this.option.istree ? 'tree' : 'grid',
        tooltip: {
          showTooltip: true
        },
        showSeriesNumber:false,
        devicePixelRatio:2,
        hdAdapter: true,
        supportCSSTransform: true,
        placeholder: this.option.placeholder || '-',
        showSeriesNumber: this.option.showSeriesNumber,
        totals: {
          row: {
            showGrandTotals: this.option.isshowsummary,
            showSubTotals: this.option.isshowsummary && this.option.isshowsubsummary,
            reverseLayout: this.option.reverseLayout ? false : true,
            reverseSubLayout: true,
            label: this.option.totalTitle,
            subTotalsDimensions: rows,
          },
          col: {
            showGrandTotals: this.option.isshowsubcolsummary,
            showSubTotals: this.option.isshowsubcolsummary,
            reverseLayout: this.option.reverseLayout ? false : true,
            reverseSubLayout: true,
            label: this.option.coltitle || '合计',
            subLabel: '小计',
            subTotalsDimensions: rows,
          }
        },
        style: {
          layoutWidthType: 'adaptive',
          'cellCfg': {
            height: 36
          }
        },
        headerActionIcons: [
          {
            iconNames: ['DrillDownIcon'],
            belongsCell: 'rowCell',
            displayCondition: (meta) => {
              if (meta.level == this.zuanIndex && meta.value != '小计' && meta.value != (this.option.totalTitle || '总计')) {
                return true
              }
            },
            action: (props) => {
              this.dirill(props)
            },
          },
        ],
        conditions: conditions,
        layoutDataPosition: (s2, getCellData) => {
          const getCellMeta = (rowIndex, colIndex) => {
            const viewMeta = getCellData(rowIndex, colIndex);
            if (viewMeta.rowId === 'root[&]'+(this.option.totalTitle || '总计') || g.like(viewMeta.rowId, '小计')) {
              let sum = null
              let fieldValue = `${this.option.placeholder || '-'}`
              if (this.option.subTotalsDimensions && this.option.subTotalsDimensions.includes(viewMeta.valueField)){
                sum = null
              }else{
                let displayData = viewMeta.spreadsheet.dataSet.displayData
                let param = {}
                if (viewMeta.rowQuery) {
                  param = {...param, ...viewMeta.rowQuery}
                }
                if (viewMeta.colQuery) {
                  param = {...param, ...viewMeta.colQuery}
                }
                let filterdisplayData = filter(displayData, param)
                sum = g.sum(filterdisplayData, [viewMeta.valueField])
                if (this.option.totalToFixed){
                  sum = sum[viewMeta.valueField].toFixed(`${this.option.totalToFixed}`);
                }else{
                  sum = sum[viewMeta.valueField];
                }
              }
              if (sum != 0) {
                fieldValue = this.option.isTableThousandPoint && (sum >= 1000 || sum <= 1000) ? g.cuter(sum,this.option.spaceNumber || 3) : sum
              }
              return {
                ...viewMeta,
                fieldValue: fieldValue,
              };
            } else {
              let fieldValue = `${this.option.placeholder || '-'}`
              let extJson = this.config.indexParamList.find(v=>v.columnTitle === viewMeta.valueField)
              let numberDataFormatToSymbol = ''
              if (extJson.numberDataFormat === 'CUSTOM'){
                numberDataFormatToSymbol = extJson.extJson.numberDataFormatToSymbol;
              }
              if (viewMeta.fieldValue == 0){
                viewMeta.fieldValue = null
              }
              if (viewMeta.fieldValue){
                if (this.option.unifiedToFixed || this.option.unifiedToFixed == 0){
                  viewMeta.fieldValue = Number(viewMeta.fieldValue).toFixed(this.option.unifiedToFixed || 0)
                }
                viewMeta.fieldValue = this.option.isTableThousandPoint && (viewMeta.fieldValue >= 1000 || viewMeta.fieldValue <= 1000) ?
                  g.cuter(viewMeta.fieldValue, this.option.spaceNumber || 3) : `${viewMeta.fieldValue}${numberDataFormatToSymbol}`
              }else{
                viewMeta.fieldValue = fieldValue
              }
            }
            return viewMeta;
          };
          return getCellMeta;
        },
        enableCopy: true,
      }

      this.s2Theme = {};

      const getSpreadSheet = (instance) => {
        this.instance = instance
      }

      let s2Palette = {
        basicColors: [
          this.option.headerFontColor || '#FFFFFF',
          this.option.bodyBackground || '#F4F7FE',
          this.option.bodyBackground || '#DDE7FD',
          this.option.headerBackground || '#3471F9',
          this.option.headerBackground || '#2C60D3',
          this.option.headerBackground || '#2C60D3',
          this.option.headerBackground || '#0000EE',
          this.option.headerBackground || '#326EF4',
          this.option.evenRowBGC || '#FFFFFF',//偶行
          this.option.borderLineWidth || '#E0E9FE', //边框
          this.option.headerBackground || '#5286F9',
          this.option.borderLineWidth || '#5286F9',//左侧边框颜色
          this.option.headerBackground || '#3471F9',
          this.option.bodyFontColor || '#282B33',//表格主题颜色
          this.option.bodyFontColor || '#121826',
        ],
        semanticColors: {
          red: '#FF4D4F',
          green: '#29A294',
        },
      };


      let TextTheme = {
        textAlign: this.option.bodyTextAlign || 'center',
        fontSize: this.option.fontSize || '12',
        fontWeight: this.option.headerFontWeight,
      }
      let CellTheme = {
        crossBackgroundColor: this.option.oddRowBGC || '#fff',
        verticalBorderWidth: this.option.borderLineWidth || 1,
        horizontalBorderWidth: this.option.borderLineWidth || 1,
        horizontalBorderColor: this.option.borderLineColor || 'rgba(3, 3, 3, 0.37)',
        verticalBorderColor: this.option.borderLineColor || 'rgba(3, 3, 3, 0.37)',
      }
      let DefaultCellTheme = {
        bolderText: TextTheme,
        text: TextTheme,
        cell: CellTheme
      }
      let customTheme = {
        cornerCell: DefaultCellTheme,
        rowCell: DefaultCellTheme,
        colCell: DefaultCellTheme,
        dataCell: DefaultCellTheme,
        scrollBar: {
          hoverSize: 23,
          size: 8
        }
      }
      this.s2Theme.name = 'colorful'
      this.s2Theme.palette = s2Palette
      this.s2Theme.theme = customTheme
      this.loading = false
      this.visible = false
      const s2 = new PivotSheet(document.getElementById('xGrid' + this.index), this.s2DataConfig, this.s2options)
      s2.render()
      // ReactDOM.render(
        //   <SheetComponent
        //     sheetType={sheetType}
        //     themeCfg={this.s2Theme}
        //     dataCfg={this.s2DataConfig}
        //     options={this.s2options}
        //     getSpreadSheet={getSpreadSheet}
        //     onDataCellDoubleClick={onContextMenu}
        //     onColCellDoubleClick={onColCellDouble}
        //     adaptive={{width: true, height: false}}
        //   />,
        //   document.getElementById('xGrid' + this.index),
      // );
    },
    exportExcel() {
      const data = copyData(this.instance, ',', true)
      copyToClipboard(data)
        .then(() => {
        })
        .catch(() => {
        })
      download(data, '导出')
    },
    update(data) {
      this.originData = data;
      this.s2util();
    },
    breadcrumbClick(props) {
      if (this.config.zuanLevel <= 0) return;
      this.config.zuanLevel = props.index;
      this.config.zuanStack = this.config.zuanStack.slice(
        0,
        this.config.zuanLevel
      );
      if (props.index < 1) {
        this.breadcrumb = [{'name': '首页', 'field': '全部', 'index': 0}]
      } else {
        this.breadcrumb.splice(props.index)
      }
      this.$emit("preview");
    },
    dirill(props) {
      if (this.config.zuanLevel + 1 >= this.config.zuan.length) {
        return this.$message({
          type: "warning",
          message: "已经钻取到最后一层了",
        });
      }
      this.config.zuanStack.push(props.meta.value);
      this.config.zuanLevel += 1;
      this.breadcrumb.push({'name': props.meta.value, 'field': props.meta.field, 'index': this.config.zuanLevel})
      this.$emit("preview");
    },
    deskinit() {
      this.loading = true
      this.config.rowParamList.length = 0
      this.config.columnParamList.length = 0
      this.config.indexParamList.length = 0
      let rowParamList = this.rowParamListCheckList
      let columnParamList = this.columnParamListCheckList
      let indexParamList = this.indexParamListCheckList
      let columnList = []
      rowParamList.forEach((item) => {
        let itemm = this.oldlist.find(v => v.id === item)
        itemm.cubeColumnId = itemm.id
        columnList.push(itemm)
        this.config.rowParamList.push(itemm)
      })
      columnParamList.forEach((item) => {
        let itemm = this.oldlist.find(v => v.id === item)
        itemm.cubeColumnId = itemm.id
        columnList.push(itemm)
        this.config.columnParamList.push(itemm)
      })
      indexParamList.forEach((item) => {
        let itemm = this.oldlist.find(v => v.id === item)
        itemm.cubeColumnId = itemm.id
        columnList.push(itemm)
        this.config.indexParamList.push(itemm)
      })
      this.$emit("preview", true, true, [], true);
      return false
    },
    isjiegou() {
      this.visible = true
    },
    initRender() {
      let config = {
        "dataType": "CUBE",
        "category": "",
        "dataId": 27,
        "rowParamList": [{
          "cubeDataId": 27,
          "tableName": "POWERBI_XIAOSHOUSHUJU",
          "tableAliasName": "SrFmG",
          "columnTitle": "门店",
          "columnName": "COL_2",
          "columnComment": "门店",
          "oldViewDataType": "STRING",
          "viewDataType": "STRING",
          "dimensionType": "WEIDU",
          "columnAttr": "NORMAL",
          "numberDataFormat": "AUTO",
          "timeDataFormat": "yyyy_MM_ddhh$mm$ss",
          "aggregationType": "SUM",
          "columnFormula": "",
          "hiddenStatus": 0,
          "sortNum": 6,
          "columnSql": "SrFmG.COL_2",
          "zuan": false,
          "cubeColumnId": 1625
        }, {
          "cubeDataId": 27,
          "tableName": "POWERBI_CHANPIN",
          "tableAliasName": "eQyyf",
          "columnTitle": "产品名称",
          "columnName": "COL_3",
          "columnComment": "产品名称",
          "oldViewDataType": "STRING",
          "viewDataType": "STRING",
          "dimensionType": "WEIDU",
          "columnAttr": "NORMAL",
          "numberDataFormat": "AUTO",
          "timeDataFormat": "yyyy_MM_ddhh$mm$ss",
          "aggregationType": "SUM",
          "columnFormula": "",
          "hiddenStatus": 0,
          "sortNum": 12,
          "columnSql": "eQyyf.COL_3",
          "zuan": false,
          "cubeColumnId": 1631
        }],
        "columnParamList": [],
        "indexParamList": [{
          "cubeDataId": 27,
          "tableName": "POWERBI_XIAOSHOUSHUJU",
          "tableAliasName": "SrFmG",
          "columnTitle": "数量",
          "columnName": "COL_5",
          "columnComment": "数量",
          "oldViewDataType": "NUMBER",
          "viewDataType": "NUMBER",
          "dimensionType": "ZHIBIAO",
          "columnAttr": "NORMAL",
          "numberDataFormat": "AUTO",
          "timeDataFormat": "yyyy_MM_ddhh$mm$ss",
          "aggregationType": "SUM",
          "columnFormula": "",
          "hiddenStatus": 0,
          "sortNum": 1,
          "columnSql": "SrFmG.COL_5",
          "zuan": false,
          "cubeColumnId": 1641
        }, {
          "cubeDataId": 27,
          "tableName": "POWERBI_CHANPIN",
          "tableAliasName": "eQyyf",
          "columnTitle": "价格",
          "columnName": "COL_4",
          "columnComment": "价格",
          "oldViewDataType": "NUMBER",
          "viewDataType": "NUMBER",
          "dimensionType": "ZHIBIAO",
          "columnAttr": "NORMAL",
          "numberDataFormat": "AUTO",
          "timeDataFormat": "yyyy_MM_ddhh$mm$ss",
          "aggregationType": "SUM",
          "columnFormula": "",
          "hiddenStatus": 0,
          "sortNum": 2,
          "columnSql": "eQyyf.COL_4",
          "zuan": false,
          "cubeColumnId": 1642
        }]
      };
      this.config = config
      let originData = '[{"ROW_ID":"1","数量":"3","价格":"96","门店":"安庆市","产品名称":"美式大杯"},{"ROW_ID":"2","数量":"1","价格":"24","门店":"安庆市","产品名称":"美式小杯"},{"ROW_ID":"3","数量":"12","价格":"174","门店":"安庆市","产品名称":"美式中杯"},{"ROW_ID":"4","数量":"25","价格":"490","门店":"安庆市","产品名称":"摩卡大杯"},{"ROW_ID":"5","数量":"44","价格":"620","门店":"安庆市","产品名称":"摩卡小杯"},{"ROW_ID":"6","数量":"79","价格":"1320","门店":"安庆市","产品名称":"摩卡中杯"},{"ROW_ID":"7","数量":"66","价格":"1260","门店":"安庆市","产品名称":"拿铁大杯"},{"ROW_ID":"8","数量":"52","价格":"868","门店":"安庆市","产品名称":"拿铁小杯"},{"ROW_ID":"9","数量":"130","价格":"2013","门店":"安庆市","产品名称":"拿铁中杯"},{"ROW_ID":"10","数量":"1","价格":"36","门店":"安庆市","产品名称":"卡布奇诺大杯"},{"ROW_ID":"11","数量":"11","价格":"170","门店":"安庆市","产品名称":"卡布奇诺中杯"},{"ROW_ID":"12","数量":"5","价格":"96","门店":"包头市","产品名称":"美式大杯"},{"ROW_ID":"13","数量":"4","价格":"48","门店":"包头市","产品名称":"美式小杯"},{"ROW_ID":"14","数量":"11","价格":"174","门店":"包头市","产品名称":"美式中杯"},{"ROW_ID":"15","数量":"25","价格":"490","门店":"包头市","产品名称":"摩卡大杯"},{"ROW_ID":"16","数量":"35","价格":"496","门店":"包头市","产品名称":"摩卡小杯"},{"ROW_ID":"17","数量":"54","价格":"891","门店":"包头市","产品名称":"摩卡中杯"},{"ROW_ID":"18","数量":"125","价格":"2065","门店":"包头市","产品名称":"拿铁大杯"},{"ROW_ID":"19","数量":"152","价格":"2170","门店":"包头市","产品名称":"拿铁小杯"},{"ROW_ID":"20","数量":"239","价格":"4323","门店":"包头市","产品名称":"拿铁中杯"},{"ROW_ID":"21","数量":"5","价格":"72","门店":"包头市","产品名称":"卡布奇诺大杯"},{"ROW_ID":"22","数量":"7","价格":"96","门店":"包头市","产品名称":"卡布奇诺小杯"},{"ROW_ID":"23","数量":"5","价格":"102","门店":"包头市","产品名称":"卡布奇诺中杯"},{"ROW_ID":"24","数量":"9","价格":"96","门店":"北海市","产品名称":"美式大杯"},{"ROW_ID":"25","数量":"4","价格":"48","门店":"北海市","产品名称":"美式小杯"},{"ROW_ID":"26","数量":"9","价格":"116","门店":"北海市","产品名称":"美式中杯"},{"ROW_ID":"27","数量":"52","价格":"735","门店":"北海市","产品名称":"摩卡大杯"},{"ROW_ID":"28","数量":"43","价格":"806","门店":"北海市","产品名称":"摩卡小杯"}]'
      this.originData = JSON.parse(originData)
      this.s2util();
    },
  },
};
</script>
<style lang="scss" scoped>
.table {
  width: 100%;
  height: 100%;
}

.box-card {
  font-size: 14px;
  width: 100%;
  height: 300px;
  overflow: auto;

  li {
    margin-bottom: 5px;
    list-style: none;
    border: solid 1px #eee;
    padding: 5px;
    overflow: hidden;
  }

  .item {
    margin-right: 2%
  }

  .item:hover {
    cursor: move;
  }
}

.el-card__body {
  padding: 5px !important
}

.cent {
  /*height: 100px;*/
  width: 100%;
  right: 4px;
  text-align: right;
  position: absolute;
  top: -30px;
}

.edit {
  opacity: 0;
  transition: 0.3s;
  -webkit-transition: .5s;
  -moz-transition: .5s;
}

.cent:hover .edit {
  color: #656e73;
  opacity: 1;
}
</style>
