<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-select
            v-model="form.filter.abs_epg"
            multiple
            filterable
            collapse-tags
            remote
            placeholder="请输入节目名"
            reserve-keyword
            :remote-method="querySearchAsync"
          >
            <el-option
              v-for="item in selectList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="form.date"
            type="daterange"
            :disabled-date="time => disabledDate(time)"
            range-separator="-"
            value-format="YYYY-MM-DD"
            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 label="时间">
          <el-time-picker
            v-model="rangeTime"
            is-range
            format="HH:mm"
            @change="() => (form.filter.time = [])"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-time-picker>
        </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
        v-if="tableData.length"
        :list="tableDate"
        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="29省"
          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 {
  overlapSearchTitle,
  selectDate,
  country,
//   countryExport,
} from "@/api/kuyun";

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

import config from "@/config/index";
export default {
  name: "Channel",
  data() {
    return {
      searchDate: [],
      selectList: [],
      rangeTime: [],
      form: {
        info: 1,
        org_id: 20,
        field: [
          "area_c_1",
          "abs_epg",
          "indicators_tv_ratings",
          "indicators_market_ratings",
        ],
        filter: {},
      },
      tableData: [],
      loading: false,
      loading1: false,
    };
  },
  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 - 1, M, D].join("-"),[Y, M, D].join("-")];
    this.loading = true;
    selectDate({
      date: this.form.date,
      key: "abs_epg,channel_0,time,week,area_c_1",
      org_id: 20,
    })
      .then(r => {
        this.searchDate = r || [];
        for (let i = 0; i < this.searchDate.length; i++) {
          const v = this.searchDate[i];
          this.form.filter[v.id] = [v.list[0].key + ""];
        }
        country(this.form)
          .then(r => {
            this.tableData = r || [];
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      })
      .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: "市占率",
        },
      ];
      for (let i = 0; i < this.tableData.length; i++) {
        const v = this.tableData[i];
        if (typeof obj[v.abs_epg] !== "object") obj[v.abs_epg] = [];
        obj[v.abs_epg][v.area_c_1] = 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: "市占率",
          },
        ];
        const v = this.tableData[i];
        if (obj[v.abs_epg] === true) continue;
        obj[v.abs_epg] = true;
        li.push(
          ...b.map(k => {
            k.key = v.abs_epg + "_" + k.key;
            k.name = v.abs_epg + "_" + k.name;
            return k;
          })
        );
      }
      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: "市占率",
          },
        ];
        const v = this.tableData[i];
        if (obj[v.abs_epg] === true) continue;
        obj[v.abs_epg] = true;
        li.push({
          name: v.abs_epg,
          children: b.map(k => {
            k.key = v.abs_epg + "_" + k.key;
            return k;
          }),
        });
      }
      return li;
    },
  },
  methods: {
    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];
      this.rangeTime = [];
    },
    querySearchAsync(queryString) {
      if (!queryString) {
        this.selectList = [];
        return;
      }
      overlapSearchTitle("kw=" + queryString + "&ft=1").then(r => {
        this.selectList = r || [];
      });
    },
    onExport() {
      this.loading1 = true;
      let form = JSON.parse(JSON.stringify(this.form));
      if (this.rangeTime.length) {
        form.filter.time = this.rangeTime;
      }
      let keys = Object.keys(this.form.filter);
      form.filter.time = ["0000_2400"];
      for (let i = 0; i < keys.length; i++) {
        const v = keys[i];
        if (v === "time") 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;
          }
        }
      }
      fetch(
        config.base.kuyunApi + "/kuyun/api/evaluation/eye/download/performance/epgkpi/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));
      if (this.rangeTime.length) {
        form.filter.time = this.rangeTime;
      }
      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;
          }
        }
      }
      country(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");
        this.rangeTime = [];
      } else this.timeSelect(se, v.id, "-1");
    },
  },
  components: { lineCharts },
};
</script>

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