<template>
  <ai-list class="AppActiveAnalysis">
    <template slot="title">
      <ai-title title="日活分析" isShowBottomBorder>
        <template #rightBtn>
          <ai-import
            :instance="instance"
            :dict="dict"
            type="wxuseruselog"
            name="成员日活记录"
            @success="getData">
            <el-button icon="iconfont iconImport" size="small">导入</el-button>
          </ai-import>
        </template>
      </ai-title>
    </template>
    <template #left>
      <div class="addressBook-left">
        <div class="addressBook-left__title">
          <h2 class="tab-active">组织架构</h2>
        </div>
        <div class="addressBook-left__list--title">
          <el-input
            size="mini"
            placeholder="请输入部门名称"
            v-model="unitName"
            clearable
            suffix-icon="iconfont iconSearch">
          </el-input>
        </div>
        <div class="addressBook-left__list--wrapper">
          <div class="addressBook-left__list">
            <el-tree
              :filter-node-method="filterNode"
              ref="tree"
              :props="defaultProps"
              node-key="id"
              :expand-on-click-node="false"
              :data="unitList"
              highlight-current
              :current-node-key="departmentId"
              :default-expanded-keys="defaultExpanded"
              :default-checked-keys="defaultChecked"
              @current-change="onTreeChange">
            </el-tree>
          </div>
        </div>
      </div>
    </template>


    <template slot="content">
      <ai-card title="当天数据统计">
        <template #right>
          <el-date-picker
            v-model="today"
            value-format="yyyy-MM-dd"
            :clearable="false"
            type="date"
            size="small"
            placeholder="请选择开始日期"
            @change="getDtInfo">
          </el-date-picker>
          <el-button type="text" @click="getActiveList(), isShowList = true">查看明细</el-button>
        </template>
        <template #content>
          <div class="chart1" style="width: 100%; height: 300px"></div>
        </template>
      </ai-card>
      <ai-card title="趋势数据统计">
        <template #content>
          <div class="chart2" style="width: 100%; height: 400px"></div>
        </template>
      </ai-card>
      <ai-card title="活跃统计">
        <template #right>
          <div class="right-search">
            <div>
              <span>数据统计日期范围：</span>
              <el-input-number v-model="x" size="small" @change="getActiveAnalysStatistics" :min="1" label="请输入"></el-input-number>
            </div>
            <div>
              <span>活跃状态天数指标：</span>
              <el-input-number v-model="y" size="small" @change="getActiveAnalysStatistics" :min="1" label="请输入"></el-input-number>
            </div>
          </div>
        </template>
        <template #content>
          <ai-table
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="search1.total"
            :current.sync="search1.current"
            :size.sync="search1.size"
            @getList="getActiveAnalysStatistics">
          </ai-table>
        </template>
      </ai-card>
      <ai-dialog
        :visible.sync="isShowList"
        width="1090px"
        customFooter
        title="成员活跃明细">
        <ai-search-bar bottomBorder>
          <template #right>
            <el-select @change="getActiveList" v-model="search.status" size="small" placeholder="请选择活跃状态">
              <el-option
                v-for="item in statusList"
                :key="item.dictName"
                :label="item.dictName"
                :value="item.dictName">
              </el-option>
            </el-select>
            <el-input
              v-model="search.name"
              size="small"
              placeholder="请输入成员姓名"
              clearable
              v-throttle="() => {search.current = 1, getActiveList()}"
              @clear="search.current = 1, search.name = '', getActiveList()"
              suffix-icon="iconfont iconSearch">
            </el-input>
          </template>
        </ai-search-bar>
        <ai-table
          :tableData="activeList"
          :col-configs="activeColConfigs"
          :total="search.total"
          style="margin-top: 16px;"
          :current.sync="search.current"
          :size.sync="search.size"
          @getList="getActiveList">
          <el-table-column slot="options" width="90px" fixed="right" label="操作" align="center">
            <template slot-scope="{ row }">
              <div class="table-options">
                <el-button type="text" @click="userSearch.wxUserId = row.wxUserId, isShowDetail = true, getUserActiveList()">详情</el-button>
              </div>
            </template>
          </el-table-column>
        </ai-table>
        <div class="dialog-footer" slot="footer">
          <el-button @click="isShowList = false">关闭</el-button>
        </div>
      </ai-dialog>
      <ai-dialog
        :visible.sync="isShowDetail"
        width="1090px"
        customFooter
        title="成员活跃明细">
        <ai-search-bar bottomBorder>
          <template #right>
            <el-select @change="getUserActiveList" v-model="userSearch.status" size="small" placeholder="请选择活跃状态">
              <el-option
                v-for="item in statusList"
                :key="item.dictName"
                :label="item.dictName"
                :value="item.dictName">
              </el-option>
            </el-select>
          </template>
        </ai-search-bar>
        <ai-table
          :tableData="userDetailList"
          :col-configs="activeColConfigs"
          :total="userSearch.total"
          style="margin-top: 16px;"
          :current.sync="userSearch.current"
          :size.sync="userSearch.size"
          @getList="getUserActiveList">
        </ai-table>
        <div class="dialog-footer" slot="footer">
          <el-button @click="isShowDetail = false">关闭</el-button>
        </div>
      </ai-dialog>
    </template>
  </ai-list>
