<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="daterange"
            :disabled-date="time => disabledDate(time)"
            range-separator="-"
            start-placeholder="开始日期"
            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.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.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
        v-if="tableData.length"
        keyName="type"
        :tabs="[
          {
            name: '收视率',
            key: 'r',
          },
          {
            name: '占有率',
            key: 'mr',
          },
        ]"
        :list="tableData"
      ></bilateral-bar-chart>
      <el-table
        :data="tableData"
        :header-cell-style="{ backgroundColor: '#f4f5f7', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column type="index" />
        <el-table-column align="center" prop="type" label="频道" />
        <el-table-column
          align="center"
          prop="r"
          :formatter="matrer"
          label="收视率"
        />
        <el-table-column
          align="center"
          prop="mr"
          :formatter="matrer"
          label="市占率"
        />
      </el-table>
    </el-card>
  </div>
</template>

<script>
// @ is an alias to /src
import { channel } from '@/api/index';

import bilateralBarChart from '@/components/bilateralBarChart';

import config from '@/config/index';
export default {
  name: 'Channel',
  data() {
    return {
      form: {
        rangeTime: [],
        channelGroup: 0,
        date: [
          new Date(new Date() - 86400000),
          new Date(new Date() - 86400000),
        ],
        region: -1,
      },
      tableData: [],
    };
  },
  mounted() {
    this.onSubmit();
  },
  computed: {
    cycle() {
      return config.cycle;
    },
    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),
      ];
    },

    onExport() {
      const p = this.formatListData();
      let strcsv =
        'data:text/csv;charset=utf-8,\uFEFF序号,频道,收视率(%),市占率(%)\r\n';
      this.tableData.map((v, i) => {
        strcsv += [
          i + 1,
          v.tvn,
          ((v.r || 0) * 100).toFixed(4),
          ((v.mr || 0) * 100).toFixed(4),
          '\r\n',
        ].join(',');
      });
      // 导出
      let link = document.createElement('a');
      link.id = 'download-csv';
      link.setAttribute('href', encodeURI(strcsv));
      link.setAttribute('download', `收视率收听率分析${p.start}/${p.end}.csv`);
      // document.body.appendChild(link);
      link.click();
      link = undefined;
    },
    disabledDate(time) {
      return time.getTime() > Date.now() - 86400000;
    },
    onSubmit() {
      channel(this.formatListData())
        .then(r => {
          this.tableData = r;
        })
        .catch(err => {
          this.tableData = [];
          console.log('===', err);
        });
    },
    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 e = new Date(this.form.date[1]);
      let d1 = this.dateFormat(this.form.date[0]);
      let d2 = this.dateFormat(e.getTime() + 86400000);
      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,
        area_id: this.form.region || this.region[0].value,
        start: [d1.year, d1.month, d1.day].join('-'),
        end: [d2.year, d2.month, d2.day].join('-'),
      };
    },
    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(',');
    },
  },
  components: { bilateralBarChart },
};
</script>

<style>
.program {
  margin: 10px 15px;
}
.program .has-seconds .el-time-spinner__wrapper:last-child {
  display: none;
}
</style>
