passenger-retention.vue 11.6 KB
<template>
  <div class="base-analysis">
    <el-header>
      <span class="asis-title">{{ asisName }}&nbsp;{{ $t('asis.PassengerRetention') }}</span>
    </el-header>
    <more-option ref="init" @reportTime="reportHandler" @initData="initTab" @changeTime="changeTime"/>
    <div class="element-main rank-main">
      <!-- 小时分钟合并 -->
      <div class="asis-table-wrapper">
        <h3 class="asis-table-header">
          <span class="asis-table-download" @click="exportDataHandle(isTabChart ? 'domRetention' : 'retentionChart', retentionTitle)">
            {{ $t('allPages.load') }}
          </span>
          <span class="report-type-box">
            <span class="report-item line-report" :class="!isTabChart ? 'report-item-line' : ''" @click="selReport('line')"></span>
            <span class="report-item" :class="isTabChart ? 'report-item-tab' : ''" @click="selReport('table')"></span>
          </span>
        </h3>
        <div class="date-radio-wrapper tf-ratio-group single-ratio-group">
          <el-radio-group v-model="optionRadio" size="mini" fill="#0069FF" @change="handleRadioChange(optionRadio)">
            <el-radio-button v-for="item in selectItem" :key="item.label" :label="item.label" border :disabled='item.disabled'> 
              {{ $t(item.text) }}
            </el-radio-button>
          </el-radio-group>
        </div>
        <div class="asis-table-content" v-loading="loading">
          <template v-if="isTabChart">
            <el-table
              class="asis-table"
              id="domRetention"
              :data="inAndOutTableData"
              lazy
              header-row-class-name="asis-table-head"
              style="width: 100%"
              :max-height="tableHeight"
            >
              <comp-column v-for="(item, index) in inAndOutHeadData" :key="index" :col="item" />
            </el-table>
        </template>
          <!-- 折线图 -->
          <mix-charts v-else chartId="retentionChart" class="retention-chart-box" :chartData="retentionChartData" chartType="Line" :style="{ height: tableHeight + 'px' }" />
        </div>
      </div>
    </div>
    <export-data-dialog ref="exportDialog" />
  </div>
</template>

<script>
import ExportDataDialog from '@/views/public/exportData'
import MoreOption from '../common/option/retentionMoreOption'
import CompCol from '../../public/myColum'

