<template>
  <div style=" background-color: #fff; padding:15px; min-height: 10px; overflow: hidden;">
    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
      <el-date-picker
        v-model="filter.time_range"
        type="daterange"
        value-format="timestamp"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="instantPickerOptions"
        @change="loadRankData"
      ></el-date-picker>
      <!-- <el-cascader
        clearable
        :options="categoryTree"
        change-on-select
        v-model="filter.category_id"
        @change="loadRankData"
        placeholder="选择积分分类进行筛选"
        class="gap-right-8"
        style="width:150px;"
      ></el-cascader>-->
      <div style="position:relative; display:inline-block;" @click.stop="show3 = !show3">
        <el-button style="color:rgb(192 196 204); padding-right:25px;">
          <span style="max-width: 150px; display: inline-block; overflow: hidden;" :class="{'treeActice':textTip != '选择积分分类筛选'}">{{textTip}}</span>
          <span class="el-input__suffix">
            <span class="el-input__suffix-inner">
              <i :class="{'arrRotation': show3}" class="el-input__icon el-icon-arrow-down"></i>
            </span>
          </span>
        </el-button>
        <el-collapse-transition>
          <div
            v-show="show3"
            style="margin-top:10px;
            padding:6px 0;
             max-height:250px;
             min-width: 180px;
             overflow: auto;
             position:absolute;
             z-index:99;
             border: 1px solid #e4e7ed;
             border-radius: 2px;
             background:#fff;
             box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);"
          >
            <el-tree
              node-key="value"
              ref="tree"
              :data="categoryTree"
              :accordion="true"
              :highlight-current="true"
              :props="defaultProps"
              show-checkbox
              @check="handleCheck"
            ></el-tree>
          </div>
        </el-collapse-transition>
      </div>

      <el-select
        v-show="settings.point_set.indexOf('a') >= 0"
        v-model="filter.point_type"
        @change="loadRankData"
        style="width:90px;"
      >
        <el-option
          v-for="item in pointTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-cascader
        v-show="false"
        clearable
        :options="deptTree"
        change-on-select
        v-model="filter.dept_id"
        @change="loadRankData"
        placeholder="选择部门进行筛选"
        class="gap-right-8"
        style="width:100px;"
      ></el-cascader>
    </div>
    <el-col :span="24">
      <ve-bar
        v-loading="loading"
        ref="chart-histogram"
        :xAxis="xAxis"
        :yAxis="yAxis"
        :tooltip="tooltip"
        :series="series"
        :grid="{left:10,bottom:15,top:70}"
        :legend="Legend"
        height="450px"
        :settings="chartSettings"
        :colors="colorsintegral"
      ></ve-bar>
    </el-col>
  </div>
</template>

<script>
import Vue from 'vue';
import VCharts from 'v-charts';

Vue.use(VCharts)

