<template>
  <section class="DataDetail">
    <ai-detail>
      <template #content>
        <ai-tree-menu title="应报到党组织名单" @search="(v) => $refs.gridTree.filter(v)" searchPlaceholder="请输入党组织...">
          <ai-party-tree :instance="instance" :root="user.info.organizationId" @node-click="handleSelectGrid" :filter-node-method="handleTreeFilter" ref="gridTree"></ai-party-tree>
        </ai-tree-menu>

        <div class="echarts-content">
          <div class="mainPane">
            <!-- 近12个月党员活动参与情况统计 -->
            <el-row>
              <div class="cardPane">
                <ai-title title="近12个月党员活动参与情况统计" />
                <div id="numMonthsCountListChart" />
              </div>
            </el-row>

            <!-- 总体统计和学员报到类型比例统计 -->
            <div class="data-flex">
              <el-date-picker type="month" size="small" v-model="search.time" value-format="yyyy-MM" clearables @change="getList().then(() => getChartData())" />

              <!-- 总体统计 -->
              <el-row class="card" type="flex">
                <el-row class="totals" type="flex">
                  <div class="cards eventCountMap" v-for="v in eventCountMap" :key="v.key">
                    <b class="name-cards">{{ v.name }}</b>
                    <b class="count" v-if="v.v1 == 'NaN%'">0</b>
                    <b class="count" v-else>
                      <span v-if="v.name == '活动实际参与率'">
                        {{ v.v1.toString().replace(/(?=(?!\b)(\d{3})+$)/g, ',') }}
                        <span class="ren">%</span>
                      </span>
                      <span v-else>
                        {{ v.v1.toString().replace(/(?=(?!\b)(\d{3})+$)/g, ',') }}
                        <span class="ren">人</span>
                      </span>
                    </b>
                  </div>
                </el-row>

                <!-- 学员报到类型比例 -->
                <el-row class="ceharts">
                  <div>
                    <ai-title title="学员报到类型比例" />
                    <div id="typesofStudentReportsListChart" />
                  </div>
                </el-row>
              </el-row>
            </div>

            <!-- 党员活动记录列表 -->
            <div class="table">
              <div class="records"><span class="record">党员活动记录</span></div>
              <div class="template">
                <div class="left">
                  <el-date-picker placeholder="年/月" size="small" v-model="searchObj.time" value-format="yyyy-MM-01" type="month" clearables @change=";(page.current = 1), getInfoList().then(() => getChartData())" />

                  <ai-download :instance="instance" url="/app/apppartyreport/export-signup" :params="param" fileName="党员活动记录模板" />
                </div>

                <div class="right">
                  <el-input v-model="searchObj.name" size="small" placeholder="姓名" prefix-icon="iconfont iconSearch" clearable @change=";(page.current = 1), getInfoList()" />
                  <el-button class="el-button" type="primary" icon="el-icon-search" size="small" @click=";(page.current = 1), getInfoList()">查询</el-button>
                  <el-button class="el-button" icon="el-icon-refresh-right" @click="reset()">重置</el-button>
                </div>
              </div>
              <ai-table :tableData="tableData" :col-configs="colConfigs" :total="total" :current.sync="page.current" :size.sync="page.size" @getList="getInfoList" :dict="dict" @selection-change="(v) => (ids = v.map((e) => e.id))"> </ai-table>
            </div>
          </div>
        </div>
      </template>
    </ai-detail>
  </section>
</template>

<script>
import { mapState } from 'vuex'
import * as echarts from 'echarts'

