
<template>
  <div>
    <div class="dashboard-container">
      <el-row :gutter="24">
        <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">
          <vab-query-form style="float: right;">
            <vab-query-form-right-panel :span="24">
              <el-form :inline="true" :model="queryForm" @submit.prevent>
                <el-form-item class="ml10">
                  <ms-date-range-picker
                    v-model="order_time_range"
                    @update:modelValue="order_time_range = $event"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    icon="el-icon-search"
                    type="primary"
                    @click="fetchData"
                  >
                    {{ t('查询') }}
                  </el-button>
                </el-form-item>
              </el-form>
            </vab-query-form-right-panel>
          </vab-query-form>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <top-num
            background="white"
            :bottom-text="t('累计用户')"
            :count-config="userNumConfig"
            icon="user-3-line"
            :title="t('累计用户')"
            :unit-text="t('个')"
          />
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <top-num
            background="white"
            :bottom-text="t('访客数')"
            :count-config="visitsUserConfig"
            icon="user-4-line"
            :title="t('访客数')"
            :unit-text="t('人')"
          />
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <top-num
            background="white"
            :bottom-text="t('新增用户数')"
            :count-config="regUserNumConfig"
            icon="user-add-line"
            :title="t('新增用户数')"
            :unit-text="t('个')"
          />
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <top-num
            background="white"
            :bottom-text="t('浏览量')"
            :count-config="accessNumConfig"
            icon="user-search-line"
            :title="t('浏览量')"
            :unit-text="t('PV')"
          />
        </el-col>
      </el-row>

    </div>

    <el-row :gutter="30">
      <el-col :span="12">
        <el-card v-loading="loading" class="box-card">
          <div slot="header">
            {{ __('操作系统') }}
          </div>
          <ms-chart
            :init-options="initOptions"
            :option="osOpt"
            style="width: 100%"
            theme="vab-echarts-theme"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card v-loading="loading" class="box-card">
          <div slot="header">
            <span style="font-size: 16px">{{ __('浏览器') }}</span>
          </div>
          <ms-chart
            :init-options="initOptions"
            :option="browserOpt"
            style="width: 100%"
            theme="vab-echarts-theme"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="30">
      <el-col :span="12">
        <el-card  v-loading="loading" class="box-card">
          <div slot="header">
            {{ __('访问省份') }}
          </div>
          <ms-chart
            :init-options="initOptions"
            :option="provinceOpt"
            style="width: 100%"
            theme="vab-echarts-theme"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card v-loading="loading" class="box-card">
          <div slot="header">
            {{ __('访问设备') }}
          </div>
          <ms-chart
            :init-options="initOptions"
            :option="deviceOpt"
            style="width: 100%"
            theme="vab-echarts-theme"
          />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <el-col :span="24">
        <div class="grid-content bg-purple">
          <el-card v-loading="loading" class="box-card">
            <template #header>
              <vab-icon icon="account-box-line" />
              {{ __('用户统计') }}
              <el-radio-group
                v-model="userTime"
                class="radio-inline"
                size="small"
                style="float: right"
                @change="getAccessItemUserTimeLineFunEvt"
              >
                <el-radio-button
                  :label="7"
                >{{ t('7天') }}</el-radio-button>
                <el-radio-button
                  :label="30"
                >{{ t('30天') }}</el-radio-button>
                <el-radio-button
                  :label="90"
                >{{ t('3个月') }}</el-radio-button>
                <el-radio-button
                  :label="180"
                >{{ t('半年') }}</el-radio-button>
              </el-radio-group>
            </template>
            <ms-chart
              :init-options="initOptions"
              :option="accessUserTimeLineOption"
              style="width: 100%"
              theme="ms-echarts-theme"
            />
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>



<script>

import { translateTitle as t } from '@/utils/i18n'
import TopNum from '@/components/MsWidget/TopNum'
import MsDateRangePicker from '@/components/MsDateRangePicker'
import MsChart from '@/extra/VabChart'

import {
  getOrderCustomerNumTimeline,
} from '@/api/analytics/order';
import {
  getUserTimeLine,
  getUserNum,
  getUserNum as getRegUserNum,
} from '@/api/analytics/user';

import {
  getAccessVisitorTimeLine,
  getAccessVisitorNum,
  getAccessNum,
} from '@/api/analytics/access/history';

import moment from 'dayjs';
import { formatTimeLine, formatTimeLineRange } from '@/utils';


import { getCustomerDate } from '@/api/order/base'
import {
  getAccessOs,
  getAccessBrowser,
  getAccessCountry,
  getAccessDevice,
  getAccessProvince,
} from '@/api/analytics/access/history'

