<template>
  <div class="Key">
    <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"
            placeholder="日期"
            value-format="YYYY-MM-DD"
            :disabled-date="time => disabledDate(time)"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="分析周期">
          <el-select v-model="form.cycle" placeholder="请选择">
            <el-option
              v-for="item in cycleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.area" label="地区">
          <el-select v-model="form.area" placeholder="请选择">
            <el-option
              v-for="item in areaList"
              :key="item"
              :label="item"
              :value="item"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电台">
          <el-select
            multiple
            v-model="form.rb"
            collapse-tags
            clearable
            placeholder="请选择"
            @change="channelSelect"
          >
            <el-option
              v-for="item in radioList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <br />
    <el-card class="box-card">
      <bilateral-bar-chart
        ref="chart"
        v-if="tableData.length"
        keyName="program_name"
        :list="tableData"
        :tabs="[
          {
            name: '收听率',
            key: 'radio_rate',
          },
          {
            name: '占有率',
            key: 'market_rate',
          },
        ]"
      ></bilateral-bar-chart>
      <div style="text-align: right; padding: 1em 0">
        <el-button size="small" type="primary" @click="onExport">
          导出
        </el-button>
      </div>
      <el-table
        :data="tableData"
        :header-cell-style="{ backgroundColor: '#f4f5f7', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column align="center" prop="" label="" width="30">
        </el-table-column>
        <el-table-column type="index" />
        <el-table-column align="center" prop="dt" label="日期" />
        <el-table-column align="center" prop="name" label="广播" />
        <el-table-column align="center" prop="program_name" label="栏目名称" />
        <el-table-column
          align="center"
          prop="radio_rate"
          sortable
          :formatter="
            (row, column, cellValue) => (cellValue * 100).toFixed(4) + '%'
          "
          label="收听率"
        />
        <el-table-column
          align="center"
          prop="market_rate"
          sortable
          :formatter="
            (row, column, cellValue) => (cellValue * 100).toFixed(4) + '%'
          "
          label="占有率"
        />
      </el-table>
    </el-card>
  </div>
</template>

<script>
// @ is an alias to /src
import bilateralBarChart from "@/components/bilateralBarChart";

import { audioKeyGet, audioList, audioAreaList } from "@/api/index";
import config from "@/config/index";
export default {
  name: "Key",
  data() {
    return {
      form: {
        rb: [],
        cycle: "None",
        date: [],
        area: undefined,
      },
      tableData: [],
      radioList: [],
      areaList: [],
    };
  },
  mounted() {
    const t = new Date(Date.now() - 86400000),
      y = t.getFullYear(),
      m = t.getMonth() + 1 > 9 ? t.getMonth() + 1 : "0" + (t.getMonth() + 1),
      d = t.getDate() > 9 ? t.getDate() : "0" + t.getDate(),
      date = [y, m, d].join("-");
    this.form.date = [date, date];
    audioList().then(r => {
      let radioList = [
        {
          name: "全部",
          value: "全部",
        },
      ];
      for (let i = 0; i < (r || []).length; i++) {
        const v = (r || [])[i];
        radioList.push({
          name: v,
          value: v,
        });
      }
      this.radioList = radioList;
      this.form.rb = [radioList[0].name];
    });

    // 地区
    audioAreaList().then(r => {
      console.log(r);
      this.areaList = r || [];
      this.form.area = this.areaList[0];
    });

    this.onSubmit();
  },
  computed: {
    cycleList() {
      return config.audioCycle;
    },
  },
  methods: {
    playTime(row) {
      return row.start_time.split(" ")[1] + "~" + row.end_time.split(" ")[1];
    },
    disabledDate(time) {
      let timeNow = time.getTime();
      return (
        timeNow > Date.now() - 86400000 || timeNow < new Date("2021-12-31")
      );
    },
    onSubmit() {
      audioKeyGet(this.formatListData())
        .then(r => {
          this.tableData = r || [];
        })
        .catch(() => {
          this.tableData = [];
        });
    },
    formatListData() {
      let s = (this.form.date[0] || "").replace(/-/g, ""),
        e = (this.form.date[1] || "").replace(/-/g, ""),
        rb = [];
      for (let i = 0; i < this.form.rb.length; i++) {
        const v = this.form.rb[i];
        if (v !== "全部") rb.push(v);
      }
      return {
        start: s,
        end: e,
        range: this.form.cycle,
        names: rb,
        area: this.form.area || undefined,
      };
    },
    channelSelect(a) {
      if (!a.length) return;
      if (a[a.length - 1] === "全部") return (this.form.rb = ["全部"]);
      let l = [];
      for (let i = 0; i < a.length; i++) {
        const v = a[i];
        if (v === "全部") continue;
        l.push(v);
      }
      this.form.rb = l;
    },
    onExport() {
        const data = this.formatListData();
      audioKeyGet(data).then(r => {
        // 生成数据
        let strcsv = "data:text/csv;charset=utf-8,\uFEFF广播,栏目名称,收听率,占有率,区域,日期区间\r\n";
        (r || []).map(v => {
          strcsv += [
            v.name,
            v.program_name,
            v.radio_rate * 100 + "%",
            v.market_rate * 100 + "%",
            data.area,
            v.dt,
            "\r\n",
          ].join(",");
        });
        // 导出
        let link = document.createElement("a");
        link.id = "download-csv";
        link.setAttribute("href", encodeURI(strcsv));
        link.setAttribute("download", "重点栏目分析" + ".csv");
        // document.body.appendChild(link);
        link.click();
        link = undefined;
      });
    },
  },
  beforeUnmount: function () {},
  components: { bilateralBarChart },
};
</script>

<style>
.Key {
  margin: 10px 15px;
}
</style>
