<!-- @desc:自定义报表  @auth:周兴  @time:2023/3/28 17:12 -->
<template>
  <div class="main-div" ref="mainDiv">
    <!--加载中-->
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <BaseIndexButtonGroup id="BaseIndexButtonGroup">
      <template #left>
        <!--    查询    -->
        <BaseIndexButton right-button="user-select" ref="search" name="search"></BaseIndexButton>
        <!--    清空条件    -->
        <BaseIndexButton ref="clear" name="clear"></BaseIndexButton>
        <!--    设置透视表    -->
        <BaseIndexButton ref="settingPivot" name="settingPivot" :is-must-choose-flag="false"></BaseIndexButton>
        <!--    清除透视表    -->
        <BaseIndexButton ref="deletePivot" name="deletePivot" :is-must-choose-flag="false"></BaseIndexButton>
      </template>
    </BaseIndexButtonGroup>

    <!--  查询条件区域  -->
    <div id="search-cond-div" ref="search-cond-div" class="search-cond-class">
      <SearchCond ref="searchCond" v-model="searchCond"
                  @collapse-change="collapseChange" :setFlag="false"
                  :searchContent="searchContent"
      ></SearchCond>
    </div>

    <!-- 表格展示  -->
    <DkTable slot="top" :id="'table-'+$options.name" ref="table-select"
             :data="tableData"
             :height="this.tableHeight"
             :show-setting-flag="false"
             :choose-flag="false"
             :pageFlag="reportForm.flgPage"
             :page-total-flag="reportForm.flgPage"
             sumTotalType="subTotal"
             :page-total="pageInfo.total"
             :current-page="pageInfo.currentPage"
             @pageChange="pageSizeChange">
      <DkTableColumn
        v-for="(item, index) in tableColumns"
        :align="item.align"
        :type="item.type"
        :field="item.field"
        :title="item.title"
        :digits="item.digits"
        :sum="item.sum"
        :dataType="item.dataType"
      >
      </DkTableColumn>
      <!--        :width="index === tabsOptions[tabIndex].tableColumns.length - 1?'auto': item.width"-->
    </DkTable>
  </div>
</template>

<script>
import {indexMixin} from "@/mixins";

