<template>
  <div class="Content">
    <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-if="form.date.length"
            v-model="form.date"
            type="daterange"
            :disabled-date="time => disabledDate(time)"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="应用">
          <el-select
            v-model="form.app"
            placeholder="请选择时段"
            @change="change"
          >
            <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
            filterable
            multiple
            collapse-tags
            clearable
            v-model="form.version"
            placeholder="请选择版本"
            @change="changeversion"
          >
            <el-option
              v-for="item in version"
              :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-button
            size="small"
            style="margin-left: 0.5em"
            type="primary"
            @click="onExport"
          >
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <br />
    <el-card class="box-card">
      <el-table
        :data="table || []"
        style="width: 100%"
        :header-cell-style="{
          backgroundColor: '#f4f5f7',
          color: '#606266',
        }"
      >
        <el-table-column
          show-overflow-tooltip
          label="应用名称"
          header-align="center"
          align="center"
        >
          <template #default>
            <span>{{ lastParams.app || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="日期"
          header-align="center"
          align="center"
          prop="dtf"
        >
        </el-table-column>
        <el-table-column
          label="累计访问次数"
          header-align="center"
          align="center"
          prop="pv"
        >
          <template #default="scope">
            <countTo
              :startVal="scope.row.pv || 0"
              :endVal="scope.row.pv || 0"
              :duration="100"
            ></countTo>
          </template>
        </el-table-column>
        <el-table-column
          label="累计访问用户数"
          header-align="center"
          align="center"
          prop="uv"
        >
          <template #default="scope">
            <countTo
              :startVal="scope.row.uv || 0"
              :endVal="scope.row.uv || 0"
              :duration="100"
            ></countTo>
          </template>
        </el-table-column>
        <el-table-column
          label="日访问最高稿件"
          header-align="center"
          align="center"
        >
          <el-table-column
            prop="title"
            header-align="center"
            align="center"
            show-overflow-tooltip
            label="标题"
          />
          <el-table-column
            label="浏览量"
            header-align="center"
            align="center"
            prop="cpv"
          >
            <template #default="scope">
              <countTo
                :startVal="scope.row.cpv || 0"
                :endVal="scope.row.cpv || 0"
                :duration="100"
              ></countTo>
            </template>
          </el-table-column>
          <el-table-column
            label="阅读量"
            header-align="center"
            align="center"
            prop="cuser"
          >
            <template #default="scope">
              <countTo
                :startVal="scope.row.cuser || 0"
                :endVal="scope.row.cuser || 0"
                :duration="100"
              ></countTo>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
// @ is an alias to /src
import { getRule, getAppList, getSearchData } from '@/api/index';
import { getContentDayList } from '@/api/newMdeiaApi';

import countTo from '@/components/counto/vue-countTo.vue';
import { defaultAppNameFunc } from '@/utils/tool.js';

import config from '@/config/index';
export default {
  name: 'Version',
  data() {
    return {
      lastParams: {},
      table: [],
      numType: 'newUser',
      form: {
        app: '',
        version: [],
        date: [],
      },
      cycle: [],
      showList: [],
      version: [],
    };
  },
  async mounted() {
    const { source, appV, appli, appVLi } = await this.getAppListFunc();
    const keys = {
      value: 'mname',
      label: 'mname',
    };
    this.cycle = this.verifyList(appli, source, keys, false);
    this.version = this.verifyList(appVLi, appV, keys, true);
    this.form = {
      //   app: (this.cycle[0] || { value: "" }).value,
      app: defaultAppNameFunc(this.cycle),
      version: [(this.version[0] || { value: '' }).value],
      date: [new Date(Date.now() - 604800000), new Date(Date.now() - 86400000)],
    };
    this.onSubmit();
  },
  computed: {},
  methods: {
    verifyList(list, verify, obj, more) {
      if (!obj) return;
      let li = list || [];
      const out = [];
      more && out.push({ value: -1, label: '不限' });
      for (let i = 0; i < li.length; i++) {
        const v = li[i];
        if (verify.length !== 0 && !verify[v.mcode]) continue;
        out.push({
          value: v[obj.value],
          label: v[obj.label],
        });
      }
      return out;
    },
    onSubmit() {
      this.lastParams = {
        app: this.form.app,
        start: this.FormData(this.form.date[0]),
        end: this.FormData(this.form.date[1]),
        version: this.form.version == -1 ? undefined : this.form.version,
      };
      getContentDayList(this.lastParams).then(r => {
        this.table = r || {};
      });
    },
    async getAppListFunc() {
      const { r, li, appVersion } = await this.getAppListOri();
      let source = { length: 0 },
        appli = [];
      let appV = { length: 0 },
        appVLi = [];
      let prvList =
        (r.output && r.output.data && r.output.data.prvRolectrl) || [];
      for (let i = 0; i < prvList.length; i++) {
        const v = prvList[i];
        if (v.controlid == 'RMT_SOURCE')
          (source[v.detid] = true), (source.length = source.length + 1);
        if (v.controlid == 'APP_VERSION')
          (appV[v.detid] = true), (appV.length = appV.length + 1);
      }
      if (li.status === '0') appli = li.output.data || [];
      if (appVersion.length) appVLi = appVersion || [];
      return {
        source,
        appV,
        appli,
        appVLi,
      };
    },
    async getAppListOri() {
      const roleid = JSON.parse(
        window.parent.localStorage.userinfo || '{}'
      ).roleid;
      const r = await getRule({
        db: 'authplat',
        exportMark: '0',
        menuid: 399,
        roleid,
      });
      //   应用列表

      const li = await getAppList({
        exportMark: '0',
        gcode: 'SOURCE',
        pageid: 1,
        pagesize: 1000,
      });
      const cycle = li.output ? li.output.data || [] : [];
      //   应用版本列表
      const appVersion = await getSearchData({
        gcode: 'APP_VERSION',
        source: defaultAppNameFunc(cycle, 'mname'),
      });
      return { r, li, appVersion };
    },
    disabledDate(time) {
      const first = new Date('2021-06-21 00:00:00');
      return (
        time.getTime() > Date.now() - 86400000 ||
        time.getTime() < first.getTime()
      );
    },
    FormData(date) {
      const d = new Date(date || Date.now() - 86400000);
      const year = d.getFullYear();
      const month =
        d.getMonth() <= 8 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
      const day = d.getDate() <= 9 ? '0' + d.getDate() : d.getDate();
      return [year, month, day].join('-');
    },
    change() {
      const roleid = JSON.parse(
        window.parent.localStorage.userinfo || '{}'
      ).roleid;
      const appV = {
        length: 0,
      };
      getRule({
        db: 'authplat',
        exportMark: '0',
        menuid: 399,
        roleid,
      }).then(rule => {
        let prvList =
          (rule.output && rule.output.data && rule.output.data.prvRolectrl) ||
          [];
        for (let i = 0; i < prvList.length; i++) {
          const v = prvList[i];
          if (v.controlid == 'APP_VERSION')
            (appV[v.detid] = true), (appV.length = appV.length + 1);
        }
        getSearchData({
          gcode: 'APP_VERSION',
          source: this.form.app,
        }).then(r => {
          let version = [
            {
              label: '不限',
              value: -1,
            },
          ];
          r.map(v => {
            if ((appV.length && appV[v.mcode]) || appV.length === 0)
              version.push({
                value: v.mname,
                label: v.mname,
              });
          });
          this.version = version;
          this.form = {
            ...this.form,
            version: [-1],
          };
        });
      });
    },
    changeversion(v) {
      if (!v.length) return (this.form.version = [-1]);
      const last = v[v.length - 1];
      if (last == -1) return (this.form.version = [-1]);
      let ver = [];
      for (let i = 0; i < v.length; i++) {
        const element = v[i];
        if (element == -1) continue;
        ver.push(element);
      }
      this.form.version = ver;
    },
    onExport() {
      const S = this.form.date[0]
        ? this.FormData(this.form.date[0])
        : undefined;
      const E = this.form.date[1]
        ? this.FormData(this.form.date[1])
        : undefined;
      const app = this.lastParams.app || this.form.app;
      const version =
        this.form.version == -1 ? undefined : this.form.version.join(',');
      let url =
        config.base.url2 +
        '/new-media/content/daily-export?start=' +
        S +
        '&end=' +
        E +
        '&app=' +
        app;
      version && (url += '&version=' + version);
      window.open(url);
    },
  },
  components: {
    countTo,
  },
};
</script>

<style>
.Content {
  margin: 10px 15px;
}
.libTitle {
  color: tomato;
  font-weight: 700;
  font-size: 14px;
}
.btn-next i,
.btn-prev i {
  margin: 0 auto;
}
.caret-wrapper .ascending {
  display: none;
}
</style>
