<template>
  <div class="statistics_personal_b_box">
    <van-nav-bar title="我的B分统计" left-text="返回" @click-left="$route_back" left-arrow>
      <template slot="right">
        <span class="right_button" @click.stop="viewRanking">查看排名</span>
      </template>
    </van-nav-bar>
    <div class="body_com">
      <scroller>
        <div class="person_b_box">
          <YearMonthPicker v-model="date_value"></YearMonthPicker>
          <StatisticsMonthTotal :data="statisticsData"/>
        </div>
        <van-cell-group style="margin:0;">
          <van-cell class="b-point__wrapper">
            <div class="b-point-title" style="margin-top: 0.52rem;" slot="title">近半年的B分</div>
          </van-cell>
          <div slot="default">
            <div id="chartLineBox" style="height: 3.6rem;"></div>
          </div>
        </van-cell-group>
        <van-cell-group>
          <van-cell class="b-point__wrapper">
            <div class="b-point-title" slot="title">积分构成</div>
          </van-cell>
          <div slot="default">
            <van-empty v-if="pieData == null || (pieData != null && pieData.length == 0)" description="暂无数据"/>
            <div id="chartPieBox" style="height: 2.48rem;"></div>
          </div>
        </van-cell-group>

        <van-cell-group>
          <van-cell class="b-point__wrapper">
            <div class="b-point-title" slot="title">最新积分事件</div>
            <div slot="default">
              <span @click="event_list" v-if="integral_list !== null && integral_list.length > 0">查看更多</span>
            </div>
          </van-cell>
          <div slot="default">
            <van-cell v-for="(item,index) in integral_list" :key="index" :title="item.remark">
              <template slot="right-icon">{{item.point}}{{point_name(item.pt_id).name}}</template>
                <!-- <span :class="item.point < 0?'color_green':'color_red'"></span> -->
            </van-cell>
            <van-empty v-if="integral_list == null || (integral_list != null && integral_list.length == 0)" description="暂无数据"/>
          </div>
        </van-cell-group>

        <van-cell-group>
          <van-cell
            class="b-point__wrapper"
            style="border-bottom: 0.02rem solid #ebedf0;"
          >
            <div class="b-point-title" slot="title">奖分最多</div>
          </van-cell>
          <!--  @click="$router.push({name:'event_detail', query:{id: o.id}})" -->
          <noData :list="fiveList"></noData>
          <div class="current-event__item"
               v-for="(o, i) in fiveList" :key="i">
            <div class="current-event_content" v-if="o.remark.customize != ''">{{ o.remark.customize }}</div>
            <div class="current-event_content" v-else>{{ o.remark.rule }}</div>
            <div class="current-event_value">+{{ o.point }}</div>
          </div>
        </van-cell-group>
        <van-cell v-if="showMore" @click="lookMore" >
          <template slot="default">
            <div  style="text-align: center;">查看更多<van-icon name="arrow-down" style="vertical-align: middle;" /></div>
          </template>
        </van-cell>
        <van-cell-group>
          <van-cell
            class="b-point__wrapper"
            style="border-bottom: 0.02rem solid #ebedf0;"
          >
            <div class="b-point-title" slot="title">扣分最多</div>
          </van-cell>
          <div @click="$router.push({name:'event_detail', query:{id: o.id}})" class="current-event__item"
               v-for="(o, i) in fiveListBad" :key="i">
            <div class="current-event_content" v-if="o.remark.customize != ''">{{ o.remark.customize }}</div>
            <div class="current-event_content" v-else>{{ o.remark.rule }}</div>
            <div class="current-event_value green">{{ o.point }}</div>
          </div>
          <van-cell v-if="showMoreBad && hasMostDeductionPointData" @click="setShowMore" >
            <template slot="default">
              <div  style="text-align: center;">查看更多<van-icon name="arrow-down" style="vertical-align: middle;" /></div>
            </template>
          </van-cell>
          <van-empty v-if="!hasMostDeductionPointData" description="当月没有扣分事件"/>
        </van-cell-group>
      </scroller>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import Vue from 'vue'
import {Empty, Panel, Image, Button, Icon } from 'vant'
import YearMonthPicker from '@/components/common/YearMonthPicker'
import StatisticsMonthTotal from './statistics_month_total'
import moment from 'moment'

Vue.use(Empty)
  .use(Panel)
  .use(Image)
  .use(Button).use(Icon)