export default {
  data() {
    this.chartSettings = {
      stack: { 日期: ['奖分', '扣分'] }
    }
    return {
      settings: this.$store.getters.system_setting,
      textTip: '选择积分分类筛选',
      show3: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // props: {
      //   label: "name",
      //   children: "zones"
      // },
      loading: false,
      Legend: {
        itemWidth: 18,
        itemHeight: 12,
        right: 10,
        top: 20
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(a) {
          console.log(a)
          return (
            '奖分：' +
            a[0].value +
            '<br/>扣分：' +
            a[1].value +
            '<br/>奖扣比例：' +
            ((a[1].value / a[0].value) * 100).toFixed(0) +
            '%'
          )
        }
      },
      xAxis: {
        type: 'value',
        data: []
      },
      yAxis: {
        type: 'category',
        data: []
      },
      series: [
        {
          name: '奖分',
          type: 'bar',
          stack: '分数',
          data: [],
          barMinHeight: 1
        },
        {
          name: '扣分',
          type: 'bar',
          stack: '分数',
          data: [],
          barMinHeight: 0
        }
      ],
      colorsintegral: ['#5ab1ef', '#fc8675'],

      filtersAdvShow: false,
      filter: {
        keywords: '',
        target_id_set: [],
        category_id: [],
        dept_id: [],
        point_type: 0,
        time_range: ''
      },
      profile: this.$store.getters.user_info,
      categoryTree: [],
      pointTypes: [],
      deptTree: [],

      instantPickerOptions: {
        shortcuts: [
          {
            text: '本周',
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString())
              let start =
                now.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000
              let end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '上周',
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString())
              let start =
                now.getTime() - (now.getDay() + 6) * 24 * 60 * 60 * 1000
              let end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '本月',
            onClick(picker) {
              const now = new Date()
              let startDate = new Date(now.getFullYear(), now.getMonth(), 1)
              let endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          },
          {
            text: '上月',
            onClick(picker) {
              const now = new Date()
              let startDate = new Date(
                now.getFullYear() - (now.getMonth() > 0 ? 0 : 1),
                (now.getMonth() + 11) % 12,
                1
              )
              let endDate = new Date(now.getFullYear(), now.getMonth(), 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          },
          {
            text: '本年',
            onClick(picker) {
              const now = new Date()
              let startDate = new Date(now.getFullYear(), 0, 1)
              let endDate = new Date(now.getFullYear() + 1, 0, 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          }
        ]
      }
    }
  },
  components: {},
  methods: {
    handleCheck(target , param) {
      this.textTip = ''
      const textTip = []
      this.$refs.tree.getCheckedNodes().forEach(item => {
        textTip.push(item.label)
      })
      this.textTip = textTip.join('、')
      if (param.checkedKeys.length == 0) {
        this.textTip = '选择积分分类筛选'
      }
      this.filter.category_id = param.checkedKeys
      this.loadRankData()
      this.show3 = false
    },
    updateEmployeeRange: function(currentVal) {
      if (currentVal) {
        this.loadTargetList()
        this.onFilterChanged()
      } else {
        var self = this
        this.loadTargetList(() => {
          const idArr = self.employeeOptions.map(item => {
            return item.id
          })
          self.filter.target_id_set = self.filter.target_id_set.filter(
            item => idArr.indexOf(item) > -1
          )
          self.onFilterChanged()
        })
      }
    },
    // 获取控件所需数据
    loadWidgetData: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/prepare_integral_options',{
            id: this.profile.id,
            category_tree: 1,
            dept_tree: 1
          })
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.categoryTree = jsonData.category_tree
              self.deptTree = jsonData.dept_tree
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    loadPointType: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_point_types')
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.pointTypes = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    loadRankData: function() {
      this.loading = true
      let params = {
        site_id: this.profile.site_id,
        page: this.currentPage
      }
      for (const item in this.filter) {
        const value = this.filter[item]
        if (item == 'category_id' || item == 'dept_id') {
          if (!value || value.length == 0) {
            continue
          }
          if (item == 'category_id') {
            params[item] = value
          }else {
            params[item] = value[value.length - 1]
          }
          // params[item] = value[value.length - 1];
        } else if (item == 'time_range') {
          if (!value || value.length < 2) {
            continue
          }
          const timeRangeArr = value.map(x => parseInt(x / 1000))
          timeRangeArr[1] += 60 * 60 * 24 - 1
          params[item] = timeRangeArr.join(',')
        } else {
          params[item] = value
        }
      }
      var self = this
      this.$http('get','/integral.php/point_data/rank_by_dept',params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false
            let jsonData = response.data
            try {
              const datetime = []
              const add_point = []
              const sub_point = []

              console.log(jsonData)
              //if(typeof(jsonData.trend_chart_data) != 'undefined'){
              for (const item in jsonData.labels) {
                datetime.push(jsonData.labels[item])

                sub_point.push(jsonData.p_negative[item] * -1)
                add_point.push(jsonData.p_positive[item] * 1)
              }

              // }
              // console.log(add_point, sub_point,datetime)
              self.$set(self.series[0], 'data', add_point.reverse())
              self.$set(self.series[1], 'data', sub_point.reverse())
              self.$set(self.yAxis, 'data', datetime.reverse())

              /*let chart = self.$refs['deptRankChart']
              chart.getChart().xAxis[0].setCategories(jsonData.labels)
              chart.removeSeries()
              chart.addSeries({
                name: "奖分",
                data: jsonData.p_positive.map(Number),
                stack: 'n'
              })
              const p_negative = []
              for(let i in jsonData.p_negative.map(Number)){
                p_negative.push(jsonData.p_negative.map(Number)[i]*-1)
              }
              chart.addSeries([{
                name: "奖分",
                data: jsonData.p_positive.map(Number),
                stack: 'n'
              },{
                name: "扣分",
                data: p_negative,
                stack: 'n'
              }])*/
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    resize() {}
  },
  watch: {
    '$store.getters.sidebar.opened': function(curVal, oldVal) {
      // 左边菜单发生变化时，重新设定图表宽度，以适应屏幕
      const self = this
      setTimeout(() => {
        self.$refs['chart-histogram'].echarts.resize()
      }, 300)
    }
  },
  created() {
    this.loadWidgetData()
    this.loadPointType()
    this.loadRankData()
    this.$nextTick(() => { // 点击body关闭筛选组件
      document.querySelector('#app').addEventListener('click', e => {
        if (this.show3) {
          this.show3 = false
        }
      })
    })
  }
}
</script>

<style>
tbody .image-container div.cell {
  height: 42px;
}
.arrRotation {
  transform: rotate(180deg);
}
.treeActice{
  color: #606266;
}
.el-tree-node__content{
  height: 34px;
}
</style>