import axios from "axios";


export default {
  name: 'AnalyticsUser',
  components: { MsChart, TopNum, MsDateRangePicker },
  data() {
    return {
      userTime: 7,
      userNumConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      visitsUserConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      accessNumConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      regUserNumConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      form: {
        startVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 5000,
      },
      data: {
        order_num: 0,
        favorable_order_num: 0,
        user_reg_yestoday: [
          {
            num: 0,
          },
          {
            num: 0,
          },
        ],
        user_payment_yestoday: [
          {
            num: 0,
          },
          {
            num: 0,
          },
        ],
      },
      accessUserTimeLineOption: {
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['新增用户数', '访客数', '成交用户数'],
        },
        grid: {
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '新增用户数',
            type: 'line',
            data: [],
          },
          {
            name: '访客数',
            type: 'line',
            data: [],
          },
          {
            name: '成交用户数',
            type: 'line',
            data: [],
          },
        ],
      },
      columnLoading: false,
      polylineLoading: false,
      loading: false,
      initOptions: {
        renderer: 'svg',
      },
      height: this.$baseTableHeight(),
      itemList: [],
      listLoading: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: '',
      order_time_range: ['', ''],
      userList: [],
      queryForm: {
        product_name: '',
        product_id: '',
        product_number: '',
        user_id: '',
        stime: '',
        etime: '',
      },




      osOpt: {
        title: {
          text: this.__('操作系统'),
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'right',
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      },
      browserOpt: {
        title: {
          text: this.__('浏览器'),
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'right',
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      },
      countryOpt: {
        title: {
          text: this.__('访问国家'),
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'right',
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      },
      deviceOpt: {
        title: {
          text: this.__('访问设备'),
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'right',
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      },
      provinceOpt: {},
      customerOpt: {
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['提交订单的客户数'],
        },
        grid: {
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: this.__('提交订单的客户数'),
            type: 'line',
            data: [],
          },
        ],
      },
    };
  },
  methods: {
    t,
    async fetchData() {
      if (this.order_time_range.length > 0) {
        if (this.order_time_range[0]) {
          this.queryForm.stime = this.order_time_range[0].getTime();
        }
        if (this.order_time_range[1]) {
          this.queryForm.etime = this.order_time_range[1].getTime();
        }
      } else {
        this.queryForm.stime = null;
        this.queryForm.etime = null;
      }
      const params = this.queryForm;

      //所有用户
      this.getUserNumFun({stime:null, etime:null});

      this.getAccessVisitorNumFun(params);
      this.getAccessNumFun(params);
      this.getRegUserNumFun(params);
      let days = 30;
      if (this.queryForm.stime && this.queryForm.etime) {
        this.userTime = '';
        days = (this.queryForm.etime - this.queryForm.stime) / (1000 * 3600 * 24);
        const timeRange = {
          days,
          stime: this.queryForm.stime,
          etime: this.queryForm.etime,
        };
        this.getAccessItemUserTimeLineFunRange(timeRange);
      } else {
        this.getAccessItemUserTimeLineFun(days);
      }



      await this.getAccessOs()
      await this.getAccessBrowser()
      await this.getAccessCountry()
      await this.getAccessDevice()
      await this.getAccessProvince()
      //await this.getCustomerDate(7)
    },
    async getAccessItemUserTimeLineFunRange(timeRange) {
      this.loading = true;
      const params = { stime: timeRange.stime, etime: timeRange.etime };
      const { data } = await getUserTimeLine(params);
      formatTimeLineRange(data, timeRange.days, timeRange.etime);
      const { data: visitorNum } = await getAccessVisitorTimeLine(params);
      formatTimeLineRange(visitorNum, timeRange.days, timeRange.etime);
      const { data: customerNum } = await getOrderCustomerNumTimeline(params);
      formatTimeLineRange(customerNum, timeRange.days, timeRange.etime);
      this.accessUserTimeLineOption.xAxis.data = data.map((item) => item.time);
      this.accessUserTimeLineOption.series[0].data = data.map((item) => item.num);
      this.accessUserTimeLineOption.series[1].data = visitorNum.map((item) => item.num);
      this.accessUserTimeLineOption.series[2].data = customerNum.map((item) => item.num);
      this.loading = false;
    },
    async getUserNumFun(params) {
      const { data } = await getUserNum(params);
      data.today = data.current;
      data.yestoday = data.pre;
      this.userNumConfig = Object.assign(this.userNumConfig, data);
    },
    async getAccessVisitorNumFun(params) {
      const { data } = await getAccessVisitorNum(params);
      data.today = data.current;
      data.yestoday = data.pre;
      this.visitsUserConfig = Object.assign(this.visitsUserConfig, data);
    },
    async getAccessNumFun(params) {
      const { data } = await getAccessNum(params);
      data.today = data.current;
      data.yestoday = data.pre;
      this.accessNumConfig = Object.assign(this.accessNumConfig, data);
    },
    async getRegUserNumFun(params) {
      const { data } = await getRegUserNum(params);
      data.today = data.current;
      data.yestoday = data.pre;
      this.regUserNumConfig = Object.assign(this.regUserNumConfig, data);
    },
    async getAccessItemUserTimeLineFunEvt() {
      this.getAccessItemUserTimeLineFun(parseInt(this.userTime))
    },
    async getAccessItemUserTimeLineFun(days) {
      this.loading = true;
      const start = new Date(moment(moment().subtract(days - 1, 'days').format('YYYY-MM-DD')));
      const end = new Date();
      const params = { stime: start.getTime(), etime: end.getTime() };
      const { data } = await getUserTimeLine(params);
      formatTimeLine(data, days);
      const { data: visitorNum } = await getAccessVisitorTimeLine(params);
      formatTimeLine(visitorNum, days);
      const { data: customerNum } = await getOrderCustomerNumTimeline(params);
      formatTimeLine(customerNum, days);
      this.accessUserTimeLineOption.xAxis.data = data.map((item) => item.time);
      this.accessUserTimeLineOption.series[0].data = data.map((item) => item.num);
      this.accessUserTimeLineOption.series[1].data = visitorNum.map((item) => item.num);
      this.accessUserTimeLineOption.series[2].data = customerNum.map((item) => item.num);
      this.loading = false;
    },




    async getAccessOs() {
      const { data } = await getAccessOs()
      this.osOpt.series[0].data = data
    },
    async getAccessBrowser() {
      const { data } = await getAccessBrowser()
      this.browserOpt.series[0].data = data
    },
    async getAccessCountry() {
      const { data } = await getAccessCountry()
      this.countryOpt.series[0].data = data
    },
    async getAccessDevice() {
      const { data } = await getAccessDevice()
      this.deviceOpt.series[0].data = data
    },
    async getAccessProvince() {
      let { data } = await getAccessProvince()
      console.info(JSON.stringify(data))

      // let names = data.map((item) => item.name)
      // this.provinceOpt.xAxis[0].data = names
      // let values = data.map((item) => item.value)
      // this.provinceOpt.series[0].data = values
      console.info(JSON.stringify(data))

      const china = await axios({
        url: 'json/china.json',
        method: 'get',
      })
      MsChart.registerMap('china', china.data)

      this.provinceOpt = {
        title: {
          text: '访问来源',
          subtext: '',
        },
        tooltip: {
          trigger: 'item',
        },
        dataRange: {
          min: 0,
          max: 55000,
          text: ['高', '低'],
          splitNumber: 0,
        },
        series: [
          {
            name: '访问来源',
            type: 'map',
            roam: false,
            map: 'china',
            selectedMode: 'multiple',
            emphasis: {
              label: {
                show: true,
              },
            },
            data: data,
          },
        ],
      }
    },
    async getCustomerDate(days) {
      const { data } = await getCustomerDate({ days: days })
      let date = data.map((item) => item.curr_date)
      this.customerOpt.xAxis.data = date
      let nums = data.map((item) => item.num)
      this.customerOpt.series[0].data = nums
    },
  },
  created() {
    this.fetchData();
  },
};
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 0 !important;
  background: $base-color-background !important;

  .el-card {
    height: 300px;

    [class*='-echart'] {
      width: 100%;
      height: 200px;
    }
  }
}

.xe-icon {
  width: 80px;
  padding: 10px;

  .i-wh-workbench {
    display: block;
    color: #fff;
    text-align: center;
    font-size: 25px;
    line-height: 50px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-clip: padding-box;
  }
}

.xe-info {
}

.xe-num {
  display: block;
  font-size: 20px;
  font-weight: 400;
  color: #3e3f3f;
  text-align: left;
}

.xe-label {
  text-align: left;
  display: block;
  font-style: normal;
  font-size: 10px;
  text-transform: uppercase;
  color: #979898;
}

.xe-todo {
  text-align: right;
  display: block;
  font-style: normal;
  font-size: 10px;
  text-transform: uppercase;
  color: #979898;
  margin-top: 5px;
}

.el-row {
  margin-bottom: 0px;
}

.ml10 {
  margin-left: 10px;
}
</style>