export default {
  name: 'statistics_personal_b',
  data () {
    const {month} = this.$route.query
    const date_value = month || moment().format('YYYY-MM')

    return {
      statisticsData: [
        {label: '本月B分', value: 0},
        {label: '本年B分', value: 0},
        {label: '累计B分', value: 0}
      ],
      showMore: false,
      showMoreBad: false,
      mostRewardPointList: null,
      fiveList: null,
      fiveListBad: null,
      mostDeductionPointList: null,
      date_value: date_value,
      pieData: null,
      employee_id: null,
      integral_list: null,
      point_types: JSON.parse(localStorage.getItem('SET_POINT_TYPES')) || JSON.parse(plus.storage.getItem('SET_POINT_TYPES'))
    }
  },
  components: {YearMonthPicker, StatisticsMonthTotal},
  watch: {
    date_value () {
      this.get_data()
    }
  },
  computed: {
    hasMostRewardPointData () {
      return Array.isArray(this.mostRewardPointList) && this.mostRewardPointList.length > 0
    },
    hasMostDeductionPointData () {
      return Array.isArray(this.mostDeductionPointList) && this.mostDeductionPointList.length > 0
    }
  },
  methods: {
    event_list () {
      let employee_id = ''
      this.$route.query.employee_id ? employee_id = this.$route.query.employee_id : employee_id = this.$userInfo().id
      this.$router.push({name: 'event_list', query: {employee_id: employee_id}})
    },
    viewRanking () {
      this.$router.push({name: 'integral_rank', query: {month: this.date_value}})
    },
    initEChartOption () {
      this.option = {
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            params = params[0]
            return '月份：' + params.name + ' </br> 分值：' + params.value
          },
          axisPointer: {
            animation: false
          },
          show: true
        },
        grid: {
          containLabel: true,
          top: '4%',
          right: '4%',
          bottom: '5%',
          left: '7%'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLine: {lineStyle: {color: '#eee'}},
          axisLabel: {color: '#333'}
        },
        yAxis: {
          position: 'right',
          axisLine: {lineStyle: {color: '#eee'}},
          axisLabel: {color: '#333'},
          type: 'value',
          splitLine: {lineStyle: {color: '#eee'}}
        },
        series: {
          type: 'line',
          lineStyle: {normal: {color: '#26A2FF'}}
        }
      }
      this.pieOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          top: 'middle',
          left: '45%',
          itemGap: 15,
          itemWidth: 10,
          itemHeight: 10,
          data: null
        },
        series: {
          name: '积分构成',
          type: 'pie',
          radius: ['30%', '80%'],
          center: ['25%', '50%'],
          label: {show: false},
          labelLine: {show: false},
          data: null
        }
      }

      this.pieChartItemsStyle = [
        {color: '#46A7F8'},
        {color: '#ED4A60'},
        {color: '#75D16D'},
        {color: '#F3983E'}
      ]
    },
    lookMore () {
      this.fiveList = this.mostRewardPointList
      this.showMore = false
    },
    setShowMore () {
      this.fiveListBad = this.mostDeductionPointList
      this.showMoreBad = false
    },
    get_data () {
      this.$toast.loading({message: '正在加载'})

      const method = 'get'
      let params = {}
      if (this.employee_id) {
        params = {employee_id: this.employee_id, month: this.date_value}
      } else {
        params = {employee_id: this.$userInfo().id, month: this.date_value}
      }
      const mainRequest = request('get','/api/integral/statistics/b', params)
      const pieRequest = request('get','/api/integral/statistics/pie/b', params,'v2')

      Promise.all([mainRequest, pieRequest]).then(resArr => {
        if (resArr[0].data.code == 1) {
          const xAxisData = []
          const {b, chart, good, bad} = resArr[0].data.data
          const points = chart.reward.map((rewardItem, index) => {
            xAxisData.push(rewardItem.month)
            return rewardItem.point + (chart.deduction[index].point || 0)
          })
          this.mostRewardPointList = good
          if (good.length > 5) {
            this.showMore = true
            this.fiveList = good.slice(0, 5)
          } else {
            this.showMore = false
            this.fiveList = this.mostRewardPointList
          }
          this.mostDeductionPointList = bad

          if (bad.length > 5) {
            this.showMoreBad = true
            this.fiveListBad = bad.slice(0, 5)
          } else {
            this.showMoreBad = false
            this.fiveListBad = this.mostDeductionPointList
          }

          this.statisticsData[0].value = b.month_point || '0'
          this.statisticsData[1].value = b.year_point || '0'
          this.statisticsData[2].value = b.total_point || '0'
          this.setEChartOption(xAxisData, points)
        }
        if (resArr[1].data.code == 1) {
          let totalPoint = 0
          const pieData = resArr[1].data.data.list.map((item, index) => {
            totalPoint += item.point
            if (item.ratio < 0) {
              return {name: item.name, value:0,value2: item.deduction,ratio:item.ratio,itemStyle: this.pieChartItemsStyle[index]}
            } else {
              return {name: item.name, value: item.reward,value2: item.deduction,ratio:item.ratio,itemStyle: this.pieChartItemsStyle[index]}
            }
          })
          this.setEchartPieOption(pieData, totalPoint)
        }
      }).finally(() => this.$toast.clear())
    },
    setEChartOption (xAxisData, points) {
      this.option.xAxis.data = xAxisData
      this.option.series.data = points
      this.chartLine.setOption(this.option)
    },
    setEchartPieOption (pieData, totalPoint) {
      const {legend, series} = this.pieOption
      legend.data = pieData
      this.pieData = pieData
      legend.formatter = (name) => {
        const item = pieData.find(o => o.name === name)

        return `${name} 奖${item.value}分 扣${item.value2}分 ${item.ratio}%`
      }
      series.data = pieData
      this.chartPie.setOption(this.pieOption)
    },

    get_integral_list () {
      let self = this
      let employee_id = ''
      this.$route.query.employee_id ? employee_id = this.$route.query.employee_id : employee_id = this.$userInfo().id
      let data = {page_size: 5, page: 1, employee_ids: employee_id, pt_id: '3'}
      this.$route.query.employee_id ? data['employee_ids'] = this.$route.query.employee_id : ''
      request('get','/api/integral/statistics/integral', data).then(res => {
        if (res.data.code == 1) {
          self.integral_list = res.data.data.list
        }
      })
    },
    point_name (name) {
      if (this.point_types) {
        let pt_name = this.point_types.find(function (element) {
          if (element.id == name) {
            return element.name
          }
        })
        return pt_name
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      setTimeout(() => {
        this.get_data()
        this.initEChartOption()
        this.chartLine = this.$echarts.init(document.getElementById('chartLineBox'))
        this.chartPie = this.$echarts.init(document.getElementById('chartPieBox'))
      }, 200)
      document.querySelector('.body_com').scrollTop = 100
    })
    if (this.$route.query.employee_id) {
      this.employee_id = this.$route.query.employee_id
    }
    this.get_integral_list()
  }
}
</script>

