<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" class="card-box">
        <el-card>
          <div slot="header"><span>搜索信息</span></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="120px">
              <el-form-item label="活动开始时间" prop="startTime">
                <el-date-picker clearable
                  v-model="queryParams.startTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择活动开始时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="活动结束时间" prop="endTime">
                <el-date-picker clearable
                  v-model="queryParams.endTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择活动结束时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8" class="card-box">
        <el-card>
          <div slot="header"><span>活动统计</span></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="activities" style="height: 500px" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="16" class="card-box">
        <el-card>
          <div slot="header">
            <span>人数统计</span>
          </div>
          <el-row :gutter="24">
            <el-col :span="4" v-for="(item, index) in userData" :key="index"><div style="margin-top: 8px;">{{ item.name }}: {{ item.value }}人</div></el-col>
          </el-row>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="usedmemory" style="height: 440px" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { activityCountByType, userCountByType, userCountByTag, userTotalCountByTag, userTimesByTag, userTotalTimesByTag } from "@/api/stat/index";
import echarts from "echarts";

export default {
  name: "Cache",
  dicts: ['user_tags'],
  data() {
    return {
      activities: null,
      // cache信息
      cache: [],
      queryParams: {},
      dateRange: [],
      userData: [],
      titleList: [
        { name: '文化娱乐', value: 'whyl' },
        { name: '志愿服务', value: 'zyfu' },
        { name: '教育宣讲', value: 'jyxj' },
        { name: '治理防范', value: 'zlff' },
        { name: '环境卫生', value: 'hjws' },
        { name: '关爱服务', value: 'gafw' }
      ]
    }
  },
  mounted() {
    this.handleQuery();
    // this.openLoading();
  },
  methods: {
    // 搜索
    handleQuery() {
      this.$modal.loading("正在加载活动统计数据，请稍候！");
      this.getActivity();
      this.getUser();
      this.getUserList();
    },
    // 重置
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 人数信息 */
    async getUserList() {
      const typeUser = await userCountByTag(this.queryParams);
      // 用户群体按字典排序
      typeUser.data.sort((a, b) =>
        (this.dict.type.user_tags.find(tag => tag.label === a.name)?.raw.dictSort ?? Infinity) -
        (this.dict.type.user_tags.find(tag => tag.label === b.name)?.raw.dictSort ?? Infinity)
      );
      const allUser = await userTotalTimesByTag(this.queryParams);
      const allData = [{ name: '总人次', value: allUser.data }];
      this.userData = [ ...allData, ...typeUser?.data ];
      this.$modal.closeLoading();
    },
    async getActivity() {
      const res = await activityCountByType(this.queryParams);
      const data = res?.data.map(e => {
        const type = this.titleList.find(j => j.value == e.name);
        if (type) e.name = type.name;
        return e;
      });;
      const myChart = echarts.init(this.$refs.activities, 'macarons');
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: "{b}: {c} ({d}%)",
        },
        series: [
          {
            type: "pie",
            roseType: "radius",
            radius: [15, 95],
            center: ["50%", "38%"],
            data,
            animationEasing: "cubicInOut",
            animationDuration: 1000,
          }
        ]
      };
      myChart.setOption(option);
    },
    async getUser() {
      const res = await userCountByType(this.queryParams);
      const data = res?.data.map(e => {
        const type = this.titleList.find(j => j.value == e.name);
        if (type) e.name = type.name;
        return e;
      });
      const myChart = echarts.init(this.$refs.usedmemory);
      const option = {
        xAxis: {
          type: 'category',
          data: (() => {
            let list = [];
              data.map((item) => {
                  list.push(item.name);
              });
              return list;
          })(),
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            },
            label: {
              show: true,
              position: 'top'
            },
            itemStyle: {
              normal: {
                color: function(params) {
                    return '#3f48cc'
                }
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    }
  }
};
</script>