<template>
  <div class="Region">
    <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 label="渠道">
          <el-select
            filterable
            multiple
            collapse-tags
            clearable
            v-model="form.channel"
            @change="changechannel"
            placeholder="请选择渠道"
          >
            <el-option
              v-for="item in channel"
              :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
            collapse-tags
            clearable
            v-model="form.client"
            placeholder="请选择来源"
          >
            <el-option
              v-for="item in client"
              :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 type="primary" @click="onExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <br />
    <el-card class="box-card">
      <el-tabs
        v-model="form.cityType"
        class="demo-tabs"
        @tab-click="changeTabs"
      >
        <el-tab-pane name="1" label="地市"></el-tab-pane>
        <el-tab-pane name="2" label="省"></el-tab-pane>
      </el-tabs>
      <el-row>
        <el-col :span="6">
          <div
            style="
              padding: 10px 0;
              text-align: center;
              color: rgb(14, 14, 14);
              font-size: 20px;
            "
          >
            活跃用户排行榜
          </div>
          <el-table
            height="500"
            v-if="table.length"
            :data="table"
            style="width: 100%"
            :header-cell-style="{
              backgroundColor: '#f4f5f7',
              color: '#606266',
            }"
          >
            <el-table-column
              header-align="center"
              align="center"
              prop="dt"
              label="地名"
            >
              <template #default="scope">
                {{
                  lastParams.cityType === '1'
                    ? scope.row.city
                    : scope.row.province
                }}
              </template>
            </el-table-column>
            <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
              header-align="center"
              align="center"
              prop="userSum"
              label="活跃用户数"
            >
              <template #default="scope">
                <countTo
                  :startVal="scope.row.userSum"
                  :endVal="scope.row.userSum"
                  :duration="100"
                ></countTo>
              </template>
            </el-table-column>
          </el-table>
          <br />
        </el-col>
        <el-col :span="18">
          <div style="position: relative">
            <div style="position: absolute; top: 10px; left: 10px">
              <div v-if="item.name" class="item">区域名称：{{ item.name }}</div>
              <div v-if="item.name" class="item">
                活跃用户数：
                <countTo
                  :startVal="item.userSum"
                  :endVal="item.userSum"
                  :duration="100"
                ></countTo>
              </div>
              <div v-if="item.name" class="item">
                新增用户数：
                <countTo
                  :startVal="item.newUser"
                  :endVal="item.newUser"
                  :duration="100"
                ></countTo>
              </div>
              <div v-if="item.name" class="item">
                活跃用户占比：{{ item.distribution }}
              </div>
            </div>
            <el-select
              v-model="dateType"
              @change="createImage"
              style="position: absolute; right: 0; top: 0; z-index: 1"
              size="small"
            >
              <el-option label="用户数" value="userSum" />
              <el-option label="新增用户数" value="newUser" />
            </el-select>
            <div ref="regionChart"></div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import china from '../../assets/map/100000_full.json';
import shanxi from '../../assets/map/610000_shaanxi.json';
import countTo from '@/components/counto/vue-countTo.vue';
import { defaultAppNameFunc } from '@/utils/tool.js';
// @ is an alias to /src
import {
  getRule,
  getAppList,
  getRegionChart,
  getSearchData,
  getMaplever,
} from '@/api/index';

