timec.vue 12.8 KB
<template>
  <div class="base-analysis">
    <el-header>
      <span class="asis-title">{{ asisName }}&nbsp;{{$t('asis.Timecomp')}}</span>
    </el-header>
    <tc-option ref="init" @reportTime="reportHandler" @initData="initTab"></tc-option>
    <div class="element-main tc-main" style="margin-top: 178px">
      <!-- 总客流 | 天级对比 -->
      <div class="asis-table-wrapper">
        <h3 class="asis-table-header single-report-header tf-table-header">
          <!-- <span class="asis-table-download" @click="dealExport('domTrafficFlow', i18nFormatter(tc_title))">{{ $t('allPages.load') }}</span> -->
          <span class="asis-table-download" @click="exportDataHandle('pieLineChart', i18nFormatter(tc_title))">{{ $t('allPages.load') }}</span>
        </h3>
        <div class="date-radio-wrapper tf-ratio-group single-ratio-group">
          <el-radio-group v-model="radioDate" size="mini" fill="#0069FF" @change="changeTabSelect(radioDate)">
            <el-radio-button label="totalTraffic" border>{{ $t('button.totalTraffic') }}</el-radio-button>
            <template v-if="isOneDay">
              <el-radio-button label="trafficMin" v-show="isTrafficKpi" border>{{ $t('button.min') }}</el-radio-button>
              <el-radio-button label="trafficHour" border>{{ $t('button.hour') }}</el-radio-button>
            </template>
            <template v-else>
              <el-radio-button label="dayTraffic" border>{{ $t('button.dayTraffic') }}</el-radio-button>
            </template>
          </el-radio-group>
        </div>
        <div class="asis-table-content" v-loading="loading">
          <mix-charts v-if="radioDate !== 'totalTraffic'" chartId="pieLineChart" :chartData="pieChartData" chartType="AreaLine" />
          <el-table
            class="asis-table"
            id="domTrafficFlow"
            :data="trafficTab"
            :border="false"
            header-row-class-name="asis-table-head" 
            style="width: 100%"
            :max-height="tableHeight">
            <el-table-column type="index" align="center" :label="$t('table.order')" width="100" v-if="trafficHead.length > 0">
            </el-table-column>
            <public-column v-for="(item, index) in trafficHead" :key="index" :col="item" />
            <!-- <el-table-column :prop="item.prop" :label="item.label" align="center" v-for="item in trafficHead" :key="item.prop"> -->
            <!-- </el-table-column> -->
          </el-table>
          <mix-charts v-if="radioDate === 'totalTraffic'" chartId="pieLineChart" :chartData="pieChartData" chartType="Ring" />
          <!-- <div id="pieLineChart"></div> -->
        </div>
      </div>
    </div>
    <export-data-dialog ref="exportDialog" @downloadChange="downloadChange"></export-data-dialog>
  </div>
</template>

