<!-- @desc:透视表  @auth:周兴  @time:2023/3/18 17:21 -->
<template>
  <div>
    <DkModal
      :title="title"
      v-model="visible"
      :mask-closable="false"
      :mask="false"
      :closable="false"
      :loading="loading"
      draggable
      sticky
      fullscreen
      :save-flag="settingFlag"
      :autoClearFlag="false"
      @modalOk="modalOk"
      @modalCancel="modalCancel"
      :ok-visible-flag="false"
    >
      <DkPivot
        ref="dkPivot"
        :data="tableData"
        :fields="fields"
        :availableFieldsLabelText="vm.$t('Available fields')"
        :colsLabelText="vm.$t('columns')"
        :rowsLabelText="vm.$t('rows')"
        :dataLabelText="vm.$t('data')"
        :available-field-keys="availableFieldKeys"
        :row-field-keys="rowFieldKeys"
        :col-field-keys="colFieldKeys"
        :data-field-keys="dataFieldKeys"
        :reducer="reducer"
        :default-show-settings="defaultShowSettings"
      >
        <div slot="button">
          <DkButton @click="choosePlan">选择方案</DkButton>
          <DkButton @click="savePlan">保存方案</DkButton>
          <DkButton @click="managerPlan">方案管理</DkButton>
        </div>
      </DkPivot>

    </DkModal>

    <DkModal
      ref="choosePlanModal"
      title="选择方案"
      v-model="choosePlanShow"
      @modalOk="choosePlanOk"
      width="600px"
    >
      <DkTable ref="table-plan" :data="planList"
               :pageFlag="false"
               :show-setting-flag="false"
               :choose-flag="false"
               primary-key="planId"
      >
        <DkTableColumn field="flgCustom" type="switch"></DkTableColumn>
        <DkTableColumn field="name"></DkTableColumn>
        <DkTableColumn field="remarks"></DkTableColumn>
      </DkTable>
    </DkModal>

    <DkModal
      ref="savePlanModal"
      title="保存方案"
      v-model="savePlanShow"
      @modalOk="savePlanOk">
      <DkForm ref="savePlanForm" v-model="savePlanForm" :col-count="1" :label-max-words="2">
        <DkFormItem prop="name" required>
          <InputPop v-model="savePlanForm.name" />
        </DkFormItem>
        <DkFormItem prop="remarks">
          <InputPop v-model="savePlanForm.remarks" textareaFlag/>
        </DkFormItem>
        <DkFormItem prop="flgDefault" :label="vm.$t('ownerFlag')">
          <DkSwitch v-model="savePlanForm.flgDefault" />
        </DkFormItem>
      </DkForm>
    </DkModal>

    <DkModal
      ref="managePlanModal"
      title="方案管理"
      v-model="managePlanShow"
      @modalOk="managePlanOk"
      width="800px">
      <vxe-table ref="table-manage" :data="planList.filter(f => f.flgValid)" align="center" height="300px" border>
        <vxe-column type="seq" :title="vm.$t('seq')" width="60"></vxe-column>
        <vxe-column field="flgDefault" :title="vm.$t('defaultPlan')" align="center">
          <template #default="{ row }">
            <dk-switch v-model="row.flgDefault" @on-change="(e)=>changeDefault(e,row)" style="margin-bottom: 5px" :disabled="!row.flgCustom"/>
          </template>
        </vxe-column>
        <vxe-column field="name" :title="vm.$t('name')">
          <template #default="{ row }">
            <InputPop v-model="row.name" />
          </template>
        </vxe-column>
        <vxe-column field="remarks" :title="vm.$t('remarks')">
          <template #default="{ row }">
            <InputPop v-model="row.remarks" />
          </template>
        </vxe-column>
        <vxe-column align="center" width="60">
          <template #default="{ row }">
            <DkButton size="small" type="error" style="margin-bottom: 5px" @click="deletePlan(row.planId)" :disabled="!row.flgCustom">{{vm.$t('delete')}}</DkButton>
          </template>
        </vxe-column>
      </vxe-table>
    </DkModal>

  </div>
