<template>
  <div class="yearly">
    <!-- 本年每日报表 -->
    <div class="asis-table-wrapper single-report-wrapper">
      <h3 class="asis-table-header single-report-header">
        <!-- <span class="asis-table-title">{{ i18nFormatter(detailData_title) }}</span> -->
        <!-- <el-select v-model="kpiValue" class="select-box" size="mini" @change="changeSel('detailData', kpiValue)" :placeholder="$t('pholder.select')">
                    <el-option v-for="item in kpiOption" :key="item.value" :label="i18n(item.label)" :value="item.value">
                    </el-option>
        </el-select>-->
        <span
          class="asis-table-download"
          @click="downloadData(i18nFormatter(detailData_title))"
        >{{$t('allPages.load')}}</span>
        <span class="report-type-box">
          <span :class="barLineIcon" @click="selReport('line')"></span>
          <span
            :class="isYTabChart ? 'report-item report-item-tab' : 'report-item'"
            @click="selReport('table')"
          ></span>
        </span>
      </h3>
      <div
        class="date-radio-wrapper tf-ratio-group single-ratio-group"
      >
        <template v-if="emitData.asis_object === 1">
          <el-radio-group
            v-model="radioDate"
            size="mini"
            fill="#0069FF"
            @change="changeTabSelect(radioDate)"
          >
            <!-- 小时级 天汇总 周汇总 月汇总 -->
            <el-radio-button label="trafficOfMonth" border>{{ $t('button.month') }}</el-radio-button>
            <el-radio-button label="trafficOfWeek" border>{{ $t('button.week') }}</el-radio-button>
            <el-radio-button label="detailData" border>{{ $t('button.day') }}</el-radio-button>
            <el-radio-button label="hourAverageTraffic" border>{{ $t('button.hour') }}</el-radio-button>
            <!-- <el-radio-button label="detailData" border>{{$t('button.min')}}</el-radio-button> -->
            <!-- <el-radio-button label="detailData" border>{{$t('button.week')}}</el-radio-button> -->
          </el-radio-group>
        </template>
        <template v-else>
          <el-radio-group
            v-model="multipleRadio"
            size="mini"
            fill="#0069FF"
            @change="changeTabSelect(multipleRadio)"
          >
            <el-radio-button label="trafficOfMonth" border>{{ $t('button.month') }}</el-radio-button>
            <el-radio-button label="trafficOfWeek" border>{{ $t('button.week') }}</el-radio-button>
            <el-radio-button label="detailData" border>{{ $t('button.day') }}</el-radio-button>
            <el-radio-button label="hourAverageTraffic" border>{{ $t('button.hour') }}</el-radio-button>
          </el-radio-group>  
        </template>
      </div>
      <div class="asis-table-content" v-loading="loading">
        <el-table
          v-if="isYTabChart"
          ref="tableContainer"
          id="domByTrafficFlow"
          class="asis-table"
          :data="tabData"
          header-row-class-name="asis-table-head"
          style="width: 100%"
          :max-height="tableHeight"
        >
          <el-table-column
            :prop="item.prop"
            :label="item.label"
            align="center"
            v-for="(item,index) in tabHeadData"
            :key="index"
            min-width="100"
            :fixed="index == 0"
          ></el-table-column>
          <el-table-column
            prop="averageVal"
            :label="$t('table.average')"
            show-overflow-tooltip
            align="center"
            v-if="emitData.asis_object != 1"
          ></el-table-column>
          <el-table-column
            prop="sums"
            :label="$t('table.total')"
            show-overflow-tooltip
            align="center"
            v-if="emitData.asis_object != 1"
          ></el-table-column>
        </el-table>
        <!-- <basic-chart v-else id="bylineChart" class="basic-line-chart" :style="{ height: tableHeight + 'px' }" :options="chartData" chartType="BasicLine"></basic-chart> -->
        <mix-charts
          v-else
          chartId="bylineChart"
          class="basic-line-chart"
          :style="{ height: tableHeight + 'px' }"
          :chartData="chartData"
          chartType="AreaLine"
        />
      </div>
    </div>
    <export-data-dialog ref="exportDialog"></export-data-dialog>
  </div>
</template>

<script>
import { debounce } from "@/utils";
// import commonTable from '../../public/tableCommon'
import exportData from "../../public/exportData";

