<template>
  <div class="height100 flexbox pivot-contanier">
    <div class="left-con" :style="{width:showSettings?'200px':'0'}">
      <ts-button
        @click="toggleShowSettings"
        class="setting-btn"
      >{{ showSettings?hideSettingsText:showSettingsText }}</ts-button>
      <!-- <div
        v-if="dsObj.dsName&&(internal.screenFieldKeys.length>0||internal.rowFieldKeys.length>0||internal.colFieldKeys.length>0)"
        class="font12 setting-btn"
      >所属数据源：【{{dsObj.dsName}}】</div>-->
      <div
        v-show="showSettings"
        class="drag-area border-primary val-drag"
        :class="dragAreaClass"
        @dragenter="dropEnterHandler($event,'valFieldKeys')"
        @drop="dropHandler($event,'valFieldKeys')"
        @dragover="dragOver($event,'valFieldKeys')"
      >
        <div class="drag-area-title mb-3">值</div>
        <draggable
          v-model="internal.valFieldKeys"
          class="d-flex flex-row drag-area-zone"
          group="fields"
          handle=".btn-draggable"
          @start="start"
          @end="end"
        >
          <el-tag
            class="btn-draggable"
            v-for="(tag,index) in internal.valFieldKeys"
            :key="index"
            closable
            size="small"
            @close="removeItem($event, index,'valFieldKeys',tag)"
          >{{tag}}</el-tag>
        </draggable>
      </div>
      <div
        v-show="showSettings"
        class="drag-area border-primary flex"
        :class="dragAreaClass"
        @dragenter="dropEnterHandler($event,'rowFieldKeys')"
        @drop="dropHandler($event,'rowFieldKeys')"
        @dragover="dragOver($event,'rowFieldKeys')"
      >
        <div class="drag-area-title mb-3">{{ rowsLabelText }}</div>
        <draggable
          v-model="internal.rowFieldKeys"
          class="d-flex align-items-start drag-area-zone"
          group="fields"
          handle=".btn-draggable"
          @start="start"
          @end="end"
        >
          <el-tag
            class="btn-draggable"
            v-for="(tag,index) in internal.rowFieldKeys"
            :key="index"
            closable
            size="small"
            @close="removeItem($event, index,'rowFieldKeys',tag)"
          >{{tag}}</el-tag>
          <!-- </div> -->
        </draggable>
      </div>
    </div>
    <div class="right-con" :style="{width:showSettings?'calc(100% - 200px)':'100%'}">
      <div
        v-show="showSettings"
        class="drag-area"
        :class="dragAreaScreenClass"
        @dragenter="dropEnterHandler($event,'screenFieldKeys')"
        @drop="dropHandler($event,'screenFieldKeys')"
        @dragover="dragOver($event,'screenFieldKeys')"
      >
        <div class="drag-area-title mb-3">{{ screenFieldsLabelText }}</div>
        <draggable
          v-model="internal.screenFieldKeys"
          class="d-flex flex-row drag-area-zone"
          group="fields111"
          handle=".btn-draggable"
        >
          <el-tag
            class="btn-draggable"
            v-for="(tag,index) in internal.screenFieldKeys"
            :key="index"
            closable
            size="small"
            @close="removeItem($event, index,'screenFieldKeys',tag)"
          >{{tag}}</el-tag>
        </draggable>
      </div>
      <div
        v-show="showSettings"
        class="drag-area border-primary"
        :class="dragAreaClass"
        @dragenter="dropEnterHandler($event,'colFieldKeys')"
        @drop="dropHandler($event,'colFieldKeys')"
        @dragover="dragOver($event,'colFieldKeys')"
      >
        <div class="drag-area-title mb-3">{{ colsLabelText }}</div>
        <draggable
          v-model="internal.colFieldKeys"
          class="d-flex flex-row drag-area-zone"
          group="fields"
          handle=".btn-draggable"
          @start="start"
          @end="end"
        >
          <el-tag
            class="btn-draggable"
            v-for="(tag,index) in internal.colFieldKeys"
            :key="index"
            closable
            size="small"
            @close="removeItem($event, index,'colFieldKeys',tag)"
          >{{tag}}</el-tag>
        </draggable>
      </div>
      <div
        class="pivot-table-con"
        ref="pivotTableCon"
        :style="{marginTop:showSettings?'8px':'35px',height:showSettings?('calc(100% - '+tableMarginH+'px)'):'calc(100% - 55px)'}"
      >
        <!-- <ts-loading :loading="loading"></ts-loading> -->
        <pivot-table
          v-if="rowFields.length>0||colFields.length>0"
          :data="data"
          :row-fields="rowFields"
          :col-fields="colFields"
          :val-fields="valFields"
          :reducer="reducer"
          :reducer-initial-value="reducerInitialValue"
          :no-data-warning-text="noDataWarningText"
          :is-data-loading="isDataLoading"
          :showFooter="true"
          :labelSlotName="labelSlotName"
          ref="pivotTable"
        >
          <template v-for="(_, slot) of $scopedSlots" v-slot:[slot]="scope">
            <slot :name="slot" v-bind="scope" />
          </template>
        </pivot-table>
        <!-- <ts-empty v-else-if="!loading&&data.length==0" /> -->
      </div>
    </div>
  </div>