export default {
  name: "setting-pivot",
  mixins: [indexMixin],
  data() {
    return {
      reportId: '',
      sqlId: null,
      flgVisible: true,
      form: {},
      reportForm: {},
      tableColumns: [],//报表列
      tableData: [],// 报表数据
      searchContent: [],// 查询条件
      changeFlag: false,// 是否是跳转
      searchParams: {},// 查询条件
      linkChangeTabs: {},// 点击链接跳转到相应的页签
    }
  },
  methods: {
    /**
     * @desc   : 翻页
     * @author : 周兴
     * @date   : 2023/4/20 16:31
     */
    pageSizeChange(pageInfo) {
      // 是点击跳转的翻页
      if (this.changeFlag) {
        let params = {...this.searchParams}
        params.currentPage = pageInfo.currentPage;
        params.pageSize = pageInfo.pageSize;
        this.getData(params)              // 执行查询
      } else {
        this.searchData(pageInfo);
      }
    },
    /**
     * @desc   : 设置参数
     * @author : 周兴
     * @date   : 2023/3/28 20:06
     */
    setSearchParams(params) {
      params.reportId = this.reportId
      params.sqlId = this.sqlId
      params.flgPage = this.reportForm.flgPage
      // 处理查询条件
      this.searchContent.forEach(it => {
        // 日期的处理
        if (it.valueKind === 'DATE_RANGE') {
          if (!this.hasKey(params, it.itemCode + 'Start')) {
            params[it.itemCode + 'Start'] = null;
          }
          if (!this.hasKey(params, it.itemCode + 'End')) {
            params[it.itemCode + 'End'] = null;
          }
        }
        // 如果没有输入查询条件，需要设置为null
        if (!this.hasKey(params, it.itemCode)) {
          params[it.itemCode] = null;
        } else {
          if (params[it.itemCode] == undefined) {
            params[it.itemCode] = null;
          }
          // 如果是下拉需要处理数据
          if (it.valueKind === 'M-CHOICE') {
            let values = params[it.itemCode];
            if (values && values.length > 0) {
              for (let i in values) {
                if (typeof values[i] === 'string') {
                  if (values[i].toString().indexOf('\'') < 0) {
                    values[i] = '\'' + values[i] + '\'';
                  }
                  // 判断是否是uuid
                  if (values[i].toString().length === 38) {
                    values[i] = values[i] + ' ::uuid '
                  }
                }
              }
            }
          }
        }
      })
      return params;
    },
    /**
     * @desc   : 查询数据
     * @author : 周兴
     * @date   : 2023/3/28 20:09
     */
    getData(params) {
      this.changeFlag = false;
      return this.excute(this.$service.customReportService, this.$service.customReportService.selectByReportId, params)
    },
    /**
     * @desc   : 打开设置透视表界面
     * @author : 周兴
     * @date   : 2023/5/18 15:35
     */
    settingPivot() {
      let data = this.tableData?.copy();
      const tableColumns = this.$refs['table-select'].getTableColumn()
      if (tableColumns && tableColumns.visibleColumn ) {
        let columns = [...tableColumns.visibleColumn];
        columns = columns.filter(it => it.type != 'seq' && it.type != 'checkbox' && it.type != 'radio').filterColumns(['field', 'title', 'type', 'params'])
        this.$Perspective({
            component: this.$refs[this.name],
            columns: columns,
            tableData: data,
            sqlId: this.sqlId,
            reportId: this.reportId,
            settingFlag: true
          },
          {})
      }
    },
    /**
     * @desc   : 删除透视表
     * @author : 周兴
     * @date   : 2023/5/23 10:20
     */
    deletePivot() {
      this.$IBMessage({
          content: vm.$t('Q_002', {'param': vm.$t('deletePivot')}),
          title: vm.$t('systemQuestion')
        },
        {
          ok: () => {
            let params = {
              sqlId: this.sqlId,
              pivotData: null,
              flgPivot: false
            }
            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('deletePivot')}))
              } else {
                this.$Message.warning(res.message)
              }
              this.loading = false
            })
          },
          cancel: () => {
          }
        })
    },
    /**
     * @desc   : 查询明细
     * @author : 周兴
     * @date   : 2023/3/28 17:51
     */
    detail(id) {
      this.excute(this.$service.customReportService,
        this.$service.customReportService.selectByReport, {
          reportId: id,
          sqlId: this.sqlId,
          ftyId: this.$store.state.user.ftyId
        }, false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.reportForm = res.data;
          // 查询条件
          let conditionList = res.data.conditionList;
          this.handleCondition(conditionList);
          // sql设置
          let tabsOptions = res.data.sqlList;
          // 表格设置
          this.handleTableSetting(tabsOptions[0]);
          console.log('tabsOptions', tabsOptions)
        }
      })
    },
    /**
     * @desc   : 处理查询条件
     * @author : 周兴
     * @date   : 2023/3/28 19:33
     */
    handleCondition(conditionList) {
      if (conditionList && conditionList.length > 0) {
        this.searchContent = []
        conditionList.forEach(it => {
          let item = {
            itemCode: it.code,
            itemName: it.name,
            required: it.flgRequired,
          }
          // 得到类型
          item.valueKind = this.handleReportKind(it.kind);
          item.valueFormat = {}
          // 赋值默认值
          if (it.defaultValue && it.defaultValue.default) {
            item.valueFormat.default = it.defaultValue.default;
          }
          // 如果下拉
          if (it.kind === this.$config.reportKind.single ||
            it.kind === this.$config.reportKind.multiple) {
            item.treeFlag = it.flgTree
            item.treeStrict = it.flgTreeStrict
            item.valueFormat.valueKey = 'value';
            item.valueFormat.labelKey = 'name';
            // 获取下拉数据源
            this.getSelectData(it.conditionId, item, it.defaultValue?.default);
          } else if (it.kind === this.$config.reportKind.dateRange) {
            // 日期范围
            if (it.defaultValue && it.defaultValue.rangeSel) {
              item.valueFormat.default = this.handleDateDefault(it.defaultValue)
            }
          }
          this.searchContent.push(item);
        })
      }
    },
    /**
     * @desc   : 处理
     * @author : 周兴
     * @date   : 2023/5/17 8:39
     */
    handleDateDefault(defaultValue) {
      let value = []
      let now = new Date();
      switch (defaultValue.rangeSel) {
        // 今天
        case this.$config.rangeSel.today.value:
          value = [now, now];
          break;
        // 昨天
        case this.$config.rangeSel.yesterday.value:
          let yesterday = now.addDays(-1);
          value = [yesterday, yesterday];
          break;
        // 本周
        case this.$config.rangeSel.thisWeek.value:
          value = [now.getWeekFirstDay(), now.getWeekLastDay()];
          break;
        // 近一周
        case this.$config.rangeSel.nearlyWeek.value:
          let beginDate = now.addDays(-6)
          value = [now.addDays(-6), now];
          break;
        // 上一周
        case this.$config.rangeSel.beforeWeek.value:
          let beforeDay = now.addDays(-7);
          value = [beforeDay.getWeekFirstDay(), beforeDay.getWeekLastDay()];
          break;
        // 本月
        case this.$config.rangeSel.thisMonth.value:
          value = [now.getFirstDateStr(), now.getLastDateStr()];
          break;
        // 近一月
        case this.$config.rangeSel.nearlyMonth.value:
          value = [now.addMonths(-1), now];
          break;
        // 上一月
        case this.$config.rangeSel.beforeMonth.value:
          let beforeMonth = now.addMonths(-1);
          value = [beforeMonth.getFirstDateStr(), beforeMonth.getLastDateStr()];
          break;
        // 自定义
        case this.$config.rangeSel.custom.value:
          let beforeDayCustom = now;
          // 间隔月份
          if (defaultValue.intervalMonth) {
            beforeDayCustom = beforeDayCustom.addMonths(-1 * defaultValue.intervalMonth)
          }
          // 间隔天数
          if (defaultValue.intervalDay) {
            beforeDayCustom = beforeDayCustom.addDays(-1 * defaultValue.intervalDay)
          }
          value = [beforeDayCustom, now];
          break;
      }
      return value;
      // if(defaultValue.rangeSel == this.$config.rangeSel.today.value){
      //
      // }
    },
    /**
     * @desc   : 处理报表的类型
     * @author : 周兴
     * @date   : 2023/4/20 8:53
     */
    handleReportKind(kind) {
      let valueKind = ''
      if (kind === this.$config.reportKind.single) {
        valueKind = this.$config.docUserInput.sChoice
      } else if (kind === this.$config.reportKind.multiple) {
        valueKind = this.$config.docUserInput.mChoice
      } else if (kind === this.$config.reportKind.date) {
        valueKind = this.$config.docUserInput.date
      } else if (kind === this.$config.reportKind.dateRange) {
        valueKind = this.$config.docUserInput.dateRange
      } else if (kind === this.$config.reportKind.dateTimeRange) {
        valueKind = this.$config.docUserInput.dateTimeRange
      } else if (kind === this.$config.reportKind.month) {
        valueKind = this.$config.docUserInput.month
      } else if (kind === this.$config.reportKind.monthRange) {
        valueKind = this.$config.docUserInput.monthRange
      } else if (kind === this.$config.reportKind.mSearch) {
        valueKind = this.$config.docUserInput.mSearch
      } else if (kind === this.$config.reportKind.sSearch) {
        valueKind = this.$config.docUserInput.sSearch
      }
      return valueKind;
    },
    /**
     * @desc   : 获取下拉的数据源
     * @author : 周兴
     * @date   : 2023/3/29 10:09
     */
    getSelectData(conditionId, item, defaultValue) {
      let params = {
        conditionId: conditionId,
        ftyId: this.$store.state.user.ftyId
      }
      this.excute(this.$service.customReportService, this.$service.customReportService.getSelectDataById, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          let defaultV = null;
          if (item.valueKind === 'M-CHOICE') {
            defaultV = defaultValue ? [defaultValue] : null
          } else {
            defaultV = defaultValue;
          }
          // 给下拉数据源赋值
          this.$refs['searchCond'].changeOptions(item.itemCode, res.data, defaultV)
        }
      })
    },
    /**
     * @desc   : 设置表格设置信息
     * @author : 周兴
     * @date   : 2023/3/28 19:55
     */
    handleTableSetting(row) {
      let table = row.tableSettingList?.copy();
      let tableColumns = []
      this.showFooter = false;
      if (table && table.length > 0) {
        table.forEach(it => {
          if (it.flgVisible) {
            let item = {...it}
            item.field = it.code
            item.title = it.name
            item.sum = it.flgSum
            if (it.dataType === 'switch') {
              item.type = it.dataType;
            } else {
              item.type = 'text';
            }
            // 是否是链接
            if (it.flgLink) {
              item.type = 'link'
              this.linkChangeTabs[it.code] = it.changeTabName
            }
            item.dataType = it.dataType ? it.dataType : this.$config.dataType.str
            // if (it.flgSum) {
            //   this.form['showFooter_' + index] = it.flgSum
            // }
            tableColumns.push(item);
          }
        })
      }
      this.tableColumns = tableColumns;
    },
    /**
     * @desc   : 同一路由加载数据
     * @author : 周兴
     * @date   : 2023/3/31 16:02
     */
    createdInit() {
      this.initSearchFlag = false; // 默认不查询
      this.routeObjName = 'customReport' // 路由
    },
  },
  mounted() {
    this.routeObjName = 'customReport' // 路由
    let param = this.$route.params.id
    if (param) {
      let params = param.split('|')
      if (params && params.length > 1) {
        this.reportId = params[0];
        this.sqlId = params[1].toNum();
        this.detail(params[0])   // 查询该报表的信息
      }
    }
  }
}
</script>

<style scoped>
/deep/ .ivu-row {
  flex-flow: wrap !important;
  display: flex !important;
}
</style>