import * as echarts from 'echarts';
let data = {};
// import config from "@/config/index";
let chart = undefined;
export default {
  name: 'region',
  data() {
    return {
      lastParams: {},
      table: [],
      form: {
        app: '',
        version: [],
        channel: [],
        date: [],
        region: '',
        cityType: '1',
        client: '',
      },
      dateType: 'userSum',
      cycle: [],
      item: {},
      version: [],
      channel: [],
      client: [],
    };
  },
  async mounted() {
    if (echarts) {
      echarts.registerMap('China', china);
      echarts.registerMap('ShanXi', shanxi);
    }
    if (chart && chart.dispose) chart.dispose();
    const { source, appV, appC, appli, appCLi, appVLi, clentli, clentV } =
      await this.getAppListFunc();
    const keys = {
      value: 'mname',
      label: 'mname',
    };
    const clentliList = clentli.find(r => r.mdefault) || false;
    let client = clentliList ? clentliList.mcode.toString() : -1;
    this.cycle = this.verifyList(appli, source, keys, false);
    this.channel = this.verifyList(appCLi, appC, keys, true);
    this.version = this.verifyList(appVLi, appV, keys, true);
    this.client = this.verifyList(
      clentli,
      clentV,
      {
        value: 'mcode',
        label: 'mname',
      },
      true
    );
    this.form = {
      //   app: (this.cycle[0] || { value: "" }).value,
      app: defaultAppNameFunc(this.cycle),
      version: [(this.version[0] || { value: '' }).value],
      channel: [(this.channel[0] || { value: '' }).value],
      date: [new Date(Date.now() - 604800000), new Date(Date.now() - 86400000)],
      cityType: '1',
      client,
    };
    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;
    },
    changeTabs() {
      this.onSubmit();
    },
    onSubmit() {
      this.lastParams = {
        app: this.form.app,
        start: this.FormData(this.form.date[0]),
        end: this.FormData(this.form.date[1]),
        manufacturer: this.form.channel == -1 ? undefined : this.form.channel,
        version: this.form.version == -1 ? undefined : this.form.version,
        cityType: this.form.cityType,
        lib: this.form.client == -1 ? undefined : this.form.client,
      };
      getMaplever(this.lastParams)
        .then(r => {
          if (!this.$refs.regionChart) return;
          let list = r.list || [];
          chart && chart.clear();
          this.lastParams.cityType = this.form.cityType;
          this.table = list;
          for (let i = 0; i < list.length; i++) {
            const v = list[i];
            if (v.city === '西安市' || v.province === '陕西省') {
              this.item = {
                name: v.city === '西安市' ? '西安市' : '陕西省',
                value: v.userSum,
                distribution: (v.distribution * 100).toFixed(2) - 0 + '%',
                userSum: v.userSum,
                newUser: v.newUser
              };
              break;
            }
          }
          data = r || {};
          this.createImage();
          chart && chart.hideLoading();
        })
        .catch(() => {
          chart && chart.clear() && chart.hideLoading();
        });
    },
    createImage() {
      const { list, range } = data;
      if (!chart) {
        chart = echarts.init(this.$refs.regionChart);
        window.onresize = chart.resize;
      }
      chart.clear();
      chart.resize({
        height: this.$refs.regionChart.offsetWidth * 1,
      });
      //   let min = list[list.length - 1].userSum;
      const p = {
        tooltip: {
          confine: true,
          trigger: 'item',
          formatter: function (e) {
            if (e.value) return e.name + '<br />' + (e.value || '');
            return '';
          },
        },
        visualMap: {
          type: 'piecewise',
          pieces: range,
        },
        series: [
          {
            type: 'map',
            map: this.lastParams.cityType === '1' ? 'ShanXi' : 'China',
            label: {
              show: true,
            },
            data: list.map(v => {
              return {
                name: this.lastParams.cityType === '1' ? v.city : v.province,
                value: v[this.dateType],
                distribution: (v.distribution * 100).toFixed(2) - 0 + '%',
                userSum: v.userSum,
                newUser: v.newUser,
              };
            }),
          },
        ],
      };
      chart.setOption(p);
      const _this = this;
      chart.on('click', function (params) {
        _this.item = params.data || {};
      });
    },
    async getAppListFunc() {
      const { r, li, appVersion, channel, clientList } =
        await this.getAppListOri();
      let source = { length: 0 },
        appli = [];
      let appV = { length: 0 },
        appVLi = [];
      let appC = { length: 0 },
        appCLi = [];
      let clentV = { length: 0 },
        clentli = [];
      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 (v.controlid == 'CHANNEL')
          (appC[v.detid] = true), (appC.length = appC.length + 1);
      }
      if (li.status === '0') appli = li.output.data || [];
      if (appVersion.length) appVLi = appVersion || [];
      if (channel.length) appCLi = channel || [];
      if (clientList.length) clentli = clientList || [];
      return {
        source,
        appV,
        appC,
        appli,
        clentV,
        appVLi,
        appCLi,
        clentli,
      };
    },
    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 clientList = await getSearchData({
        gcode: 'CLIENT_TYPE',
        source: defaultAppNameFunc(cycle, 'mname'),
      });
      //   应用版本列表
      const appVersion = await getSearchData({
        gcode: 'APP_VERSION',
        source: defaultAppNameFunc(cycle, 'mname'),
      });
      //   应用渠道列表
      const channel = await getSearchData({
        gcode: 'CHANNEL',
        source: defaultAppNameFunc(cycle, 'mname'),
      });
      return { r, li, appVersion, channel, clientList };
    },
    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('-');
    },
    timeFormat(t) {
      const Time = t || 0;
      const mH = Time % 3600;
      let hour = (Time - mH) / 3600;
      let min = (mH - (mH % 60)) / 60;
      let son = Number(mH % 60).toFixed(0);
      hour = hour <= 9 ? '0' + hour : hour;
      min = min <= 9 ? '0' + min : min;
      son = son <= 9 ? '0' + son : son;
      let out = [];
      if (hour * 1 > 0) out.push(hour);
      out.push(...[min, son]);
      return out.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.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;
    },
    changechannel(v) {
      if (!v.length) return (this.form.channel = [-1]);
      const last = v[v.length - 1];
      if (last == -1) return (this.form.channel = [-1]);
      let ver = [];
      for (let i = 0; i < v.length; i++) {
        const element = v[i];
        if (element == -1) continue;
        ver.push(element);
      }
      this.form.channel = ver;
    },
    onExport() {
      const S = this.lastParams.start;
      const E = this.lastParams.end;
      getRegionChart(this.lastParams).then(r => {
        // 生成数据
        let strcsv =
          'data:text/csv;charset=utf-8,\uFEFF应用名称,省份,地市,活跃用户数\r\n';
        (r || []).map(v => {
          strcsv += [
            this.lastParams.app,
            v.province,
            v.city,
            v[this.dateType],
            '\r\n',
          ].join(',');
        });
        // 导出
        let link = document.createElement('a');
        link.id = 'download-csv';
        link.setAttribute('href', encodeURI(strcsv));
        link.setAttribute(
          'download',
          this.lastParams.app + '地域分析' + S + '_' + E + '.csv'
        );
        // document.body.appendChild(link);
        link.click();
      });
    }
  },
  components: {
    countTo,
  },
};
</script>

<style>
.Region {
  margin: 10px 15px;
}
.Region .has-seconds .el-time-spinner__wrapper:last-child {
  display: none;
}
.head {
  display: flex;
  font-weight: 500;
}
.head .head-item {
  flex: 1;
  text-align: center;
  font-size: 0.8em;
  border-top: 3px solid #fff;
  padding-top: 10px;
}
.head .value {
  margin: 15px 0;
  color: #396fff;
  font-size: 25px;
}
.ttable {
  position: absolute;
  z-index: 2;
  width: 25em;
}
.item {
  line-height: 1.8em;
}
</style>