</template>

<script>
// import { PivotTable, FieldLabel } from '@click2buy/vue-pivot-table'
import Draggable from 'vuedraggable'
import PivotTable from './PivotTable'
import previewRealDate from '../../utils/dateUtils'
// import naturalSort from 'javascript-natural-sort'

export default {
  name: 'pivot',
  components: { PivotTable, Draggable },
  props: {
    data: {
      type: Array,
      default: () => []
    },
    fields: {
      type: Array,
      default: () => []
    },
    availableFieldKeys: {
      type: Array,
      default: () => []
    },
    screenFieldKeys: {
      //筛选
      type: Array,
      default: () => []
    },
    rowFieldKeys: {
      type: Array,
      default: () => []
    },
    colFieldKeys: {
      type: Array,
      default: () => []
    },
    valFieldKeys: {
      type: Array,
      default: () => []
    },
    reducer: {
      type: Function,
      default: sum => sum + 1
    },
    reducerInitialValue: {
      default: 0
    },
    defaultShowSettings: {
      type: Boolean,
      default: true
    },
    availableFieldsLabelText: {
      type: String,
      default: 'Available fields'
    },
    screenFieldsLabelText: {
      type: String,
      default: 'Available fields'
    },
    colsLabelText: {
      type: String,
      default: 'Columns'
    },
    rowsLabelText: {
      type: String,
      default: 'Rows'
    },
    hideSettingsText: {
      type: String,
      default: 'Hide settings'
    },
    showSettingsText: {
      type: String,
      default: 'Show settings'
    },
    noDataWarningText: {
      type: String,
      default: 'No data to display.'
    },
    selectAllText: {
      type: String,
      default: 'Select all'
    },
    unselectAllText: {
      type: String,
      default: 'Unselect all'
    },
    isDataLoading: {
      type: Boolean,
      default: false
    },
    labelSlotName: {
      type: String,
      default: ''
    }
  },
  data: function() {
    const fieldValues = {}
    this.fields
      .filter(field => field.valueFilter)
      .forEach(field => {
        fieldValues[field.key] = {}
      })

    return {
      fieldValues,
      internal: {
        availableFieldKeys: this.availableFieldKeys,
        screenFieldKeys: this.screenFieldKeys,
        rowFieldKeys: this.rowFieldKeys,
        colFieldKeys: this.colFieldKeys,
        valFieldKeys: this.valFieldKeys
      },
      dragging: false,
      showSettings: true,
      dragAreaScreenClass: '',
      loading: false,
      tableMarginH: 140,
      dataBusiCode: [],
      dataDateType: [],
      dataPivotType: [],
      dsObj: { dsId: '', dsName: '' }, //保存数据源id
      dragObj: { dragType: '', dragItem: {} } // 从外移动的item
    }
  },
  computed: {
    // Fields with values extracted from data (if field has valueFilter)
    fieldsWithValues: function() {
      // Create object: field.key => field
      const fieldsWithValues = {}

      this.fields.forEach(field => {
        fieldsWithValues[field.key] = field
      })

      // Add valuesSet
      const valueFilterableFields = this.fields.filter(
        field => field.valueFilter
      )

      // Create valuesSet for each value filterable field
      valueFilterableFields.forEach(field => {
        fieldsWithValues[field.key].valuesSet = new Set()
      })

      // Iterate on data once
      this.data.forEach(item => {
        valueFilterableFields.forEach(field => {
          fieldsWithValues[field.key].valuesSet.add(field.getter(item))
        })
      })

      // Creates values sorted from valuesSet
      valueFilterableFields.forEach(field => {
        fieldsWithValues[field.key].values = Array.from(
          fieldsWithValues[field.key].valuesSet
        ).sort(field.sort)
      })

      return fieldsWithValues
    },
    // Fields selected values as set
    valuesFiltered: function() {
      const valuesFiltered = {}

      for (let [key, valuesObject] of Object.entries(this.fieldValues)) {
        valuesFiltered[key] = new Set()
        valuesObject.forEach(valueObject => {
          if (valueObject.checked) {
            valuesFiltered[key].add(valueObject.value)
          }
        })
      }

      return valuesFiltered
    },
    // Pivot table props from Pivot props & data
    rowFields: function() {
      const rowFields = []

      this.internal.rowFieldKeys.forEach(key => {
        const field = this.fields.find(field => field.label === key)
        if (field) {
          // // Generate headerSlotNames from headers
          if (field.headers) {
            field.headerSlotNames = field.headers
              .filter(header => header.checked)
              .map(header => header.slotName)
          }

          // Add selected values
          if (field.valueFilter) {
            field.valuesFiltered = this.valuesFiltered[field.key]
          }

          rowFields.push(field)
        }
      })
      return rowFields
    },
    valFields() {
      const valFields = []
      for (let i = this.internal.valFieldKeys.length - 1; i >= 0; i--) {
        let key = this.internal.valFieldKeys[i]
        const field = this.fields.find(field => field.label === key)
        valFields.push({ key: field.key, label: field.label })
      }
      return valFields
    },
    colFields: function() {
      const colFields = []
      this.internal.colFieldKeys.forEach(key => {
        const field = this.fields.find(field => field.label === key)
        if (field) {
          if (field.headers) {
            field.headerSlotNames = field.headers
              .filter(header => header.checked)
              .map(header => header.slotName)
          }

          // Add selected values
          if (field.valueFilter) {
            field.valuesFiltered = this.valuesFiltered[field.key]
          }

          colFields.push(field)
        }
      })
      return colFields
    },
    // Drag area class
    dragAreaClass: function() {
      return this.dragging ? 'drag-area-highlight' : null
    }
  },
  methods: {
    // 获取表格据顶部高度
    getTableMarginH() {
      this.$nextTick(() => {
        this.tableMarginH = this.$refs.pivotTableCon.offsetTop + 16
      })
    },
    //  删除项
    removeItem(ev, index, type, tag) {
      ev.stopPropagation()
      this.internal[type].splice(index, 1)
      for (let i in this.$parent.fields) {
        let field = this.$parent.fields[i]
        if (field.label == tag) {
          if (this.dataBusiCode.indexOf(field.dragId) > -1) {
            this.dataBusiCode.splice(this.dataBusiCode.indexOf(field.dragId), 1)
          } else if (
            this.dataPivotType.findIndex(res => res.id == field.dragId) > -1
          ) {
            this.dataPivotType.splice(
              this.dataPivotType.findIndex(res => res.id == field.dragId),
              1
            )
          } else if (
            this.dataDateType.findIndex(res => res.id == field.dragId) > -1
          ) {
            this.dataDateType.splice(
              this.dataDateType.findIndex(res => res.id == field.dragId),
              1
            )
          }
          this.$parent.fields.splice(i, 1)
          break
        }
      }
      if (this.dataBusiCode.length > 0) {
        // 指标不能为空
        this.$parent.getData(
          this.dataBusiCode,
          this.dataPivotType,
          this.dataDateType
        )
      }
    },
    // Toggle settings
    toggleShowSettings: function() {
      this.showSettings = !this.showSettings
    },
    dragOver(e) {
      e.preventDefault()
    },
    dragstart(ev, type, item) {
      // if (!this.validateDsId(item)) {
      //   // 验证数据源ID是否为同一个
      //   return
      // }
      this.dragging = false
      if (item.isScreen) {
        this.dragAreaScreenClass = 'drag-area-highlight'
      }
      this.dragging = true
      this.dragObj = { dragType: type, dragItem: item }
    },
    dropHandler(event, type) {
      if (
        !this.dragObj.dragItem ||
        (!this.dragAreaScreenClass && !this.dragging) ||
        (type == 'screenFieldKeys' &&
          this.dragObj.dragType.indexOf('condition') > -1 &&
          !this.dragObj.dragItem.isScreen)
      ) {
        return
      }
      if (type != 'screenFieldKeys') {
        // 筛选，不进入数据访问参数
        this.getPivotData(this.dragObj.dragType, this.dragObj.dragItem, type)
      }
      // if (type == 'screenFieldKeys') {
      this.dragAreaScreenClass = ''
      // } else {
      //   if (!this.dragging) {
      //     return
      //   }
      this.dragging = false
      // }
      //参数
      if (
        type == 'screenFieldKeys' &&
        this.dragObj.dragType.indexOf('condition') > -1 &&
        this.dragObj.dragItem.isScreen
      ) {
        this.setFieldKeys('screenFieldKeys')
      } else {
        if (type == 'valFieldKeys') {
          // 值
          this.setFieldKeys(type)
        } else {
          this.setRowColFieldKeys(type, 'rowFieldKeys', 'colFieldKeys')
          this.setRowColFieldKeys(type, 'colFieldKeys', 'rowFieldKeys')
        }
      }
      this.dragObj = {}
    },
    setRowColFieldKeys(type, keyName, keys) {
      if (type != keyName) {
        return
      }
      if (
        this.dragObj.dragItem.children &&
        this.dragObj.dragItem.children.length > 0
      ) {
        for (let item of this.dragObj.dragItem.children) {
          if (type == keyName && this.internal[keys].indexOf(item.name) > -1) {
            let index = this.internal[keys].indexOf(item.name)
            this.internal[keys].splice(index, 1)
          }
          this.internal[keyName].indexOf(item.name) == -1
            ? this.internal[keyName].push(item.name)
            : ''
        }
      } else {
        let name = this.dragObj.dragItem.name
        if (this.internal[keys].indexOf(name) > -1) {
          let index = this.internal[keys].indexOf(name)
          this.internal[keys].splice(index, 1)
        }
        this.internal[keyName].indexOf(name) == -1
          ? this.internal[keyName].push(name)
          : ''
      }
    },
    // 设置所有值
    setFieldKeys(keyName) {
      if (
        this.dragObj.dragItem.children &&
        this.dragObj.dragItem.children.length > 0
      ) {
        for (let item of this.dragObj.dragItem.children) {
          this.internal[keyName].indexOf(item.name) == -1
            ? this.internal[keyName].push(item.name)
            : ''
        }
      } else {
        let name = this.dragObj.dragItem.name
        this.internal[keyName].indexOf(name) == -1
          ? this.internal[keyName].push(name)
          : ''
      }
      // // 去重
      // this.internal[keyName] = Array.from(new Set(this.internal[keyName]))
    },
    dropEnterHandler(event, type) {
      if (!this.dragObj.dragItem) {
        return
      }
    },
    // 拖拽停止
    dragend(ev, type, item) {
      if (type.indexOf('condition') > -1) {
        this.dragAreaScreenClass = ''
      }
      this.dragging = false
    },
    start: function() {
      this.dragging = true
    },

    end: function() {
      this.dragging = false
    },
    //首次添加，绑定数据源
    getPivotData(dragType, dragItem) {
      if (dragType.indexOf('column') > -1) {
        let index = this.$parent.fields.findIndex(
          res => res.label == dragItem.name
        )
        if (index == -1) {
          // 不存在，则加入
          this.$parent.fields.push({
            key:
              dragType.indexOf('condition') > -1
                ? dragItem.code
                : dragItem.name,
            getter: item =>
              dragType.indexOf('condition') > -1
                ? item[dragItem.code]
                : item[dragItem.name],
            label: dragItem.name,
            dragId: dragItem.id,
            valueFilter: true
          })
          // 添加预览信息
          if (dragItem.type == 'condition') {
            // 维度
            if (dragItem.flag == 'dateType') {
              this.dataDateType.push(dragItem)
            } else {
              this.dataPivotType.push(dragItem)
            }
          } else {
            this.dataBusiCode.push(dragItem.code)
          }
          if (this.dataBusiCode.length > 0) {
            // 指标不能为空
            this.$parent.getData(
              this.dataBusiCode,
              this.dataPivotType,
              this.dataDateType
            )
          }
        }
      }
    },
    // Update fieldValues
    updateFieldValues: function() {
      for (let [key, field] of Object.entries(this.fieldsWithValues)) {
        if (field.valueFilter) {
          this.fieldValues[key] = []
          field.values.forEach(value => {
            this.fieldValues[key].push({ value, checked: true })
          })
        }
      }
    },
    // 得到预览的表头
    getPreviewTableCols() {
      let cols = []
      for (let item of this.rowFields) {
        // row头部
        cols.push({
          title: '',
          field: item.key,
          type: 'html',
          width: 120,
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:black;font-weight:bold">' +
              (cellValue || '') +
              '</div>'
            )
          }
        })
      }
      if (!this.colFields || this.colFields.length == 0) {
        // 行数据
        // 列为空
        cols.push({
          title: '',
          field: 'valxxxx',
          type: 'html',
          width: 120,
          align: 'right'
        })
        return cols
      }
      //列有值
      if (
        this.$refs.pivotTable &&
        this.$refs.pivotTable.cols &&
        this.$refs.pivotTable.cols.length > 0 // 列数据
      ) {
        let colHeader = [...this.$refs.pivotTable.tableHeader.colHeaderFields]
        this.setChildrenCols(colHeader, 0, 0, cols, 0, [])
      }
      return cols
    },
    setChildrenCols(colHeader, i, colspan, newCols, index, pField) {
      for (let j = i; j < colHeader[index].cols.length; j++) {
        let col = colHeader[index].cols[j]
        colspan = index == 0 ? col.colspan : colspan - col.colspan
        if (colspan > -1) {
          let pField2 = [...pField]
          pField2.push(col.value) // 保留父级表头
          // 行数值
          let tempCol = {
            title:
              col.value && col.value.indexOf('(') == 0
                ? col.value.substring(
                    col.value.indexOf(')') + 1,
                    col.value.length
                  )
                : col.value, // 去除()
            field: JSON.stringify(pField2), // 将key改成唯一
            children: [],
            // align: index == colHeader.length - 1?'right':'',
            width: 120
          }
          if (index == colHeader.length - 1) {
            // 最子级
            tempCol.align = 'right'
          }
          if (index < colHeader.length - 1) {
            i = this.setChildrenCols(
              colHeader,
              i,
              col.colspan,
              tempCol.children,
              index + 1,
              pField2
            )
          }
          newCols.push(tempCol)
        } else {
          i = j // 终止
          break
        }
      }
      return i
    },
    // // 递归处理预览表头
    // setChildrenCols2(newCols, i, col) {
    //   let tempCol = newCols.find(
    //     item => item.field === JSON.stringify(col.slice(0, i + 1))
    //   )
    //   if (!tempCol) {
    //     // 找存在，防止重复添加
    //     tempCol = {
    //       title:
    //         col[i] && col[i].indexOf('(') == 0
    //           ? col[i].substring(col[i].indexOf(')') + 1, col[i].length)
    //           : col[i], // 去除()
    //       field: JSON.stringify(col.slice(0, i + 1)), // 将key改成唯一
    //       children: [],
    //       align: i == col.length - 1 ? 'right' : 'center',
    //       width: 120
    //     }
    //     newCols.push(tempCol)
    //   }
    //   if (i < col.length - 1) {
    //     this.setChildrenCols(tempCol.children, i + 1, col)
    //   }
    // },
    // // 递归处理预览表头
    // setChildrenCols(newCols, i, col) {
    //   let tempCol = newCols.find(
    //     item => item.field === JSON.stringify(col.slice(0, i + 1))
    //   )
    //   if (!tempCol) {
    //     // 找存在，防止重复添加
    //     tempCol = {
    //       title:
    //         col[i] && col[i].indexOf('(') == 0
    //           ? col[i].substring(col[i].indexOf(')') + 1, col[i].length)
    //           : col[i], // 去除()
    //       field: JSON.stringify(col.slice(0, i + 1)), // 将key改成唯一
    //       children: [],
    //       align: i == col.length - 1 ? 'right' : 'center',
    //       width: 120
    //     }
    //     newCols.push(tempCol)
    //   }
    //   if (i < col.length - 1) {
    //     this.setChildrenCols(tempCol.children, i + 1, col)
    //   }
    // },
    // 得到预览的数据
    getPreviewTableDatas() {
      let datas = []
      let mergeCells = []
      if (!this.$refs.pivotTable) {
        return { datas: [], mergeCells: [] }
      }
      this.$refs.pivotTable.tableRows.forEach((tr, j) => {
        let obj = {}
        tr.rowHeaderFields.forEach((rf, i) => {
          if (rf.rowspan) {
            mergeCells.push({ row: j, col: i, rowspan: rf.rowspan, colspan: 1 })
          }
          obj[rf.key] = rf.value || ''
          for (let col of this.$refs.pivotTable.sortedCols) {
            let code = JSON.stringify(col) // 带条件的字段key值
            let nCol = col
            let value = this.$refs.pivotTable.value(tr.row, col)
            obj[code] = value
          }
        })
        datas.push(obj)
      })
      return { datas: datas, mergeCells: mergeCells }
    },
    // 获取预览的筛选框
    getPreviewTableFiltrate(dataSourceTree) {
      let filtrate = []
      for (let item of this.internal.screenFieldKeys) {
        switch (item) {
          case '天':
            filtrate.push({
              title: '时间',
              startName: 'beginDate',
              endName: 'endDate',
              width: '200px',
              type: 'date',
              value:
                previewRealDate.getRealDate('prev').startDate +
                ' ~ ' +
                previewRealDate.getRealDate('prev').endDate,
              event: this.refreshPivotPreview
            })
            break
          case '季度':
            filtrate.push({
              title: '季度',
              name: 'quarters',
              placeholder: '请选择季度',
              width: '200px',
              inputType: 'quarter',
              type: 'search',
              event: this.refreshPivotPreview,
              isbutton: true,
              value: '',
              max: this.$utils.getTodayDate('date')
            })
            break
          case '年度':
            filtrate.push({
              title: '年度',
              name: 'years',
              placeholder: '请选择年度',
              width: '120px',
              inputType: 'year',
              type: 'search',
              valueFormat: 'yyyyY',
              event: this.refreshPivotPreview,
              isbutton: true,
              value: '',
              max: this.$utils.getTodayDate('date')
            })
            break
          case '月度':
            filtrate.push({
              title: '月度',
              name: 'months',
              placeholder: '请选择月度',
              width: '120px',
              inputType: 'month',
              type: 'search',
              event: this.refreshPivotPreview,
              isbutton: true,
              valueFormat: 'yyyyYMM',
              value: '',
              max: this.$utils.getTodayDate('date')
            })
            break
          case '院区':
            filtrate.push({
              title: '院区',
              name: 'orgIds',
              type: 'select',
              width: '200px',
              deploy: {
                dataType: 'json',
                url: '/ts-query/api/user/query/table/query',
                method: 'POST',
                data: {
                  roleCode:  '',//global.userInfo.sysRoleCode,
                  userId:  '',//global.userInfo.id,
                  id: '611786aca31d827e6268556c'
                },
                page: 'pageNo',
                code: 'CODE',
                text: 'NAME',
                condition: 'condition'
              },
              event: this.refreshPivotPreview
            })
            break
          case '科室':
            filtrate.push({
              title: '科室',
              name: 'ksdms',
              type: 'select',
              width: '200px',
              deploy: {
                dataType: 'json',
                url: '/ts-bi/api/OfMzZbkMonth/dept/tree/list',
                method: 'get',
                data: [],
                code: 'id',
                text: 'name',
                children: 'children',
                tree: true,
                treeType: 'checkbox',
                treeExpand: false,
                isLoading: false,
                isClose: true,
                noParent: true,
                choice: true
              },
              event: this.refreshPivotPreview
            })
            break
        }
      }
      return filtrate
    },
    refreshPivotPreview(val, ev) {
      this.$nextTick(() => {
        if (this.dataBusiCode.length > 0) {
          let param = { ...this.$parent.$parent.$refs.previewTable.filterObj }
          for (let pa of Object.keys(param)) {
            if (pa == 'months' && param[pa]) {
              param[pa] = param[pa].replace('-', 'Y') + 'M'
            } else if (pa == 'quarters' && param[pa]) {
              param[pa] = this.$parent.$parent.$refs.previewTable.$refs[
                pa
              ][0].$refs.tsInput.inputValue
                .replace(' 年第 ', 'Y')
                .replace(' 季度', 'Q')
            }
          }
          // 指标不能为空
          this.$parent.getData(
            this.dataBusiCode,
            this.dataPivotType,
            this.dataDateType,
            param
          )
        }
      })
    },
    // 得到新增other数据
    getOtherDatas() {
      return {
        fields: this.fields,
        internal: this.internal,
        dataBusiCode: this.dataBusiCode,
        dataPivotType: this.dataPivotType,
        dataDateType: this.dataDateType
      }
    },
    // 设置other数据
    setOtherDatas(other) {
      if (other) {
        other = JSON.parse(other)
        for (let field of other.fields) {
          field.getter = item => item[field.key]
        }
        this.$parent.fields = other.fields
        this.$nextTick(() => {
          this.internal = other.internal
          this.dataBusiCode = other.dataBusiCode
          this.dataPivotType = other.dataPivotType
          this.dataDateType = other.dataDateType
          if (this.dataBusiCode.length > 0) {
            // 指标不能为空
            this.$parent.getData(
              this.dataBusiCode,
              this.dataPivotType,
              this.dataDateType
            )
          }
        })
      }
    }
  },
  watch: {
    data: function() {
      this.updateFieldValues()
    },
    'internal.screenFieldKeys': {
      handler(n) {
        this.getTableMarginH()
      },
      deep: true
    },
    'internal.colFieldKeys': {
      handler(n) {
        this.getTableMarginH()
      },
      deep: true
    }
  },
  created: function() {
    this.showSettings = this.defaultShowSettings
    this.updateFieldValues()
  }
}
</script>

<style lang="scss" scoped>
.pivot-contanier {
  .left-con {
    .setting-btn {
      margin: 8px;
    }
  }
  .right-con {
    .pivot-table-con {
      width: calc(100% - 16px);
      padding: 8px;
    }
  }
}
.el-tag {
  margin: 0 5px 5px 0;
  cursor: move;
}
.drag-area {
  border: 1px dashed #ccc;
  padding: 8px;
  margin: 8px !important;
  transition: background-color 0.4s;

  .drag-area-title {
    line-height: 1;
  }
}

.drag-area-highlight {
  background-color: #f3f3f3;
  border-color: var(--base-acv);
}

.sortable-ghost {
  opacity: 0.4;
}
.val-drag {
  min-width: 200px - 36px;
}

.field {
  position: relative;
}
</style>
