<template>
  <div class="SingleDay">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>传统媒体</el-breadcrumb-item>
      <el-breadcrumb-item>频道全天节目</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-form
        ref="form"
        :model="form"
        size="small"
        :inline="true"
        label-width="120px"
        class="demo-form-inline"
      >
        <el-form-item label="日期">
          <el-date-picker
            v-model="form.date"
            type="daterange"
            :disabled-date="time => disabledDate(time)"
            value-format="YYYY-MM-DD"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item :label="v.name" v-for="(v, i) in searchDate" :key="i">
          <el-select
            v-model="form.filter[v.key]"
            :placeholder="'请选择' + v.name"
            multiple
            collapse-tags
            @change="se => select(v, se)"
          >
            <el-option key="-1" v-if="v.id !== 'time'" label="全选" value="-1">
            </el-option>
            <el-option
              v-for="item in v.list || []"
              :key="item.id + ''"
              :label="item.name"
              :value="item.key + ''"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" :loading="loading" @click="onSubmit"
            >查询</el-button
          >
          <el-button type="primary" :loading="loading1" @click="onExport"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <br />
    <el-card class="box-card">
      <line-charts
        :list="tableDate"
        v-if="tableData.length"
        xName="date"
        :keys="chartKeys"
      ></line-charts>
      <el-table
        :data="tableDate"
        :header-cell-style="{ backgroundColor: '#f4f5f7', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column
          align="center"
          show-overflow-tooltip
          prop="date"
          label="日期"
          class-name="nowrap"
        />
        <el-table-column
          v-for="(item, i) in tableKeys"
          :key="'table' + i"
          align="center"
          :prop="item.key"
          :formatter="matrer"
          :label="item.name"
        >
          <el-table-column
            v-for="(li, o) in item.children"
            :key="i + '-' + o"
            :prop="li.key"
            :label="li.name"
            :formatter="matrer"
          />
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
// @ is an alias to /src
import { tvselectDate, tvcountry } from "@/api/kuyun";

import lineCharts from "@/views/Country/components/lineCharts";

