<template>
  <div class="AbstractProgram">
    <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)"
            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 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="tableData"
        v-if="tableData.length"
        xName="day"
        :keys="chartKeys"
      ></line-charts>
      <el-table
        :data="tableData"
        :header-cell-style="{ backgroundColor: '#f4f5f7', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column
          align="center"
          show-overflow-tooltip
          prop="channel_0"
          label="省级卫视"
          class-name="nowrap"
        />
        <el-table-column
          v-for="(item, i) in chartKeys"
          :key="'table' + i"
          align="center"
          :prop="item.key"
          :formatter="matrer"
          :label="item.name"
        />
      </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 {
      searchDate: [],
      chartKeys: [
        {
          key: "indicators_tv_ratings",
          name: "直播关注度排名",
        },
        {
          key: "indicators_tv_ratings",
          name: "直播关注度",
        },
        {
          key: "indicators_market_ratings",
          name: "市占率",
        },
        {
          key: "indicators_arrive",
          name: "到达率",
        },
        {
          key: "indicators_loyal",
          name: "忠诚度",
        },
      ],
      form: {
        filter: {},
        date: [],
        field: [
          "channel_0",
          "day",
          "minute",
          "indicators_arrive_rank",
          "indicators_loyal_rank",
          "indicators_market_ratings_rank",
          "indicators_loyal",
          "indicators_arrive",
          "indicators_market_ratings",
          "indicators_tv_ratings",
          "indicators_tv_ratings_rank",
        ],
        info: 1,
        org_id: 20,
      },
      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, M, D].join("-"), [Y, M, D].join("-")];
    tvselectDate({
      date: this.form.date,
      key: 'channel_0,area_t_1,area_c_8,area_t_2,area_c_12,area_c_13,area_t_3',
      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(r => {
          this.tableData = r || [];
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    });
  },
  computed: {},
  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) {
      if (typeof cellValue !== "number") return 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>
.AbstractProgram {
  margin: 10px 15px;
}
.AbstractProgram .nowrap .cell {
  white-space: nowrap;
}
</style>