</template>

<script>
import {button as buttonList} from "@/locale/lang/zh-CN";
import DkPivot from "./dk-pivot"
import data from './data'

export default {
  name: "dk-perspective",
  components: {DkPivot},
  data() {
    const vm = window.vm;
    return {
      documentKeyDownContent: Object,
      vm: vm,
      split: 0.5,
      loading: false,
      settingFlag: false,// 是否设置界面过来
      sqlId: null,// 自定义报表sqlId
      reportId: null,// 自定义报表Id
      title: '系统提示',//标题
      visible: false,//显示控制
      okFunc: () => {
      },//确定回调
      changeFunc: () => {
      },
      okText: vm.$t('confirm'),
      searchText: '', // 查询内容
      exchangeText: '',// 替换内容
      options: [],   // 源数据
      tableData: [],
      columns: [],
      columnsData: [],  // 数据列
      columnsCol: [],  // 列数据
      columnsRow: [],  // 行数据
      tableHeight: 400,
      component: null,
      equalFlag: false,// 是否单元格匹配
      sortable: null,
      sortableData: null,
      mouseLocation: {},// 鼠标所在位置
      currentTable: null, // 鼠标拖入的表格
      asyncData: [],

      // Pivot params
      fields: [{
        key: 'country',
        getter: item => item.country,
        label: 'Country',
        headers: [{
          slotName: 'countryFlagHeader',
          label: 'Flag',
          checked: true
        }, {
          slotName: 'countryNameHeader',
          label: 'Name',
          checked: true
        }],
        headerAttributeFilter: true,
        valueFilter: true
      }, {
        key: 'gender',
        getter: item => item.gender,
        label: 'Gender',
        headerSlotName: 'genderHeader',
        valueFilter: true,
        valueFilterSlotName: 'genderHeader'
      }, {
        key: 'year',
        getter: item => item.year,
        label: 'Year',
        valueFilter: true
      }, {
        key: 'count',
        getter: item => item.count,
        label: 'count',
      }, {
        key: 'score',
        getter: item => item.score,
        label: 'score',
      }],
      availableFieldKeys: [],
      rowFieldKeys: [],
      colFieldKeys: [],
      dataFieldKeys: [],
      reducer: (sum, item) => sum + item.count,
      defaultShowSettings: true,
      isDataLoading: false,

      // Pivot table standalone field params
      rowFields: [{
        getter: item => item.country,
        label: 'Country',
        headerSlotNames: ['countryFlagHeader', 'countryNameHeader']
      }, {
        getter: item => item.gender,
        label: 'Gender',
        headerSlotName: 'genderHeader'
      }],
      colFields: [{
        getter: item => item.year,
        label: 'Year'
      }],
      dataFields: [{
        getter: item => item.count,
        label: 'count'
      }],
      //选择方案弹窗显示
      choosePlanShow: false,
      //保存方案弹窗显示
      savePlanShow: false,
      //管理方案弹窗显示
      managePlanShow: false,
      //保存方案表单
      savePlanForm: {
        name: null,
        remarks: null,
        flgDefault: true,
        page: vm.$route.name
      },
      //当前方案
      currentPlanId: null,
      //方案数据源
      planList: [],
    }
  },
  watch: {
    visible(n, o) {
      if (!n) {
        //回复快捷键
        document.onkeydown = this.documentKeyDownContent;
      } else {
        this.detail();// 查询已经设置过的透视表
      }
    }
  },
  methods: {
    /**
     * @desc   : 查询明细
     * @author : 周兴
     * @date   : 2023/3/28 17:51
     */
    detail() {
      this.loading = true;
      this.excute(this.$service.customReportService,
        this.$service.customReportService.selectByReport, {
          reportId: this.reportId,
          sqlId: this.sqlId,
          ftyId: vm.$store.state.user.ftyId
        }, false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          if (res.data && res.data.sqlList && res.data.sqlList.length > 0) {
            let sqlItem = res.data.sqlList[0]
            // 是透视表才会处理
            if(sqlItem.flgPivot){
              sqlItem.pivotData.colFields.forEach(item => {
                this.colFieldKeys.push(item.key);
              })
              sqlItem.pivotData.rowFields.forEach(item => {
                this.rowFieldKeys.push(item.key);
              })
              sqlItem.pivotData.dataFields.forEach(item => {
                this.dataFieldKeys.push(item.key);
              })
            }
          }
          this.loading = false
        }
      })
    },
    /**
     * @desc   : 保存当前的透视表格式
     * @author : 周兴
     * @date   : 2023/5/18 15:52
     */
    modalOk() {
      if (this.settingFlag) {
        let pivotData = {
          rowFields: this.$refs.dkPivot.rowFields,
          colFields: this.$refs.dkPivot.colFields,
          groupCols: this.$refs.dkPivot.groupCols,
          dataFields: this.$refs.dkPivot.dataFields,
        }
        let params = {
          pivotData: pivotData,
          flgPivot: true,
          sqlId: this.sqlId
        }
        this.loading = true;
        this.excute(this.$service.customReportService, this.$service.customReportService.updateReportSql, params).then(res => {
          if (res.code === this.$config.SUCCESS_CODE) {
            this.$Message.success(vm.$t('I_001', {'param': vm.$t('save')}))
            this.visible = false
          } else {
            this.$Message.warning(res.message)
          }
          this.loading = false
        })
      }
    },
    modalCancel() {
    },
    countryCode: function (country) {
      switch (country) {
        case 'Australia':
          return 'au'
        case 'China':
          return 'cn'
        case 'France':
          return 'fr'
        case 'India':
          return 'in'
        case 'United States':
          return 'us'
      }
    },
    /**
     * @desc   : 确定
     * @author : 周兴
     * @date   : 2023/3/19 16:44
     */
    handleConfirm() {

    },
    /**
     * @desc   : 把列加入数据，列和行
     * @author : 周兴
     * @date   : 2023/3/19 14:36
     */
    switchChange(e) {
      //开启时，需要关闭其他
      if (e.checked) {
        if (e.switchType === 'data') {
          this.columnsData.push(({title: e.title, field: e.field}))
          if (e.col) {
            this.columnsCol = this.columnsCol.filter(it => it.field !== e.field)
          }
          if (e.row) {
            this.columnsRow = this.columnsRow.filter(it => it.field !== e.field)
          }
          this.$set(e, 'col', false)
          this.$set(e, 'row', false)
        } else if (e.switchType === 'col') {
          this.columnsCol.push(({title: e.title, field: e.field}))
          if (e.data) {
            this.columnsData = this.columnsData.filter(it => it.field !== e.field)
          }
          if (e.row) {
            this.columnsRow = this.columnsRow.filter(it => it.field !== e.field)
          }
          this.$set(e, 'data', false)
          this.$set(e, 'row', false)
        } else if (e.switchType === 'row') {
          this.columnsRow.push(({title: e.title, field: e.field}))
          if (e.data) {
            this.columnsData = this.columnsData.filter(it => it.field !== e.field)
          }
          if (e.col) {
            this.columnsCol = this.columnsCol.filter(it => it.field !== e.field)
          }
          this.$set(e, 'col', false)
          this.$set(e, 'data', false)
        }
      }
    },
    /**
     * @desc   : 设置序号的数据源
     * @author : 周兴
     * @date   : 2022/12/5 11:38
     */
    setDisplayTable() {
      if (this.columns && this.columns.length > 0) {
        this.fields = []
        this.availableFieldKeys = []
        this.columns.forEach(it => {
          let item = {
            key: it.field,
            label: it.title,
            valueFilter: true,
            type: it.type,
            getter: item => item[it.field],
          }
          if (it.type === 'switch') {
            item.sort = (a, b) => {
              return b - a
            }
          }
          this.fields.push(item);
          this.availableFieldKeys.push(it.field)
        })
        // for (let i = 0; i < this.columns.length; i++) {
        //   if (this.columns[i].type == 'checkbox' || this.columns[i].type == 'radio') {
        //     this.columns[i].label = '选择'
        //   } else {
        //     this.columns[i].label = this.columns[i].title
        //   }
        // }
        // console.log('333', this.fields, this.availableFieldKeys)
      }
    },
    /**
     * @desc   : 获取列
     * @author : 周兴
     * @date   : 2023/3/18 18:10
     */
    getComponentColumns() {
      let fields = []
      // 获取显示的列
      let tableColumns = this.component.getTableColumn()
      if (tableColumns && tableColumns.visibleColumn && tableColumns.visibleColumn.length > 0) {
        tableColumns.visibleColumn.forEach(it => {
          // 按时不支持数值
          if (!it.type || (it.type && it.type !== 'select' && it.type !== 'tableSelect' && it.type !== 'checkbox'
            && it.type !== 'radio' && it.type !== 'number')) {
            fields.pushNoRepeat(it);
          }
        })
      }
      this.fields = fields;
    },
    /**
     * @desc   : 监听全局键盘按钮按下的事件
     * @author : 周兴
     * @date   : 2022/3/4 16:57
     */
    addKeyBoardEvent() {
      let code = 0
      let self = this
      this.documentKeyDownContent = document.onkeydown;
      document.onkeydown = function (e) {
        const evn = e || event
        const key = evn.keyCode || evn.which || evn.charCode
        // alt：code = 18
        if (key === 18) {
          code = 18
        }
        // Q：code = 81 查询
        let btList = Object.values(self.$config.button);
        btList.forEach(forIt => {
          if (code === 18 && forIt.hotKey?.toLowerCase() === e.key.toLowerCase()) {
            e.returnValue = false
            if (self.$refs[forIt.name]) {
              self.$refs[forIt.name].$el.click()
            }
          }
        })
      }
      // 监听全局键盘按钮松开的事件
      document.onkeyup = function (e) {
        const evn = e || event
        const key = evn.keyCode || evn.which || evn.charCode
        if (key === 18) {
          code = 0
        }
        // 一秒钟失效，避免因为按了alt+tab之后再回来，按其他什么英文字母都不好使了的问题
        setTimeout(() => {
          code = 0
        }, 1000)
      }
    },
    /**
     * @desc   : 选择方案
     * @author : 洪旭东
     * @date   : 2023-09-27 14:53
     */
    choosePlan () {
      this.choosePlanShow = true
      this.$nextTick(()=>{
        for (let el of this.$refs.choosePlanModal.$children[0].$el.children) {
          el.style.zIndex +=1
        }
      })
    },
    /**
     * @desc   : 保存方案
     * @author : 洪旭东
     * @date   : 2023-09-27 14:08
     */
    savePlan () {
      this.savePlanShow = true
      this.$nextTick(()=>{
        for (let el of this.$refs.savePlanModal.$children[0].$el.children) {
          el.style.zIndex +=1
        }
      })
    },
    /**
     * @desc   : 管理方案
     * @author : 洪旭东
     * @date   : 2023-09-27 14:08
     */
    managerPlan () {
      this.getPlan()
      this.managePlanShow = true
      this.$nextTick(()=>{
        for (let el of this.$refs.managePlanModal.$children[0].$el.children) {
          el.style.zIndex +=1
        }
      })
    },
    /**
     * @desc   : 选择方案
     * @author : 洪旭东
     * @date   : 2023-09-27 14:55
     */
    choosePlanOk () {
      if (this.$refs['table-plan'].batchRows.length) {
        let row = this.$refs['table-plan'].batchRows[0]
        this.$refs.dkPivot.internal.rowFieldKeys = row.row
        this.$refs.dkPivot.internal.colFieldKeys = row.col
        this.$refs.dkPivot.internal.dataFieldKeys = row.value
        this.currentPlanId = row.planId
      }
      this.choosePlanShow = false
    },
    /**
     * @desc   : 保存方案确定
     * @author : 洪旭东
     * @date   : 2023-09-27 14:13
     */
    savePlanOk(){
      let param = this.savePlanForm
      param.row = this.$refs.dkPivot.internal.rowFieldKeys
      param.col = this.$refs.dkPivot.internal.colFieldKeys
      param.value = this.$refs.dkPivot.internal.dataFieldKeys
      this.excute(this.$service.perspectiveColPlanService, this.$service.perspectiveColPlanService.insert, param).then(res=>{
        if (res.code === this.$config.SUCCESS_CODE) {
          this.$Message.success(res.message)
          this.savePlanShow = false
          this.$refs.savePlanForm.resetFields()
        } else {
          this.$Message.error(res.message)
        }
      })
    },
    /**
     * @desc   : 管理方案确定
     * @author : 洪旭东
     * @date   : 2023-09-27 14:13
     */
    managePlanOk(){
      this.excute(this.$service.perspectiveColPlanService, this.$service.perspectiveColPlanService.update, this.planList).then(res=>{
        if (res.code === this.$config.SUCCESS_CODE) {
          this.managePlanShow = false
          this.getPlan()
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message)
        }
      })
    },
    /**
     * @desc   : 查询方案
     * @author : 洪旭东
     * @date   : 2023-09-27 16:07
     */
    getPlan () {
      this.excute(this.$service.perspectiveColPlanService, this.$service.perspectiveColPlanService.selectByCond, {
        userId: vm.$store.state.user.id,
        ftyId: vm.$store.state.user.ftyId,
        page: vm.$route.name
      }).then(res=>{
        if (res.code === this.$config.SUCCESS_CODE) {
          this.planList = res.data.list
          //读取默认方案
          let defaultPlan = res.data.list.filter(f => f.flgDefault)
          if (defaultPlan.length && this.currentPlanId !== defaultPlan[0].planId) {
            this.$refs.dkPivot.internal.rowFieldKeys = defaultPlan[0].row
            this.$refs.dkPivot.internal.colFieldKeys = defaultPlan[0].col
            this.$refs.dkPivot.internal.dataFieldKeys = defaultPlan[0].value
            this.currentPlanId = defaultPlan[0].planId
          }
        } else {
          this.$Message.error(res.message)
        }
      })
    },
    /**
     * @desc   : 改变默认方案
     * @author : 洪旭东
     * @date   : 2023-09-28 10:20
     */
    changeDefault (e, row) {
      if (e) {
        for (let it of this.planList.filter(f => f.planId != row.planId)) {
          it.flgDefault = !e
        }
      }
    },
    /**
     * @desc   : 删除方案
     * @author : 洪旭东
     * @date   : 2023-09-28 13:45
     */
    deletePlan (planId) {
      this.planList.filter(f => f.planId == planId)[0].flgValid = false
    }
  },
  created() {
    // Simulate async data loading
    setTimeout(() => {
      this.asyncData = data
    }, 3000)
    this.$nextTick(() => {
      this.addKeyBoardEvent()   // 增加快捷键
    })
    this.setDisplayTable(); // 获取组件的所有显示列
    //查询方案
    this.getPlan()
  },
  filters: {
    number: function (value) {
      return value.toLocaleString()
    },
    capitalize: function (value) {
      return value.replace(/\b\w/g, l => l.toUpperCase())
    }
  },
  mounted() {
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy();
    }
    if (this.sortableData) {
      this.sortableData.destroy();
    }
  },
}
</script>

<style scoped lang="scss">

</style>