<script>
import publicChart from '../common/publicChart'
import tcOption from '../common/option/timeCompMoreOption'
import PublicColumn from '@/views/public/myColum'
export default {
  data() {
    return {
      tc_title: 'timeComp',
      asisName: '',
      emitData: {},
      tableKeyToId: {},
      tableIds: '',
      radioDate: 'dayTraffic',
      loading: true,
      trafficHead: [],
      trafficTab: [],
      tableHeight: 0,
      pieChartData: {},
      isOneDay: false,
      radioKey: [],
      downloadData: {},
      isTrafficKpi: true
    }
  },
  components: {
    'tc-option': tcOption,
    PublicColumn
  },
  created() {
    let winH = $(window).height(), scale = 0.28;
    if (winH <= 720) {
      scale = 0.35
    } else if (winH <= 768) {
      scale = 0.33
    } else if (winH <= 900) {
      scale = 0.28
    } else if (winH <= 1080) {
      scale = 0.31
    }
    this.tableHeight = winH - winH * scale
  },
  mounted() {
    this.getMallOpt();
  },
  methods: {
    i18nFormatter(label) {
      let languageLabel = 'echartsTitle.' + label;
      return this.$t(languageLabel)
    },
    i18n(value) {
      let name = 'format.' + value;
      return this.$t(name)
    },
    getMallOpt() {
      this.getCommonMalls()
        .then(resolveData => {
          let { mallData, localMallId, titleName, multiMallId } = resolveData
          this.asisName = titleName
          this.$refs.init.initAsis(localMallId, mallData)
        }, (rejectData) => {
        })
    },
    initTab(data) {
      this.emitData = data
      const { asis_time, asis_kpi } = data
      // 判断是否是同一天的时间段
      this.isOneDay = this.handlerSameDay(asis_time)
      this.isTrafficKpi = asis_kpi === 'TRAFFIC'
      this.radioDate = this.isOneDay && this.isTrafficKpi
        ? 'trafficMin'
          : this.isOneDay
            ? 'trafficHour'
            : 'dayTraffic'
      this.getChartIds()
    },
    getChartIds() {
      this.tableKeyToId = {}
      this.tableIds = ''
      const chartKeyList = [
        'totalPassengerCompare',
        'totalAndAverageTraffic',
        'dayCompareTable',
        'dayCompareLine',
        'hourCompareLine',
        'hourCompareTable',
        'minuteCompareLine',
        'minuteCompareTable'
      ]
      // const chartKeys = []
      this.$api.baseReport.reportChart({
        report: 'timeCompareAnalysis'
      })
        .then(res => {
          const { data } = res.data
          data.forEach((item, index) => {
            this.tableKeyToId[item.key] = item.id
          })
          this.tableIds = this.matchKeyId(this.radioDate)
          this.getTableData()
        })
        .catch(err => { 
          this.catchErrorHandle(err)
        })
    },
    fetchChartData() {
      const { emitData, tableIds } = this
      const { asis_org, asis_time, asis_kpi } = emitData
      const [date1, date2] = asis_time
      const param = {
        orgIds: asis_org,
        startDate: date2[0],
        endDate: date2[1],
        startDate1: date1[0],
        endDate1: date1[1],
        kpiType: asis_kpi,
        chartIds: tableIds
      }
      const { params, asisLevel } = this.dealFormat(param, emitData)
      return new Promise(resolve => {
        this.$api.analysisReport.timeCompareAnalysis(asisLevel, params)
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            this.catchErrorHandle(err)
          })
      })
    },
    async getTableData() {
      this.trafficHead = []
      this.trafficTab = []
      this.pieChartData = {}
      try {
        const { data } = await this.fetchChartData()
        const { body } = data.data
        const {
          totalPassengerCompare = {},
          totalAndAverageTraffic = {},
          dayCompareTable = {},
          dayCompareLine = {},
          hourCompareTable = {},
          hourCompareLine = {},
          minuteCompareTable = {},
          minuteCompareLine = {}
        } = body
        const [_tableKey, _chartKey] = this.radioKey
        if (body[_tableKey] && body[_chartKey]) {
          this.matchChart(body[_tableKey], body[_chartKey])
        } else {
          console.warn(`The ${_tableKey} and ${_chartKey} reports has no data!!`)
          this.$message.warning(`The ${_tableKey} and ${_chartKey} reports has no data!!`)
        }
        this.loading = false
      } catch(err) {
        this.catchErrorHandle(err)
      }
    },
    matchChart() {
      try {
        // table
        this.trafficHead = this.createHeadColumn(arguments[0].xaxis.data)
        this.trafficTab = this.buildTableContent(this.trafficHead, arguments[0].series)
        // chart
        arguments[1].otherConf = this.radioDate === 'totalTraffic'
          ? {
            _color: ['#3BB8FF', '#FFC62E'],
            seriesText: 'traffic',
            legendBottom: 16
          }
          : {
            _color: ['#3BB8FF', '#FFC62E'], //['#87D14B', '#3BB8FF'],
            seriesText: this.emitData.asis_kpi === 'TRAFFIC' ? 'traffic' : 'personNum',
            legendShow: false,
            hasYaxisName: false,
            grid: { top: 16, right: 26, bottom: 60, left: 52 },
            periodTime: this.radioDate === 'trafficMin',
            nextTimeNum: this.radioDate === 'trafficMin' ? 10 : 0
          }
        this.pieChartData = arguments[1]
      } catch(err) {
        console.error(err)
      }
    },
    createHeadColumn(headColumnData) {
      let headColumn = []
      if (headColumnData.length) {
        let i = 0
        headColumn = headColumnData.map((item) => {
          if (/\[.+\]/g.test(item)) {
            // 解析
            let evalItem = JSON.parse(item.replace(/\'/g, '"'))
            return {
              label: evalItem[0],
              children: evalItem.map((childItem, childIndex) => {
                if (childIndex > 0) {
                  return {
                    prop: `defaultOrg${i++}`, label: childItem
                  }
                } else {
                  return false
                }
              }).filter(Boolean)
            }
          } else {
            return {
              prop: `defaultOrg${i++}`,
              label: item
            }
          }
        })
      }
      return headColumn
    },
    buildTableContent(headData, data) {
      let result = [], temp = {}
      if (headData.length) {
        data.forEach((item, index) => {
          temp = {}
          item.data.forEach((dataItem, dataIndex) => {
            temp[`defaultOrg${dataIndex}`] = (
              (typeof(dataItem) === 'number'
              || typeof(dataItem) === 'string')
              && dataItem !== 'null'
            ) ? dataItem : '--'
          })
          result.push(temp)
        })
      }
      return result
    },
    reportHandler(emitData) {
      const { asis_time, asis_kpi } = emitData
      // 判断是否是同一天的时间段
      this.isOneDay = this.handlerSameDay(asis_time)
      this.isTrafficKpi = asis_kpi === 'TRAFFIC'
      this.radioDate = this.isOneDay && this.isTrafficKpi
        ? 'trafficMin'
          : this.isOneDay
            ? 'trafficHour'
            : 'dayTraffic'
      this.emitData = emitData;
      this.asisName = emitData.asis_tit
      if (Object.keys(this.tableKeyToId).length) {
        this.tableIds = this.matchKeyId(this.radioDate)
        this.getTableData()
      } else {
        this.getChartIds()
      }
    },
    matchKeyId(keys) {
      const { tableKeyToId } = this
      const rules = {
        'totalTraffic': () => {
          this.radioKey = ['totalPassengerCompare', 'totalAndAverageTraffic']
          return tableKeyToId['totalPassengerCompare'] + ',' + tableKeyToId['totalAndAverageTraffic']
        },
        'dayTraffic': () => {
          this.radioKey = ['dayCompareTable', 'dayCompareLine']
          return tableKeyToId['dayCompareTable'] + ',' + tableKeyToId['dayCompareLine']
        },
        'trafficHour': () => {
          this.radioKey = ['hourCompareTable', 'hourCompareLine']
          return tableKeyToId['hourCompareTable'] + ',' + tableKeyToId['hourCompareLine']
        },
        'trafficMin': () => {
          this.radioKey = ['minuteCompareTable', 'minuteCompareLine']
          return tableKeyToId['minuteCompareTable'] + ',' + tableKeyToId['minuteCompareLine']
        }
      }
      return rules[keys]()
    },
    changeTabSelect(keys) {
      this.loading = true
      this.tableIds = this.matchKeyId(keys)
      this.getTableData()
    },
    handlerSameDay(times) {
      if (times instanceof Array && times.length > 0) {
        const [date1, date2] = times
        try {
          if (date1[0] === date1[1] && date2[0] === date2[1]) {
            return true
          }
          return false
        } catch(err) {
          console.error(err)
        }
      }
    },
    exportDataHandle(domId, title) {
      const { emitData, tableIds, radioDate } = this
      const { asis_org, asis_time, asis_kpi } = emitData
      const chartId = this.tableKeyToId[radioDate === 'totalTraffic' ? 'totalPassengerCompare' : 'dayCompareTable']
      const exportNeed = {
        domId: domId,
        title: title,
        data: {
          url: `/report/timeCompareAnalysis/${this.emitData.asis_level}/${chartId}/excel`,
          params: `orgIds=${asis_org}&startDate=${asis_time[1][0]}&endDate=${asis_time[1][1]}&startDate1=${asis_time[0][0]}&endDate1=${asis_time[0][1]}&kpiType=${asis_kpi}`
        }
      }
      this.$refs.exportDialog.dialogInit(exportNeed, true);
    },
    downloadChange(type) {
      if (type === 'Excel') {
        const { i18nFormatter, tc_title } = this
        this.dealExport('domTrafficFlow', i18nFormatter(tc_title))
        // const { multiHeader, header, data, merges } = downloadData
        // if (!header && !data) return
        // console.log('header', header)
        // console.log('data', data)
        // import('@/utils/Export2Excel').then(excel => {
        //   excel.export_json_to_excel({
        //     multiHeader,
        //     header,
        //     data,
        //     merges,
        //     filename: this.i18nFormatter(tc_title),
        //     // autoWidth: true,
        //     bookType: 'xlsx'
        //   })
        // })
      }
    },
  }
}
</script>
<style scoped>
#pieLineChart {
  height: 450px;
}
</style>