<template>
  <div class="customRanking">
    <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-autocomplete
            v-model="form.program"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入频道"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="form.date"
            type="daterange"
            :disabled-date="time => disabledDate(time)"
            range-separator="-"
            start-placeholder="开始日期"
            value-format="YYYY-MM-DD"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时间">
          <el-time-picker
            v-model="form.rangeTime"
            is-range
            format="HH:mm"
            @change="() => (form.filter.time = [])"
            range-separator="-"
            start-placeholder="开始时间"
            value-format="HH:mm"
            end-placeholder="结束时间"
          >
          </el-time-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-select v-model="form.tv_type" placeholder="请选择频道组">
            <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-cascader
            v-model="form.region"
            :options="region"
            :props="{ children: 'options' }"
          ></el-cascader>
        </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">
      <el-table
        :data="tableData"
        :header-cell-style="{ backgroundColor: '#f4f5f7', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          align="center"
          show-overflow-tooltip
          prop="tv_name"
          label="频道"
          class-name=""
        />
        <el-table-column
          align="center"
          show-overflow-tooltip
          label="直播关注度"
          class-name=""
        >
          <template #default="scope">
            <el-progress
              :percentage="
                (scope.row.tv_ratings / (total.tv_ratings || 1)) * 100
              "
              color="#00bed0"
              :format="() => rogressText(scope.row, 'tv_ratings')"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          show-overflow-tooltip
          prop="tv_name"
          label="市占率"
          class-name=""
        >
          <template #default="scope">
            <el-progress
              :percentage="
                (scope.row.market_ratings / (total.market_ratings || 1)) * 100
              "
              color="#fcc543"
              :format="() => rogressText(scope.row, 'market_ratings')"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

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

import config from "@/config/index";

export default {
  name: "CustomRanking",
  data() {
    return {
      searchDate: [],
      form: {
        filter: {},
        rangeTime: [],
        tv_type: 0,
        date: [],
        region: -1,
      },
      total: {},
      tableData: [],
    };
  },
  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("-")];
    this.total = this.tableData[0] || {};
    selectDate({
      date: this.form.date,
      key: "time",
      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;
        }
      }
    });
  },
  computed: {
    channelList() {
      return config.channelList;
    },
    region() {
      return config.region;
    },
  },
  methods: {
    handleSelect(item) {
      this.form.tv_id = item.id || "";
    },
    querySearchAsync(queryString, cb) {
      if (!queryString) {
        cb([]);
        return;
      }
      overlapSearchTitle("kw=" + queryString).then(r => {
        let li = (r || []).map(v => {
          return {
            value: v.name,
            id: v.id,
          };
        });
        cb(li);
      });
    },
    rogressText(v, key) {
      return (v[key] * 100).toFixed(4) + "%";
    },

    onExport() {
      let d = this.form.date || [];
      let li = this.form.rangeTime || [],
        type = "range";
      if (this.form.filter.time && this.form.filter.time.length) {
        li = this.form.filter.time;
        type = "select";
      }
      let time = this.formatTime(li, type);
      tvrangeexport(
        {
          tv_id: this.form.tv_id,
          area_id: this.form.region,
          weekday: 0,
          tv_type: this.form.tv_type,
          start: d[0] ? d[0] + "+00:00:00" : "",
          end: d[1] ? d[1] + "+23:59:59" : "",
          time_range: time,
        },
        "自定义时段 频道收视排行.csv"
      );
    },
    disabledDate(time) {
      return time.getTime() > Date.now() - 86400000;
    },
    formatTime(li, type) {
      let timelist = li || [],
        start = timelist[0] || "",
        end = timelist[timelist.length - 1] || "";
      if (type === "select") {
        let out = "" || "";
        out += start.split("_")[0] + "_" + (end.split("_")[1] || "");
        return out;
      }
      return start.replace(":", "") + "_" + end.replace(":", "");
    },
    onSubmit() {
      let d = this.form.date || [];
      let li = this.form.rangeTime || [],
        type = "range";
      if (this.form.filter.time && this.form.filter.time.length) {
        li = this.form.filter.time;
        type = "select";
      }
      let time = this.formatTime(li, type);
      tvrange({
        tv_id: this.form.tv_id,
        area_id: this.form.region,
        weekday: 0,
        tv_type: this.form.tv_type,
        start: d[0] ? d[0] + "+00:00:00" : "",
        end: d[1] ? d[1] + "+23:59:59" : "",
        time_range: time,
      }).then(r => {
        let li = r || { list: [] };
        this.tableData = li.list;
        this.total = this.tableData[0] || {};
      });
    },
    matrer(row, column, cellValue) {
      return (cellValue * 100).toFixed(4) + "%";
    },
    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) {
      this.timesSelect(se, v.id, "0000_2400");
      this.rangeTime = [];
    },

    timesSelect(a, key, all) {
      let ngx = new RegExp(all + ",?", "g");
      let li = [];
      let end = (a || [])[(a || []).length - 1],
        s = (a || []).join(",").replace(ngx, "");
      if (end !== all) li = s ? s.split(",") : [];
      else li = [all];
      li = li.sort((a, b) => {
        let as = a.split("_");
        let bs = b.split("_");
        return as[0] - bs[0];
      });
      for (let i = 1; i < li.length; i++) {
        const ov = li[i - 1].split("_");
        const v = li[i].split("_");

        if (ov[1] !== v[0]) {
          break; // 时间不完整
        }
      }

      this.form.filter[key] = li;
      this.form.rangeTime = [];
    },
  },
  components: {},
};
</script>

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