export default {
  name: 'DataList',
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
  },
  computed: {
    ...mapState(['user']),

    chartOps() {
      if (!this.meta) return

      // 近12个月党员活动参与情况统计
      let MonthsCount = this.meta['趋势分析'].map((e) => [e.time, e.count, e.total, e.active]),
        //
        // 学员报到类型比例
        reportsType = Object.keys(this.meta['类别分析']).map((e) => [e, this.meta['类别分析'][e] || 0])

      return {
        // 近12个月党员活动参与情况统计
        numMonthsCountList: {
          tooltip: { trigger: 'axis' },
          legend: { icon: 'rect', itemWidth: 8, itemHeight: 8 },
          color: ['#EC4461', '#38A4F8', '#02A499'],
          grid: {
            left: 82,
            right: 40,
            bottom: 80,
            top: 56,
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            axisLine: { lineStyle: { color: '#D8DDE8' } },
            axisTick: {
              //坐标轴刻度相关设置
              show: true, //是否显示坐标轴刻度。
              // inside: false, //坐标轴刻度是否朝内，默认朝外。
              length: 7, //坐标轴刻度的长度。
            },
            axisLabel: { color: '#666', margin: 19 },
          },
          yAxis: {
            name: '',
            nameTextStyle: {
              color: '#666',
              borderColor: '#000',
              padding: [0, 60, 0, 0],
            },
            type: 'value',
            axisLine: { show: true, lineStyle: { color: '#333', type: 'solid' } },
            min: 0,
            minInterval: 1,
            axisLabel: { color: '#666', margin: 19, show: true },
            splitLine: { show: true, lineStyle: { color: '#D8DDE8', type: 'solid' } },
            axisTick: {
              show: true,
              length: 7,
            },
          },
          series: [
            { type: 'line', name: '本组织党员人数' },
            { type: 'line', name: '报名活动人数' },
            { type: 'line', name: '实际参与活动人数' },
          ],
          dataset: {
            source: MonthsCount,
          },
        },

        // 学员报到类型比例
        typesofStudentReportsList: {
          legend: {
            orient: 'vertical',
            left: 370,
            y: 'center',
            itemGap: 12,
            itemWidth: 18,
            itemHeight: 12,
            tooltip: { show: true },
            textStyle: {
              rich: {
                a: { color: '#666', width: 120, fontSize: 14, lineHeight: 22 },
                b: {
                  fontWeight: 'bold',
                  align: 'right',
                  color: '#333',
                  padding: [0, 50, 0, 0],
                  fontSize: 14,
                  width: 80,
                  lineHeight: 22,
                },
              },
            },
          },
          tooltip: {},
          color: ['#FDA94F', '#4F8AFA', '#EC4461'],
          series: {
            name: '学员报到类型比例',
            center: [160, '50%'],
            radius: [40, 80],
            type: 'pie',
            minShowLabelAngle: 1,
            label: {
              normal: {
                position: 'inner',
                formatter: '{d}%',
                color: '#fff',
              },
            },
            itemStyle: { borderColor: '#fff', borderWidth: 0 },
          },
          dataset: {
            source: reportsType,
          },
        },
      }
    },

    param() {
      let params = {}
      //导出搜索条件
      if (this.ids.length) {
        params = {
          ...params,
          time: this.searchObj.time,
        }
      } else {
        params = {
          ...params,
          time: this.searchObj.time,
          name: this.searchObj.name,
          partyOrgId: this.user.info.organizationId,
        }
      }
      return params
    },
  },
  data() {
    return {
      tableData: [],
      colConfigs: [
        { prop: 'name', label: '姓名', align: 'center' },
        {
          prop: 'sex',
          label: '性别',
          dict: 'sex',
          align: 'center',
        },
        { prop: 'partyOrg', label: '所属组织', align: 'center' },
        { prop: 'signupCount', label: '报名次数', align: 'center' },
        { prop: 'partakeCount', label: '参与次数', align: 'center' },
      ],
      page: {
        size: 10,
        current: 1,
      },
      total: 0,
      searchObj: {
        name: '',
        time: '',
      },
      search: {
        time: '',
      },
      partyId: '', // 党组织id
      treeData: [],
      meta: {},
      charts: {
        numMonthsCountList: null, // 近12个月党员活动参与情况统计
        typesofStudentReportsList: null, // 学员报到类型比例
      },
      ids: [],
      eventCountMap: [
        { name: '本组织党员人数', v1: 0 },
        { name: '本月报名活动人数', v1: 0 },
        { name: '实际参与活动人数', v1: 0 },
        { name: '活动实际参与率', v1: 0 },
      ],
    }
  },
  methods: {
    getList() {
      let partyOrgId = this.user.info.organizationId
      if (this.partyId) {
        partyOrgId = this.partyId
      }
      return this.instance
        .post('/app/apppartyreport/statistic', null, {
          params: {
            partyOrgId,
            time: this.search.time + '-01',
          },
        })
        .then((res) => {
          if (res?.data) {
            this.meta = res.data

            this.eventCountMap[0].v1 = this.meta['总体分析'].count.toString().replace(/(?=(?!\b)(\d{3})+$)/g, ',')
            this.eventCountMap[1].v1 = this.meta['总体分析'].total.toString().replace(/(?=(?!\b)(\d{3})+$)/g, ',')
            this.eventCountMap[2].v1 = this.meta['总体分析'].active.toString().replace(/(?=(?!\b)(\d{3})+$)/g, ',')

            if (this.meta['总体分析'].active > 0) {
              this.eventCountMap[3].v1 = (this.meta['总体分析'].active / this.meta['总体分析'].total).toFixed(2) * 100
            } else {
              this.eventCountMap[3].v1 = 0
            }

            window.console.log('100000001001011141000'.toString().replace(/(?=(?!\b)(\d{3})+$)/g, ','))
          }
        })
    },

    getInfoList() {
      let partyOrgId = this.user.info.organizationId
      if (this.partyId) {
        partyOrgId = this.partyId
      }
      this.instance
        .post(`/app/apppartyreport/list-signup`, null, {
          params: {
            ...this.page,
            name: this.searchObj.name,
            time: this.searchObj.time,
            partyOrgId,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.tableData = res.data.records
            this.total = res.data.total
          }
        })
    },

    handleTreeFilter(v, data) {
      return data?.name.indexOf(v) > -1
    },

    handleSelectGrid(data) {
      this.partyId = data?.id
      this.getList().then(() => this.getChartData())
      this.getInfoList()
    },

    initEcharts() {
      Object.keys(this.charts).map((id) => {
        let ref = document.getElementById(id + 'Chart')
        if (ref) this.charts[id] = echarts.init(ref)
      })
    },

    getChartData() {
      Object.keys(this.charts).map((e) => {
        this.charts[e]?.setOption(this.chartOps?.[e])
      })
    },

    // 重置
    reset() {
      this.searchObj.name = ''
      this.getInfoList()
    },
  },
  created() {
    var date = new Date()
    var year = date.getFullYear()
    var mon = date.getMonth() + 1
    var month = mon < 10 ? '0' + mon : mon
    this.searchObj.time = year + '-' + month + '-01'
    this.search.time = year + '-' + month

    this.handleSelectGrid(this.user.info.organizationId)

    this.dict.load('sex').then(() => {})

    this.getInfoList()
  },
  mounted() {
    this.initEcharts()
  },
}
</script>