export default {
  components: {
    MoreOption, ExportDataDialog,
    "comp-column": CompCol
  },
  data() {
    return {
      selectItem: [
        { label: 'TAB_MINUTE', text: 'button.min',disabled:false},
        { label: 'TAB_HOUR', text: 'button.hour' ,disabled:false}
      ],

      asisName: '',
      asisLevel: '',
      emitData: {},
      tableHeight: 0,
      loading: true,
      isTabChart: false,
      optionRadio: 'TAB_MINUTE',
      chartKeyToId: {},
      chartIds: '',
      retentionTitle: '',
      retentionTable: [],
      retentionHead: [],
      retentionChartData: {},

      inAndOutHeadData: [],
      inAndOutTableData: []
    }
  },
  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
    this.getMallOpt();
  },
  mounted() {

  },
  methods: {
    // 获取门店/广场列表
    getMallOpt() {
      this.getCommonMalls().then(resolveData => {
        let { mallData, localMallId, multiMallId } = resolveData;
        let refMallId = { 'mallId': localMallId, 'multiMallId': multiMallId }
        this.$refs.init.initAsis(refMallId, mallData);
      },(rejectData) => {})
    },

    initTab(data) {
      this.emitData = data
      this.asisName = data.asis_tit
      this.chartKeyToId = {}
      this.chartIds = ''
      this.getchartKey()
    },
    changeTime(val){
      if( val == 'day') {
        this.selectItem.map((ele,index)=> {
          if(ele.label == 'TAB_DAY') {
            ele.disabled = true
            this.$set(this.selectItem,index,ele)
          } else {
             ele.disabled = false
             this.$set(this.selectItem,index,ele)
          }
        })
        this.optionRadio = 'TAB_MINUTE';
      } else {
        this.selectItem.map((ele,index)=> {
          if(ele.label == 'TAB_DAY') {
            ele.disabeled = false
            this.$set(this.selectItem,index,ele)
          } else {
             ele.disabled = true
             this.$set(this.selectItem,index,ele)
          }
        })
        this.optionRadio = 'TAB_DAY';

      }
    },
    getchartKey() {
      let chartKeyList = ['retentionInAndOutLine', 'retentionInAndOutTable']

      this.$api.baseReport.reportChart({ report: 'retentionInAndOut' })
        .then(res => {
          let { data } = res.data
          data.forEach(item => {
            if (chartKeyList.includes(item.key)) {
              this.chartKeyToId[item.key] = item.id
            }
          })
          this.chartIds = this.isTabChart ? this.chartKeyToId['retentionInAndOutTable'] : this.chartKeyToId['retentionInAndOutLine']
          this.getTableData()
        }).catch(err => { this.$throw(err) })
    },

    tableData() {
      let obj = {};
      if (this.inAndOutTableData.length) {
        // for (let key in this.inAndOutTableData[0]) {
        //   if (obj[key]) {
        //     obj[key] += obj[key];
        //   } else {
        //     obj[key] = 0;
        //   }
        // }

        this.inAndOutTableData.map((v, i) => {
          for (let j in v) {
            if (!isNaN(Number(obj[j])) && !isNaN(Number(v[j]))) {
              obj[j] += Number(Math.round(v[j] * 100) / 100);
            }
          }
        });
        this.inAndOutTableData.push(obj);
      }
    },
    // 提前一天, 当天没有统计完
    advanceTime(timeStr) {
      let strToDate

      if (typeof timeStr === 'string') {
        strToDate = new Date(timeStr.replace(/\-/g, '/'))
        return dateUnit.dateFormat(new Date(Date.parse(strToDate) - 24 * 60 * 60 * 1000), 'yyyy-MM-dd')
      }
      return timeStr
    },
    getTableData() {
      let { isTabChart, emitData: { asis_org, asis_date, asis_time ,asis_level,asis_moreTimer}, advanceTime} = this, param = {}

      this.retentionTitle = ''
      this.retentionChartData = {}
      this.retentionHead = []
      this.retentionTable = []
      
      this.inAndOutHeadData = [];
      this.inAndOutTableData = [];

      // 时间处理
      let { startTime, endTime} = this.newDateFormat(asis_date, asis_time)
        if (asis_date === 'month') {
          endTime.split('-')[0] == new Date().getFullYear()
            && endTime.split('-')[1] == new Date().getMonth() + 1
            && endTime.split('-')[2] == new Date().getDate()
            && (endTime = advanceTime(endTime))
        }
      param = { orgIds: asis_org, chartIds: this.chartIds, option: this.optionRadio,  startDate: startTime,
            endDate: endTime}
          asis_moreTimer?param.dates = asis_moreTimer:null
         this.$api.analysisReport.retentionInAndOut(asis_level,param).then(res => {
          if (res.data.code !== 200) {
            this.$message.error(res.data.msg)
            return
          }
          let { data: {
                body: {
                  retentionInAndOutLine = {},
                  retentionInAndOutTable = {}
                }}} = res.data
          if (this.isTabChart) {
            this.retentionTitle = retentionInAndOutTable.title
            let thead = retentionInAndOutTable.xaxis.data;
            this.inAndOutHeadData = this.dealThead(thead)
            // 叠加
            let temp = {};
            retentionInAndOutTable.series.forEach(item => {
              item.data.forEach((dataItem, dataIndex) => {
                temp["defaultOrg" + dataIndex] = dataItem != null ? dataItem : "--";
              })
              this.inAndOutTableData.push(temp);
              temp = {};
            });
            this.tableData()
            // this.retentionHead = this.autoComplateHead(retentionInAndOutTable.xaxis.data)
            // this.retentionTable = this.dealTableData(this.retentionHead, retentionInAndOutTable.series)
          } else {
            this.retentionTitle = retentionInAndOutLine.title
            retentionInAndOutLine.otherConf = {
              _color: ['#33bafe', '#6e6fc1', '#fec62b', '#ff9c01', '#38d4be', '#79ce4c'],
              grid: {
                top: 10,
                right: 26,
                left: 40,
                bottom: 52
              },
              seriesText: 'personNum'
            }
            this.retentionChartData = retentionInAndOutLine
          }
          this.loading = false
        }).catch(err => {
          this.catchErrorHandle(err)
          this.loading = false
        })
    },

        // 表头处理
    dealThead(theadData) {
      let [cols, $index] = [[], 0];
      cols = theadData.map((item, index) => {
        if (/^\[.+\]$/.test(item)) {
          let formatItem = eval(item);
          return {
            label: formatItem[0],
            children: formatItem.map((childItem, childIndex) => {
                if (childIndex > 0) {
                  return {
                    prop: "defaultOrg" + $index++,
                    label: childItem
                  };
                } else {
                  return false;
                }
              })
              .filter(Boolean)
          };
        } else {
          return {
            prop: "defaultOrg" + $index++,
            label: item,
            fixed: true,
            width: 120
          };
        }
      });
      return cols;
    },

    autoComplateHead(headData) {
      return headData.map((k, index) => {
        return {
          prop: 'defaultOrg' + index,
          label: k
        }
      })
    },
    dealTableData(headData, data) {
      let [temp, result] = [{}, []]

      data.forEach((item) => {
        temp = {}
        item.data.forEach((dataItem, i) => {
          temp[headData[i].prop] = (item.data[i] || item.data[i] == 0) ? item.data[i] : '--'
        })
        result.push(temp)
      })
      return result
    },
    handleRadioChange(val) {
      this.inAndOutHeadData = [];
      this.inAndOutTableData = [];
      this.getTableData()
    },
    selReport(reportChart) {
      let { getTableData } = this

      if (reportChart === 'table') {
        if (this.isTabChart) return
        this.isTabChart = true
        this.chartIds = this.chartKeyToId['retentionInAndOutTable']
      } else {
        if (!this.isTabChart) return
        this.isTabChart = false
        this.chartIds = this.chartKeyToId['retentionInAndOutLine']
      }
      this.loading = true
      getTableData()
    },
    reportHandler(data) {
      this.emitData = data
      console.info(data,'submit')
      this.asisName = data.asis_tit
      this.loading = true
      // 默认table表格 
      if (this.chartIds) {
        this.getTableData()
      } else {
        this.getchartKey()
      }
    },
    exportDataHandle(domId, title) {
      let { isTabChart, emitData: { asis_org, asis_date, asis_time,asis_level }, chartIds, optionRadio } = this,
        { startTime, endTime } = this.newDateFormat(asis_date, asis_time),
        exportDate = asis_date === 'day' ? `date=${startTime}` : `startDate=${startTime}&endDate=${endTime}`,
        exportNeed = {
          domId: domId,
          title: title,
          data: {
            url: `/report/retentionInAndOut/${asis_level}/${chartIds}/excel`,
            params: `orgIds=${asis_org}&${exportDate}&option=${optionRadio}`
          }
        }
      if (isTabChart) {
        this.dealExport(domId, title)
      }
      else {
        this.$refs.exportDialog.dialogInit(exportNeed)
      }
    }
  }
}
</script>