<template>
  <div class="program">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>传统媒体</el-breadcrumb-item>
      <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="date"
            placeholder="日期"
            :disabled-date="time => disabledDate(time)"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时间">
          <el-time-picker
            v-model="form.rangeTime"
            is-range
            format="HH:mm"
            @change="() => (form.rangeTimeRange = [])"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item label="时段">
          <el-select
            v-model="form.rangeTimeRange"
            placeholder="请选择时段"
            multiple
            collapse-tags
            clearable
            @change="timeSelect"
          >
            <el-option
              v-for="item in cycle"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="频道组">
          <el-select
            v-model="form.channelGroup"
            placeholder="请选择频道组"
            @change="channelSelect"
          >
            <el-option
              v-for="item in channelList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="form.classification"
            multiple
            clearable
            collapse-tags
            placeholder="请选择分类"
            @change="classSelect"
          >
            <el-option-group
              v-for="group in classification"
              :key="group.value"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="区域">
          <el-select
            v-model="form.region"
            placeholder="请选择区域"
            @change="regionSelect"
          >
            <el-option-group
              v-for="group in region"
              :key="group.value"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="onExport">导出</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="epg_name"
        :list="tableData"
      ></bilateral-bar-chart>
      <el-table
        :data="tableData"
        :header-cell-style="{ backgroundColor: '#f4f5f7', color: '#606266' }"
        style="width: 100%"
        @row-click="clickRow"
      >
        <el-table-column align="center" prop="" label="" width="30">
          <template #default="scope">
            <div
              v-if="scope.row.heightlight === '是'"
              style="height: 1em;width:1em;"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 1024 1024"
                data-v-066465b6=""
              >
                <path
                  fill="currentColor"
                  d="M340.864 149.312a30.592 30.592 0 0 0 0 42.752L652.736 512 340.864 831.872a30.592 30.592 0 0 0 0 42.752 29.12 29.12 0 0 0 41.728 0L714.24 534.336a32 32 0 0 0 0-44.672L382.592 149.376a29.12 29.12 0 0 0-41.728 0z"
                ></path>
              </svg>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" />
        <el-table-column align="center" prop="epg_name" label="节目" />
        <el-table-column align="center" prop="tv_name" label="频道" />
        <el-table-column
          align="center"
          prop="tv_name"
          :formatter="playTime"
          label="播出时间"
        />
        <el-table-column
          align="center"
          prop="heightlight"
          :formatter="heightlightStyle"
          label="高光时刻"
          width="180"
        >
          <template #default="scope">
            <el-image
              style="width: 1em; height: 1em; vertical-align: middle;"
              :src="require('../assets/img/lightning.png')"
              fit="fit"
              v-if="scope.row.heightlight === '是'"
            ></el-image>
            <span style="vertical-align: middle;">
              {{ scope.row.heightlight }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="tv_ratings"
          :formatter="matrer"
          label="收视率"
          width="180"
        />
        <el-table-column
          align="center"
          prop="market_ratings"
          :formatter="matrer"
          label="市占率"
          width="180"
        />
      </el-table>
    </el-card>
  </div>
</template>

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

import { list, listcsv,heightlightApi } from "@/api/index";
import config from "@/config/index";
let milestone = [];
export default {
  name: "Program",
  data() {
    return {
      form: {
        rangeTimeRange: [],
        rangeTime: [],
        channelGroup: 0,
        classification: [],
        date: new Date(new Date() - 86400000),
        region: -1,
      },
      tableData: [],
    };
  },
  mounted() {
    let d = this.dateFormat(this.form.date);
    heightlightApi({
      date: [d.year, d.month, d.day].join("-"),
    })
      .then(r => {
        milestone = r || [];
        this.onSubmit();
      })
      .catch(err => {
        console.error(err);
      });
  },
  computed: {
    cycle() {
      return config.cycle;
    },
    classification() {
      return config.classification;
    },
    channelList() {
      return config.channelList;
    },
    region() {
      return config.region;
    },
  },
  methods: {
    timeSelect(a) {
      let end = (a || [])[(a || []).length - 1];
      if (this.form.rangeTimeRange.length === config.cycle.length - 1) {
        this.form.rangeTimeRange = ["0000_2400"];
      } else {
        let n = (this.form.rangeTimeRange || []).sort((a, b) => {
          let aNum = a.split("_")[0];
          let bNum = b.split("_")[0];
          return aNum - bNum;
        });
        let isSelect = true;
        for (let i = 0; i < n.length - 1; i++) {
          let aNum = n[i].split("_")[1];
          let bNum = n[i + 1].split("_")[0];
          if (aNum !== bNum) {
            isSelect = false;
            break;
          }
        }
        if (!isSelect) {
          let arr = (n.join(",") + ",")
            .replace(end + ",", "")
            .replace(/,$/, "");
          this.form.rangeTimeRange = arr.split(",");
        }
      }
      if (!this.form.rangeTimeRange.length) return;
      let s = this.form.rangeTimeRange[0].split("_")[0];
      let e = this.form.rangeTimeRange[
        this.form.rangeTimeRange.length - 1
      ].split("_");
      e = e[e.length - 1];
      if (e == "2400") e = "2359";
      this.form.rangeTime = [
        new Date(1970, 1, 1, s[0] + s[1] - 0, s[2] + s[3] - 0),
        new Date(1970, 1, 1, e[0] + e[1] - 0, e[2] + e[3] - 0),
      ];
    },
    playTime(row) {
      return row.start_time.split(" ")[1] + "~" + row.end_time.split(" ")[1];
    },
    heightlightStyle(row, column, cellValue) {
      if (cellValue === "是") return "<el-icon><flag /></el-icon>";
      else return "<el-icon><document-add /></el-icon>";
    },
    clickRow(row) {
      if (!row.heightlight || row.heightlight === "否") return;
      this.$router.push({
        path: "/heightlight",
        query: { id: row.ca_id, t: row.tv_id },
      });
    },
    disabledDate(time) {
      return time.getTime() > Date.now() - 86400000;
    },
    onExport() {
      listcsv(this.formatListData());
    },
    formatlist(li) {
      let joinMilestone = milestone.join(",");
      return li.map(v => {
        const ngx = new RegExp(v.tv_id + "_" + v.ca_id, "g");
        v.heightlight = ngx.test(joinMilestone) ? "是" : "否";
        return v;
      });
    },
    onSubmit() {
      list(this.formatListData())
        .then(r => {
          this.tableData = this.formatlist(r.list);
        })
        .catch(() => {
          this.tableData = [];
        });
    },
    matrer(row, column, cellValue) {
      return (cellValue * 100).toFixed(4) + "%";
    },
    dateFormat(date) {
      let D = new Date(date);
      let m = D.getMonth() + 1;
      let d = D.getDate();
      let h = D.getHours();
      let M = D.getMinutes();
      let s = D.getSeconds();
      m > 9 ? m : (m = "0" + m);
      d > 9 ? d : (d = "0" + d);
      h > 9 ? h : (h = "0" + h);
      M > 9 ? M : (M = "0" + M);
      s > 9 ? s : (s = "0" + s);
      return {
        year: D.getFullYear(),
        month: m,
        day: d,
        hour: h,
        minutes: M,
        seconds: s,
      };
    },
    formatListData() {
      let d = this.dateFormat(this.form.date);
      let time = "";
      if (this.form.rangeTime.length) {
        let start = new Date(this.form.rangeTime[0]);
        let end = new Date(this.form.rangeTime[1]);
        let start_hour = start.getHours();
        let start_min = start.getMinutes();
        let end_hour = end.getHours();
        let end_min = end.getMinutes();
        start_hour = start_hour > 9 ? start_hour + "" : "0" + start_hour;
        start_min = start_min > 9 ? start_min + "" : "0" + start_min;
        end_hour = end_hour > 9 ? end_hour + "" : "0" + end_hour;
        end_min = end_min > 9 ? end_min + "" : "0" + end_min;
        if (end_hour + end_min === "2359") {
          end_hour = "24";
          end_min = "00";
        }
        time = start_hour + start_min + "_" + end_hour + end_min;
      } else {
        time = "0000_2400";
      }
      return {
        tv_type: this.form.channelGroup || this.channelList[0].value,
        time_range: time,
        date: [d.year, d.month, d.day].join("-"),
        ca_type: this.form.classification.join(",") || [
          this.classification[0].value,
        ],
        area_id: this.form.region || this.region[0].value,
      };
    },
    classSelect(a) {
      this.selectAll(a, "classification", "0");
    },
    channelSelect(a) {
      this.selectAll(a, "channelGroup", 0);
    },
    regionSelect(a) {
      this.selectAll(a, "region", -1);
    },
    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(",");
    },
  },
  beforeUnmount: function() {
    // milestone = null;
  },
  components: { bilateralBarChart },
};
</script>

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