<style scoped lang="less">
  .statistics_personal_b_box {
    & .person_b_box {
      height: 2.04rem;
      background: #26a2ff;
      z-index: 1;

      & .bg-fff {
        background: transparent;

        & /deep/ .YMPicker_item_icon,
        /deep/ .date-text, /deep/ .van-icon {
          color: #fff;
        }
      }
    }
  }

  & /deep/ .van-empty__image {
    width: 2rem;
    height: 2rem;
  }

  & /deep/ .van-empty {
    padding: 0.24rem 0;
  }

  .right_button {
    color: #fff;
  }

  .body_com {
    height: calc(100% - 0.92rem);
    position: relative;
  }

  .b-point__wrapper {
    &:after {
      border-bottom-color: transparent;
    }

    & /deep/ .van-cell__value,
    /deep/ .van-cell__right-icon {
      margin-right: 0;
      font-size: 14px;
      color: #333;
    }
  }

  .b-point-title {
    position: relative;
    padding-left: 0.2rem;
    font-size: 0.28rem;
    font-weight: 600;

    &:before {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      height: 0.32rem;
      width: 0.08rem;
      border-radius: 0.04rem;
      background: #238dfa;
      transform: translateY(-50%);
    }
  }

  .current-event__item {
    position: relative;
    display: flex;
    box-sizing: border-box;
    font-size: 0.32rem;
    color: #333;

    &:not(:last-child)::after {
      position: absolute;
      box-sizing: border-box;
      content: ' ';
      pointer-events: none;
      right: 0;
      bottom: 0;
      left: 0.32rem;
      border-bottom: 1px solid #ebedf0;
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
    }

    & .current-event_content {
      display: flex;
      flex: 1;
      padding: 0.24rem 0 0.24rem 0.32rem;
    }

    & .current-event_value {
      display: flex;
      padding-top: 0.24rem;
      padding-bottom: 0.24rem;
      padding-right: 0.32rem;
      width: 1.1rem;
      color: #ff0000;
      align-items: center;
      justify-content: flex-end;

      &.green {
        color: #4bd964;
      }
    }
  }
</style>
