<template>
  <div class="program">
    <el-card class="box-card">
      <el-form
        :model="form"
        size="small"
        :inline="true"
        label-width="120px"
        class="demo-form-inline"
      >
        <el-form-item>
          <template v-for="item in pListData" :key="item.platform">
            <el-button
              :class="
                'colorBtn ' +
                btnGroup[item.platform].class +
                (form.platform == item.platform
                  ? ' ' + btnGroup[item.platform].class + 'act'
                  : '')
              "
              @click="() => tabChange(item)"
            >
              <span
                class="icon iconfont"
                v-html="btnGroup[item.platform].text"
              />
              {{ item.platform }}
            </el-button>
          </template>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="form.dt"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :disabled-date="time => disabledDate(time)"
            placeholder="日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="关键词类别">
          <el-select
            v-model="form.kwName"
            placeholder="请选择"
          >
            <el-option :label="item.value" :value="item.name" v-for="item in selectColumns" :key="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="form.match" placeholder="检索关键词" clearable />
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="onSubmit" :loading="load">
            查询
          </el-button>
          <el-button type="primary" @click="onExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <br />
    <el-card class="box-card">
      <el-tabs v-model="activeTab" class="demo-tabs">
        <el-tab-pane label="传播数据" name="agg">
          <el-table
            :header-cell-style="{
              backgroundColor: '#f4f5f7',
              color: '#606266',
            }"
            ref="table1"
            align="center"
            :data="tableData"
            empty-text="暂无数据"
            style="width: 100%"
            @sort-change="sort_change"
          >
            <template v-for="(item, i) in agg" :key="i">
              <el-table-column
                align="center"
                :width="item.width"
                show-overflow-tooltip
                :prop="item.key"
                :label="item.label"
                :sortable="item.sortable"
                :sort-orders="
                  item.sortable ? ['ascending', 'descending', null] : []
                "
              >
                <template #default="scope">
                  {{
                    item.type == 'number'
                      ? formatter(scope.row[item.key])
                      : scope.row[item.key]
                  }}
                </template>
              </el-table-column>
            </template>
          </el-table>
        </el-tab-pane>
        <el-tab-pane name="list">
          <template #label>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="清单不含已删稿件"
              placement="top"
              :visible="true"
            >
              <div>稿件数据</div>
            </el-tooltip>
          </template>
          <el-table
            :header-cell-style="{
              backgroundColor: '#f4f5f7',
              color: '#606266',
            }"
            ref="table2"
            align="center"
            empty-text="暂无数据"
            :data="tableList"
            style="width: 100%"
            @sort-change="sort_change"
          >
            <template v-for="(item, i) in list" :key="i">
              <el-table-column
                align="center"
                :width="item.width"
                show-overflow-tooltip
                :prop="item.key"
                :label="item.label"
                :sortable="item.sortable"
                :sort-orders="
                  item.sortable ? ['ascending', 'descending', null] : []
                "
              >
                <template #default="scope">
                  {{
                    item.type == 'number'
                      ? formatter(scope.row[item.key])
                      : scope.row[item.key]
                  }}
                </template>
              </el-table-column>
            </template>
          </el-table>
          <br />
          <el-pagination
            @current-change="cChange"
            background
            :page-size="pagesize || 10"
            layout="prev, pager, next"
            :total="total"
          />
          <br />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
// @ is an alias to /src
const ElLoading = require('element-plus/lib/el-loading/index');
import 'element-plus/lib/theme-chalk/el-loading.css';

import { platformList, platformlistData, platform, selectColumns } from '@/api/index';

import { formatter } from '@/utils/tool';