import config from "@/config/index";
export default {
  name: "Channel",
  data() {
    return {
      form: {
        filter: {},
        date: [],
        field: [
          "day",
          "channel_2",
          "indicators_arrive",
          "indicators_market_ratings",
          "indicators_tv_ratings",
        ],
        info: 1,
        org_id: 20,
      },
      searchDate: [],
      loading: false,
      loading1: false,
      tableData: [],
    };
  },
  mounted() {
    const d = new Date(Date.now() - 86400000);
    let Y = d.getFullYear(),
      M = d.getMonth() + 1,
      D = d.getDate();
    M > 9 ? "" : (M = "0" + M);
    D > 9 ? "" : (D = "0" + D);
    this.form.date = [[Y, M, D].join("-"), [Y, M, D].join("-")];
    this.loading = true;
    tvselectDate({
      date: this.form.date,
      key: "channel_2,area_t_1",
      org_id: 20,
    }).then(r => {
      let area = false;
      this.searchDate = r || [];
      for (let i = 0; i < this.searchDate.length; i++) {
        const v = this.searchDate[i];
        if (/area/.test(v.id)) {
          if (area) continue;
          area = true;
          this.form.filter[v.id] = [v.list[0].key + ""];
          continue;
        }
        this.form.filter[v.id] = [v.list[0].key + ""];
      }
      tvcountry(this.form)
        .then(res => {
          console.log(res);
          this.loading = false;
          this.tableData = res || [];
        })
        .catch(() => {
          this.loading = false;
        });
    });
  },
  computed: {
    tableDate() {
      if (!this.tableData.length) return [];
      const obj = {};

      const b = [
        {
          key: "indicators_tv_ratings",
          name: "直播关注度",
        },
        {
          key: "indicators_market_ratings",
          name: "市占率",
        },
        {
          key: "indicators_arrive",
          name: "到达率",
        },
      ];
      for (let i = 0; i < this.tableData.length; i++) {
        const v = this.tableData[i];
        if (typeof obj[v.channel_2] !== "object") obj[v.channel_2] = {};
        obj[v.channel_2][v.day] = v;
      }
      let li = [],
        keys = Object.keys(obj),
        dataLen = Object.keys(obj[keys[0]]);
      for (let i = 0; i < dataLen.length; i++) {
        let p = {};
        for (let o = 0; o < keys.length; o++) {
          const v = obj[keys[o]][dataLen[i]];
          b.map(k => {
            p[keys[o] + "_" + k.key] = v[k.key];
          });
        }
        li.push({
          date: dataLen[i],
          ...p,
        });
      }
      return li;
    },
    chartKeys() {
      const obj = {},
        li = [];
      for (let i = 0; i < this.tableData.length; i++) {
        const b = [
          {
            key: "indicators_tv_ratings",
            name: "直播关注度",
          },
          {
            key: "indicators_market_ratings",
            name: "市占率",
          },
          {
            key: "indicators_arrive",
            name: "到达率",
          },
        ];
        const v = this.tableData[i];
        if (obj[v.channel_2] === true) continue;
        obj[v.channel_2] = true;
        li.push(
          ...b.map(k => {
            k.key = v.channel_2 + "_" + k.key;
            k.name = v.channel_2 + "_" + k.name;
            return k;
          })
        );
      }
      console.log(li);
      return li;
    },
    tableKeys() {
      const obj = {},
        li = [];
      for (let i = 0; i < this.tableData.length; i++) {
        const b = [
          {
            key: "indicators_tv_ratings",
            name: "直播关注度",
          },
          {
            key: "indicators_market_ratings",
            name: "市占率",
          },
          {
            key: "indicators_arrive",
            name: "到达率",
          },
        ];
        const v = this.tableData[i];
        if (obj[v.channel_2] === true) continue;
        obj[v.channel_2] = true;
        li.push({
          name: v.channel_2,
          children: b.map(k => {
            k.key = v.channel_2 + "_" + k.key;
            return k;
          }),
        });
      }
      return li;
    },
  },
  methods: {
    onExport() {
      this.loading1 = true;
      let form = JSON.parse(JSON.stringify(this.form));
      fetch(
        config.base.kuyunApi +
          "/api/evaluation/eye/download/performance/tvkpi/download",
        {
          method: "post",
          responseType: "blob",
          body: JSON.stringify(form),
        }
      )
        .then(res => {
          return res.blob();
        })
        .then(blob => {
          new Blob([blob]);
          let fileName = "频道分地区收视.csv";
          var link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          window.URL.revokeObjectURL(link.href);
          this.loading1 = false;
        });
    },
    disabledDate(time) {
      return time.getTime() > Date.now() - 86400000;
    },
    onSubmit() {
      this.loading = true;
      let form = JSON.parse(JSON.stringify(this.form));
      let keys = Object.keys(this.form.filter);
      for (let i = 0; i < keys.length; i++) {
        const v = keys[i];
        if (form.filter[v] != -1) continue;
        for (let o = 0; o < this.searchDate.length; o++) {
          const item = this.searchDate[o];
          if (v === item.key) {
            form.filter[v] = item.list.map(v => v.key);
            break;
          }
        }
      }
      tvcountry(form)
        .then(r => {
          this.tableData = r || [];
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    matrer(row, column, cellValue) {
      return (cellValue * 100).toFixed(4) - 0 + "%";
    },
    select(v, se) {
      if (v.id === "time") {
        this.timeSelect(se, v.id, "0000_2400");
      } else this.timeSelect(se, v.id, "-1");
    },
    timeSelect(a, key, all) {
      let ngx = new RegExp(all + ",?", "g");
      let end = (a || [])[(a || []).length - 1],
        s = (a || []).join(",").replace(ngx, "");
      if (end !== all) this.form.filter[key] = s ? s.split(",") : [];
      else this.form.filter[key] = [all];
    },
  },
  components: { lineCharts },
};
</script>

<style>
.SingleDay {
  margin: 10px 15px;
}
.SingleDay .nowrap .cell {
  white-space: nowrap;
}
</style>