export default {
  props: {
    propparam: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    // 'common-tab': commonTable
    "export-data-dialog": exportData
  },
  data() {
    return {
      loading: true,
      kpiValue: "TRAFFIC",
      kpiOption: [
        {
          label: "TRAFFIC",
          value: "TRAFFIC"
        },
        {
          label: "SALES",
          value: "SALES"
        },
        {
          label: "DEPTH",
          value: "DEPTH"
        },
        {
          label: "PREPRICE",
          value: "PREPRICE"
        },
        {
          label: "PERAREAVALUE",
          value: "PERAREAVALUE"
        },
        {
          label: "DURATIONTIME",
          value: "DURATIONTIME"
        }
      ],
      detailData_title: "", //本年每日报表
      tableKeyToId: {},
      tableIds: "",
      emitData: {},
      tableHeight: 0,
      isYTabChart: true,
      tabHeadData: [],
      tabOps: [],
      chartData: {},
      startDate: "",
      endDate: "",
      radioDate: "trafficOfMonth",
      multipleRadio: "detailData",
      ///////
      timer: null,
      _scrollHandler: null
    };
  },
  computed: {
    barLineIcon() {
      if (this.isYTabChart) {
        return "report-item line-report";
      } else {
        return "report-item line-report report-item-line";
      }
    },
    tabData() {
      return this.computeData(this.tabOps);
    }
  },
  watch: {
    propparam: {
      handler: "refreshHandle",
      immediate: true
    }
  },
  created() {
    let winH = $(window).height(),
      scale = 0.34;
    if (winH <= 720) {
      scale = 0.4;
    } else if (winH <= 768) {
      scale = 0.38;
    } else if (winH <= 900) {
      scale = 0.36;
    } else if (winH <= 1080) {
      scale = 0.34;
    }
    this.tableHeight = winH - winH * scale;
    this.isYTabChart =
      window._vionConfig.reportType && window._vionConfig.reportType == "table"
        ? true
        : false;
  },
  mounted() {
    // window.addEventListener('scroll', () => {
    //   clearTimeout(this.timer)
    //   this.timer = setTimeout(() => {
    //     this.chartScrollHandle()
    //   }, 500)
    // }, true)
  },
  beforeDestroy() {
    // window.removeEventListener('scroll', this.chartScrollHandle, true)
  },
  methods: {
    // chartScrollHandle() {
    //     if (!this.$refs.tableContainer) return
    //     console.dir(this.$refs.tableContainer.bodyWrapper)
    // },
    i18n(title) {
      let languageTitle = "format." + title;
      return this.$t(languageTitle);
    },
    refreshHandle(param) {
      if (param.dateType !== "/baseasis/yearly") return;
      this.emitData = param.data;
      if (this.tableIds && JSON.stringify(this.tableKeyToId) !== "{}") {
        this.tableIds = this.tableKeyToId[
          this.emitData.asis_object === 1 ? this.radioDate : this.multipleRadio
        ];
        this.getData(this.tableIds);
      } else {
        this.getTableId();
      }
    },
    changeTabSelect(val) {
      this.tableIds = this.tableKeyToId[val];
      this.getData(this.tableIds);
    },
    getTableId() {
      this.tableKeyToId = {};
      this.tableIds = "";
      let chartIds = "";
      const keyVal = this.emitData.asis_object === 1
        ? this.radioDate
        : this.multipleRadio
      this.$api.baseReport
        .reportChart({
          report: "BasicReport"
          // _t: Date.parse(new Date()) / 1000
        })
        .then(res => {
          let tableItem = res.data.data;
          tableItem.forEach((item, index) => {
            this.tableKeyToId[item.key] = item.id;
            if (item.key === "kpiData" || item.key === "detailData") {
              if (index == tableItem.length - 1) {
                chartIds += item.id;
              } else {
                chartIds += item.id + ",";
              }
            }
          });
          this.tableIds = this.tableKeyToId[keyVal];
          if (keyVal === 'trafficOfWeek') {
            this.tableIds = 401
          }
          if (keyVal === 'trafficOfMonth') {
            this.tableIds = 366
          }
          this.getData(this.tableIds);
        });
    },
    getData(chartIds) {
      this.loading = true;
      this.tabHeadData = [];
      this.chartData = {};
      this.tabOps = [];
      if (!chartIds) return;
      let formatTime = this.newDateFormat("year", this.emitData.asis_time);
      const keyVal = this.emitData.asis_object === 1
        ? this.radioDate
        : this.multipleRadio
      // this.echartsType = keyVal === "trafficOfMonth" ? "Bar" : "AreaLine";
      this.startDate = formatTime.startTime;
      this.endDate = formatTime.endTime;
      let param = {
        orgIds: this.emitData.asis_org,
        startDate: this.startDate,
        endDate: this.endDate,
        chartIds: chartIds,
        kpiType: this.emitData.asis_object == 1 ? "TRAFFIC" : this.kpiValue,
        option: this.isYTabChart ? "TAB_TABLE" : "TAB_CHART"
      };
      let { params, asisLevel } = this.dealFormat(param, this.emitData);
      this.$api.analysisReport
        .baseAnalysis(asisLevel, params)
        .then(res => {
          let result = res.data;
          let resData =
            result.data.body[keyVal];
          this.detailData_title = "BasicReportdetailData";
          setTimeout(() => {
            this.loading = false;
          }, 500);
          if (resData) {
            // 判断是否是表格还是图
            if (this.isYTabChart) {
              // 表格
              let flowBodyData = Object.freeze(resData.series);
              let flowHeadData = resData.xaxis && Object.freeze(resData.xaxis.data) || [];
              this.tabHeadData = this.autoComplateHead("detail", flowHeadData);
              this.tabOps = this.dealData(
                flowBodyData,
                this.tabHeadData,
                true,
                flowHeadData.length
              );
            } else {
              // 图
              let chartOption = resData;
              chartOption["otherConf"] = {
                _color: [
                  "#3BB8FF",
                  "#FFC62E",
                  "#4396ec",
                  "#4054af",
                  "#d83965",
                  "#9036aa",
                  "#6041b0",
                  "#4fb9d1",
                  "#3f9488",
                  "#97c05c",
                  "#154bee",
                  "#FF9631",
                  "#f39c38",
                  "#e35241"
                ],
                hasYaxisName: false,
                chartKey: true,
                isRadioObject: this.emitData.asis_object === 1 ? true : false,
                isYear: keyVal !== "trafficOfMonth" && keyVal !== "trafficOfWeek" 
              };
              // chartOption.isRadioObject = this.emitData.asis_object === 1 ? true : false;
              if (/\,/.test(this.emitData.asis_org)) {
                chartOption["otherConf"][
                  "selectedLen"
                ] = this.emitData.asis_org.split(",").length;
              }
              // chartOption['chartKey'] = true
              // chartOption['isYear'] = true
              // chartOption['hasYaxisName'] = false
              // chartOption['color'] = ['#3BB8FF', '#FFC62E', '#4396ec', '#4054af', '#d83965', '#9036aa', '#6041b0', '#4fb9d1', '#3f9488', '#97c05c', '#154bee', '#FF9631', '#f39c38', '#e35241']
              this.chartData = chartOption;
            }
          }
        })
        .catch(err => {
          this.catchErrorHandle(err);
          setTimeout(() => {
            this.loading = false;
          }, 500);
        });
    },
    selReport(iconType) {
      if (iconType === "line") {
        if (this.isYTabChart) {
          this.isYTabChart = false;
          this.getData(this.tableIds);
        }
      } else {
        if (!this.isYTabChart) {
          this.isYTabChart = true;
          this.getData(this.tableIds);
        }
      }
    },
    changeSel(tableKey, kpiVal) {
      this.getData(this.tableIds);
    },
    downloadData(title, chartKey) {
      if (this.isYTabChart) {
        this.dealExport("domByTrafficFlow", title);
      } else {
        let chartKey =
          this.emitData.asis_object == 1 ? this.radioDate : this.multipleRadio;
        this.exportDataHandle(title, chartKey);
      }
    },
    exportDataHandle(title, chartKey) {
      let chartId = this.tableKeyToId[chartKey];
      let exportNeed = {
        domId: this.isYTabChart ? "domByTrafficFlow" : "bylineChart",
        title: title,
        data: {
          url: `/report/basics/${this.emitData.asis_level}/${chartId}/excel`,
          params: `orgIds=${this.emitData.asis_org}&startDate=${
            this.startDate
          }&endDate=${this.endDate}&kpiType=${this.kpiValue}&option=${
            this.isYTabChart ? "TAB_TABLE" : "TAB_CHART"
          }`
        }
      };
      this.$refs.exportDialog.dialogInit(exportNeed);
    }
  }
};
</script>

<style scoped>
.bar-report {
  background: url("~@/assets/img/asis/bar_icon.svg") no-repeat;
  background-size: 100% 100%;
}

.report-item-bar {
  background: url("~@/assets/img/asis/active_bar_icon.svg") no-repeat;
  background-size: 100% 100%;
}
</style>