import config from '@/config/index';
let tableDataListOri = [];
let sort = null;
let sortLib = null;
export default {
  name: 'RealData',
  data() {
    return {
      btnGroup: {
        微信: {
          color: '#1cc393',
          class: 'weixin',
          text: '&#xe603;',
        },
        微博: {
          color: '#ffb712',
          class: 'weibo',
          text: '&#xe67a;',
        },
        快手: {
          color: '#ffb712',
          class: 'kuaishou',
          text: '&#xe8dc;',
        },
        抖音: {
          color: '#170b1a',
          class: 'douyin',
          text: '&#xe8db;',
        },
        头条: {
          color: '#de0517',
          class: 'toutiao',
          text: '&#xe607;',
        },
        B站: {
          color: '#ffb712',
          class: 'bzhan',
          text: '&#xe61e;',
        },
        视频号: {
          color: '#ffb712',
          class: 'weixinshipinhao',
          text: '&#xe60a;',
        },
      },
      page: 0,
      pagesize: 20,
      total: 0,
      load: false,
      activeTab: 'agg',
      form: {
        platform: '',
        dt: [],
        match: '',
        kwName: ''
      },
      formRael: { platform: '', dt: [] },
      tableData: [],
      pListData: [],
      selectColumns: []
    };
  },
  mounted() {
    platformList().then(res => {
      const first = res[0] || { platform: '', dt: '' };
      this.form.dt = [first.dt, first.dt];
      this.form.platform = first.platform;
      this.formRael = {
        dt: [first.dt, first.dt],
        platform: first.platform || '',
      };
      this.pListData = res || [];
      this.onSubmit();
    });
    selectColumns().then(r => {
      const li = r || [];
      for (let i = 0; i < li.length; i++) {
        const item = li[i];
        if (item.default != '1') continue;
        this.form.kwName = item.name;
      }
      this.selectColumns = li;
    });
  },
  computed: {
    agg() {
      if (!this.formRael.platform) return [];
      return config.tableCol.agg[this.formRael.platform];
    },
    list() {
      if (!this.formRael.platform) return [];
      return config.tableCol.list[this.formRael.platform];
    },
    tableList() {
      const out = [];
      for (
        let i = (this.page - 1) * this.pagesize;
        i < this.page * this.pagesize;
        i++
      ) {
        const v = tableDataListOri[i];
        v && out.push(v);
      }
      return out;
    },
  },
  methods: {
    formatter,
    tabChange(item) {
      let p = {
        platform: item.platform,
        dt: this.form.dt,
        match: this.form.match,
      };
      if (new Date(item.dt) - new Date(p.dt) < 0) p.dt = item.dt;
      this.form = p;
      this.$refs.table1.clearSort();
      this.$refs.table2.clearSort();
      sortLib = null;
      sort = null;
      this.onSubmit();
    },
    cChange(num) {
      this.page = num;
    },
    onExport() {
      if (!this.formRael.dt || this.formRael.dt.length != 2) return;
      const startd = this.dateFormat(this.formRael.dt[0] || 0);
      const starte = this.dateFormat(this.formRael.dt[1] || 0);
      let url =
        config.base.url2 +
        '/new-media/export?start=' +
        [startd.year, startd.month, startd.day].join('-') +
        '&end=' +
        [starte.year, starte.month, starte.day].join('-');
      if (this.formRael.sort) url += '&sort=' + this.formRael.sort;
      if (this.formRael.match) url += '&match=' + this.formRael.match;
      if (this.formRael.kwName) url += '&kwName=' + this.formRael.kwName;
      window.open(url);
    },
    disabledDate(time) {
      return time.getTime() > Date.now() - 86400000;
    },
    sort_change(type) {
      sort = type.prop;
      sortLib = type.order;
      this.onSubmit();
    },
    onSubmit() {
      const data = this.formatListData();
      this.page = 0;
      this.tableData = [];
      this.total = 0;
      this.load = true;
      const l = ElLoading.default.service();
      Promise.all([platform(data), platformlistData(data)])
        .then(list => {
          this.formRael = data;
          this.formRael.dt = [this.formRael.start, this.formRael.end];
          this.tableData = (list[0] || []).map((v, i) => {
            v.index = i + 1;
            return v;
          });
          tableDataListOri = (list[1] || []).map((v, i) => {
            v.index = i + 1;
            return v;
          });
          this.total = tableDataListOri.length;
          this.page = this.page + 1;
          this.load = false;
          l.close();
        })
        .catch(() => {
          this.load = false;
          l.close();
        });
    },
    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() {
      const startd = this.form.dt[0] ? this.dateFormat(this.form.dt[0]) : false;
      const starte = this.form.dt[1] ? this.dateFormat(this.form.dt[1]) : false;
      const loginname = JSON.parse(
        window.parent.localStorage.userinfo || '{}'
      ).loginname;
      const p = {
        platform: this.form.platform || this.pListData[0],
        start: startd
          ? [startd.year, startd.month, startd.day].join('-')
          : undefined,
        end: starte
          ? [starte.year, starte.month, starte.day].join('-')
          : undefined,
        match: this.form.match,
        userId: loginname,
        kwName: this.form.kwName
      };
      sort && (p.sort = sort);
      const sortLibType = {
        descending: 1,
        ascending: 0,
      };
      sortLib && (p.order = sortLibType[sortLib]);
      return p;
    },
  },
  components: {},
};
</script>

<style>
.colorBtn {
  background-color: #fff;
  color: #000;
  padding: 0 18px;
  width: 8em;
  height: 38px;
  line-height: 38px;
  font-size: 14px;
}
.weibo .icon {
  color: #ffb712;
}
.weiboact,
.weibo:hover,
.weibo:focus,
.weiboact .icon,
.weibo:hover .icon {
  background-color: #ffb712;
  border-color: #ffb712;
  color: #fff;
}
.toutiao .icon {
  color: #f04142;
}
.toutiaoact,
.toutiao:hover,
.toutiao:focus,
.toutiaoact .icon,
.toutiao:hover .icon {
  background-color: #f04142;
  border-color: #f04142;
  color: #fff;
}
.weixin .icon {
  color: #1cc393;
}
.weixinact,
.weixin:hover,
.weixin:focus,
.weixinact .icon,
.weixin:hover .icon {
  background-color: #1cc393;
  border-color: #1cc393;
  color: #fff;
}
.kuaishou .icon {
  color: #eb3661;
}
.kuaishouact,
.kuaishou:hover,
.kuaishou:focus,
.kuaishou:focus,
.kuaishouact .icon,
.kuaishou:hover .icon {
  background-color: #eb3661;
  border-color: #eb3661;
  color: #fff;
}
.douyin .icon {
  color: #170b1a;
}
.douyinact,
.douyin:hover,
.douyin:focus,
.douyinact .icon,
.douyin:hover .icon {
  background-color: #170b1a;
  border-color: #170b1a;
  color: #fff;
}
.bzhan .icon {
  color: #fb7299;
}
.bzhanact,
.bzhan:hover,
.bzhan:focus,
.bzhanact .icon,
.bzhan:hover .icon {
  background-color: #fb7299;
  border-color: #fb7299;
  color: #fff;
}
.weixinshipinhao .icon {
  color: #fa9d3b;
}
.weixinshipinhaoact,
.weixinshipinhao:hover,
.weixinshipinhao:focus,
.weixinshipinhaoact .icon,
.weixinshipinhao:hover .icon {
  background-color: #fa9d3b;
  border-color: #fa9d3b;
  color: #fff;
}
</style>