</template>

<script>
  import { mapState } from 'vuex'


  export default {
    name: 'List',

    props: {
      instance: Function,
      dict: Object
    },

    data () {
      return {
        userSearch: {
          status: '',
          size: 10,
          total: 0,
          current: 1,
          wxUserId: ''
        },
        search1: {
          size: 10,
          total: 0,
          current: 1
        },
        search: {
          status: '',
          size: 10,
          total: 0,
          name: '',
          current: 1
        },
        isShowDetail: false,
        userDetailList: [],
        activeList: [],
        loading: false,
        isShowList: false,
        defaultChecked: [],
        defaultExpanded: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        colConfigs: [
          { prop: 'name',  label: '姓名', align: 'left' },
          { prop: 'department', label: '部门', align: 'center' },
          { prop: 'c', label: '活跃天数', align: 'center' }
        ],
        activeColConfigs: [
          { prop: 'name',  label: '姓名', align: 'left' },
          { prop: 'department', label: '部门', align: 'center' },
          { prop: 'status', label: '状态', align: 'center' },
          { prop: 'platform', label: '平台', align: 'center' },
          { prop: 'lastUseTime', label: '最后登录时间', align: 'center' },
          { prop: 'ymd', label: '日期', align: 'center' }
        ],
        unitName: '',
        unitList: [],
        tableData: [],
        department: '',
        departmentId: '',
        today: '',
        x: 30,
        y: 18,
        statusList: []
      }
    },

    computed: {
      ...mapState(['user'])
    },

    watch: {
      unitName(val) {
        this.$refs.tree.filter(val)
      }
    },

    mounted() {
      this.today = this.$moment(new Date().getTime() - 24 * 60 * 60 * 1000).format('YYYY-MM-DD')
      this.getTree()
    },

    methods: {
      onTreeChange (e) {
        this.department = e.parentName || e.name

        this.$nextTick(() => {
          this.getData()
        })
      },

      getUserActiveList () {
        if (!this.userSearch.status && this.statusList.length) {
          this.userSearch.status = this.statusList[0].dictName
        }

        this.instance.post(`/app/wxuseruselog/list`, null, {
          params: {
            ...this.userSearch,
            status: this.userSearch.status ? this.userSearch.status : this.statusList.length ? this.statusList[0].dictName : ''
          }
        }).then(res => {
          if (res.code === 0) {
            this.userDetailList = res.data.records
            this.userSearch.total = res.data.total
          }
        })
      },

      getActiveList () {
        if (!this.search.status && this.statusList.length) {
          this.search.status = this.statusList[0].dictName
        }

        this.instance.post(`/app/wxuseruselog/active-log-list`, null, {
          params: {
            ...this.search,
            ymd: this.today,
            status: this.search.status ? this.search.status : this.statusList.length ? this.statusList[0].dictName : ''
          }
        }).then(res => {
          if (res.code === 0) {
            this.activeList = res.data.records
            this.search.total = res.data.total
          }
        })
      },

      initBarChart (data) {
        let chart = echarts.init(document.querySelector('.chart2'))
        const x = data.map(v => v.ymd)
        const y = data.length ? Object.keys(data[0]).filter(v => v !== 'ymd') : []
        let option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            type: "plain"
          },
          grid: {
            left: '20px',
            right: '38px',
            bottom: '14px',
            top: '30px',
            containLabel: true
          },
          dataZoom: [
            {
              type: 'inside',
              start: 0,
              end: 7,
              minValueSpan: 7
            },
            {
              start: 0,
              end: 7
            }
          ],
          color: ['#2266FF', '#22AA99', '#F8B425'],
          xAxis: {
            type: 'category',
            axisLabel: {
              align: 'center',
              padding: [2, 0, 0, 0],
              interval: 0,
              fontSize: 14,
              color: '#666666'
            },
            boundaryGap: false,
            axisLine: {
              lineStyle: {
                color: '#E1E5EF'
              }
            },
            data: x
          },
          yAxis: {
            axisTick: {
              length: 0,
              show: false
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: ['#E1E5EF'],
                width: 1,
                type: 'solid'
              }
            },
            nameTextStyle: {
              color: '#666666',
              align: 'left'
            },
            axisLine: {
              show: false
            },
            axisLabel: {
              color: '#666666'
            },
            type: 'value'
          },
          series: y.map(key => {
            return {
              data: data.map(v => v[key]),
              type: 'line',
              name: key,
              tooltip: {
                valueFormatter: function (value) {
                  return value
                }
              }
            }
          })
        }
        chart.setOption(option)
      },

      initPieChart (data) {
        let chart = echarts.init(document.querySelector('.chart1'))
        const option = {
          tooltip: {},
          color: ['#2896FF', '#09DBFE', '#61FDB9', '#FFBB69', '#8429FF', '#ea7ccc'],
          legend: {
            right: '5%',
            top: 'center',
            orient: 'vertical',
            formatter: function(name) {
              let data = option.series[0].data
              let total = 0
              let tarValue = 0
              for (let i = 0, l = data.length; i < l; i++) {
                total += data[i].value
                if (data[i].name == name) {
                  tarValue = data[i].value
                }
              }
              let p = total === 0 ? 0 : (tarValue / total * 100).toFixed(2)
              return name + '：' + tarValue + ' ' + p + '%'
            }
          },
          series: [
            {
              type: 'pie',
              radius: '50%',
              data: data.map(v => {
                return {
                  value: v.c,
                  name: v.status
                }
              }),
              label : {
                normal : {
                formatter: '{b}：({d}%)',
                textStyle : {
                  fontWeight : 'normal',
                    fontSize : 15
                  }
                }
              }
            }
          ]
        }

        chart.setOption(option)
      },

      getData () {
        this.getDtInfo()
        this.getActiveAnalysisTrend()
        this.getActiveAnalysStatistics()
      },

      getDtInfo () {
        this.instance.post(`/app/wxuseruselog/active-analysis-today?department=${this.department}&ymd=${this.today}`).then(res => {
          if (res.code === 0) {
            this.initPieChart(res.data)
            if (res.data.length) {
              this.statusList = res.data.map(v => {
                return {
                  dictName: v.status,
                  dictValue: v.status
                }
              })
            } else {
              this.search.status = ''
              this.statusList = []
            }
          }
        })
      },

      getActiveAnalysStatistics () {
        this.instance.post(`/app/wxuseruselog/active-analysis-statistics`, null, {
          params: {
            department: this.department,
            x: this.x,
            y: this.y,
            ...this.search1
          }
        }).then(res => {
          if (res.code === 0) {
            this.tableData = res.data.records
            this.search1.total = res.data.total
          }
        })
      },

      getActiveAnalysisTrend () {
        this.instance.post(`/app/wxuseruselog/active-analysis-trend?department=${this.department}`).then(res => {
          if (res.code === 0) {
            this.initBarChart(res.data)
          }
        })
      },

      filterNode(value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1
      },

      getTree() {
        this.instance.post(`/app/wxcp/wxdepartment/listAll?unitName=${this.unitName}`).then(res => {
          if (res.code === 0) {
            let parent = res.data.map(v => {
              v.label = v.name
              v.children = []

              return v
            }).filter(e => !e.parentid)[0]
            this.defaultExpanded = [parent.id]
            this.defaultChecked = [parent.id]
            this.departmentId = parent.id
            this.department = parent.name
            this.addChild(parent, res.data)
            this.unitList = [parent]

            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(parent.id)
            })

            this.getData()
          }
        })
      },

      addChild (parent, list) {
        for (let i = 0; i < list.length; i++) {
          if (list[i].parentid === parent.id) {
            list[i].i = parent.children.length
            list[i].parentName = `${parent.parentName || parent.name}/${list[i].name}`
            parent.children.push(list[i])
          }
        }

        if (parent.children.length) {
          parent.children.forEach(v => {
            v.len = parent.children.length
          })
        }

        if (list.length > 0) {
          parent['children'].map(v => this.addChild(v, list))
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .AppActiveAnalysis {
    .right-search {
      display: flex;
      align-items: center;

      div {
        display: flex;
        align-items: center;
      }

      span {
        margin-right: 10px;
        font-size: 14px;
        color: #686868;
      }

      div:first-child {
        margin-right: 20px;
      }
    }

    :deep( .ai-list__content--right-wrapper ) {
      padding: 0!important;
      background: transparent!important;
      border-radius: 0!important;
      box-shadow: none!important;
    }

    .tree-container {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 100%;

      .tree-name {
        padding-right: 30px;
      }

      i {
        position: absolute;
        top: 50%;
        right: 8px;
        transform: translateY(-50%);
        padding-right: 8px;
        font-weight: normal;
        color: #fff;
      }
    }

    .el-button--mini, .el-button--mini.is-round {
      height: 28px;
      line-height: 28px;
      padding: 0;
      font-size: 12px;

      :deep( span ){
        margin-left: 0;
      }
    }

    .addressBook-left__list--title {
      display: flex;
      align-items: center;
      margin: 8px 8px 0;

      .addressBook-left__list--search {
        flex: 1;

        :deep( input ){
          width: 100%;
        }
      }

      .el-button {
        width: 84px;
        flex-shrink: 1;
        margin-right: 8px;
      }
    }

    .addressBook-left {
      width: 100%;
      height: auto;
      background: #FAFAFB;

      .addressBook-left__title {
        display: flex;
        align-items: center;
        width: 100%;
        height: 40px;
        background: #ffffff;

        h2 {
          flex: 1;
          height: 100%;
          line-height: 40px;
          color: #222;
          font-size: 14px;
          text-align: center;
          cursor: pointer;
          border-bottom: 2px solid transparent;

          &.tab-active {
            color: #2266FF;
            border-bottom: 2px solid #2266FF;
          }
        }
      }

      .addressBook-left__list--wrapper {
        height: calc(100% - 68px);
        padding: 8px;
      }

      .addressBook-left__list {
        width: 100%;
        height: 100%;
        overflow: auto;

        :deep( .el-tree ){
          width: fit-content;
          min-width: 100%;
        }

        :deep( .el-scrollbar__wrap ){
          margin-bottom: 0 !important;
          overflow-x: hidden;

          .el-scrollbar__view {
            width: fit-content;
            min-width: 100%;
          }
        }

        .addressBook-left__tags--item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 40px;
          padding: 0 8px 0 16px;
          cursor: pointer;
          color: #222222;

          &.addressBook-left__tags--item-active, &:hover {
            background: #E8EFFF;
            color: #2266FF;

            i, span {
              color: #2266FF;
            }
          }

          span {
            font-size: 14px;
          }

          i {
            cursor: pointer;
            color: #8e9ebf;
            font-size: 16px;
          }
        }

        span {
          color: #222222;
          font-size: 14px;
        }

        :deep( .el-tree ){
          background: transparent;

          .el-tree-node__expand-icon.is-leaf {
            color: transparent !important;
          }

          .el-tree-node__content > .el-tree-node__expand-icon {
            padding: 4px;
          }

          .el-tree-node__content {
            height: 32px;
          }

          .el-tree__empty-text {
            color: #222;
            font-size: 14px;
          }

          .el-tree-node__children .el-tree-node__content {
            height: 32px;
          }

          .el-tree-node__content:hover {
            background: #E8EFFF;
            color: #222222;
            border-radius: 2px;
          }

          .is-current > .el-tree-node__content {
            &:hover {
              background: #2266FF;
              color: #fff;
            }

            background: #2266FF;

            span {
              color: #fff;
            }
          }
        }
      }
    }

    :deep( .ai-list__content--right ){
      flex: 1;
      min-width: 0;
      margin-left: 1px;
      box-shadow: none;

      .ai-list__content--right-wrapper {
        width: 100%;
      }
    }

  }
</style>
