<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)"
            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 label="时间">
          <el-time-picker
            v-model="rangeTime"
            is-range
            format="HH:mm"
            range-separator="-"
            @change="() => (form.filter.time = [])"
            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
        :list="tableData"
        v-if="tableData.length"
        xName="abs_epg"
        :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="abs_epg"
          label="抽象节目"
          class-name="nowrap"
        />
        <el-table-column align="center" prop="time" label="时段" />
        <el-table-column
          prop="indicators_market_ratings"
          :formatter="matrer"
          label="市占率"
        />
        <el-table-column
          prop="indicators_tv_ratings"
          :formatter="matrer"
          label="直播关注度"
        />
      </el-table>
    </el-card>
  </div>
</template>

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

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

import config from "@/config/index";
export default {
  name: "Channel",
  data() {
    return {
      searchDate: [],
      rangeTime: [],
      chartKeys: [
        {
          key: "indicators_market_ratings",
          name: "市占率",
        },
        {
          key: "indicators_tv_ratings",
          name: "直播关注度",
        },
      ],
      form: {
        filter: {},
        date: [
          new Date(new Date() - 86400000),
          new Date(new Date() - 86400000),
        ],
        field: [
          "abs_epg",
          "time",
          "indicators_market_ratings",
          "indicators_tv_ratings",
        ],
        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 - 1, M, D].join("-"), [Y, M, D].join("-")];
    selectDate({
      date: this.form.date,
      key: "channel_0,area_t_1,area_c_9,area_c_1,abs_epg,time,week",
      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 + ""];
      }
      country(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));
      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 +
          "/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) {
      if (typeof cellValue !== "number") return cellValue;
      return (cellValue * 100).toFixed(4) - 0 + "%";
    },
    selectAll(a, key, val) {
      if (!a.length) return;
      let select = a[a.length - 1];
      if (select === val) this.form[key] = [val];
      else
        this.form[key] = (a.join(",") + ",")
          .replace(val + ",", "")
          .replace(/,$/, "")
          .split(",");
    },

    select(v, se) {
      if (v.id === "time") {
        this.timeSelect(se, v.id, "0000_2400");
        this.rangeTime = [];
      } 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];
      this.rangeTime = [];
    },
  },
  components: { lineCharts },
};
</script>

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