<style lang="scss" scoped>
.DataDetail {
  height: 100%;
  font-size: 14px;
  .ai-detail {
    ::v-deep .ai-detail__content {
      .ai-detail__content--wrapper {
        min-width: 100%;
        display: flex;
        .AiTreeMenu {
          width: 16%;
        }
        .echarts-content {
          width: 83%;
          padding: 0 10px 0 0;
          margin-left: 10px;
          .mainPane {
            .el-row {
              width: 100%;
              gap: 16px;
              height: auto;
              .cardPane {
                flex: 1;
                padding: 0 10px 10px 10px;
                background: #ffffff;
                box-shadow: 0 0 4px 0 rgba(20, 16, 16, 0.05);
                border-radius: 4px;
              }
            }

            .data-flex {
              margin-top: 15px;
              padding: 10px;
              background-color: #fff;
              .card {
                margin-top: 20px;
                .totals {
                  width: 50%;
                  flex-wrap: wrap;
                  .cards {
                    display: flex;
                    flex-direction: column;
                    padding: 15px 0 0 15px;
                    width: 45%;
                    background-color: #f9f9f9;
                    .name-cards {
                      font-size: 16px;
                    }
                    .count {
                      line-height: 4;
                      color: #2a6cfb;
                      font-size: 22px;
                      .ren {
                        color: #9f9fa0;
                        font-size: 12px;
                      }
                    }
                  }
                }
                .ceharts {
                  background-color: #f9f9f9;
                  width: 50%;
                  padding: 5px 0 0 15px;
                }
              }
            }

            .table {
              padding: 0 10px 10px 10px;
              margin-top: 15px;
              background-color: #fff;
              .records {
                width: 140px;
                line-height: 40px;
                border-bottom: 2px solid #296bfb;
                .record {
                  margin-left: 25px;
                  color: #2c6dfb;
                  font-size: 14px;
                  font-weight: 800;
                }
              }
              .template {
                margin-top: 10px;
                display: flex;
                justify-content: space-between;
                .left {
                  display: flex;
                  .ai-download {
                    margin-left: 10px;
                  }
                }
                .right {
                  display: flex;
                  .el-input {
                    margin-right: 10px;
                  }
                }
              }
              .ai-table {
                margin-top: 10px;
              }
            }
          }
        }
      }
    }

    #numMonthsCountListChart {
      width: 100%;
      height: 290px;
    }

    #typesofStudentReportsListChart {
      width: 100%;
      height: 240px;
    }
  }
}
</style>
