<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-cascader
        clearable
        v-if="false"
        :options="categoryTree"
        change-on-select
        v-model="filter.category_id"
        @change="onFilterChanged"
        placeholder="选择积分分类进行筛选"
        class="gap-right-8"
        style="width:150px;"
      ></el-cascader>

       <div style="position:relative; display:inline-block;">
        <el-button @click.stop="show3 = !show3" 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="onFilterChanged"
        style="width:90px;"
      >
        <el-option
          v-for="item in pointTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-date-picker
        v-model="filter.time_range"
        type="daterange"
        value-format="timestamp"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="instantPickerOptions"
        @change="onFilterChanged"
      ></el-date-picker>
      <el-select
        v-model="filter.job_id"
        placeholder="选择职位进行筛选"
        @change="onFilterChanged"
        style="width:150px"
      >
        <el-option v-for="item in jobOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
    </div>

    <el-table
      v-loading="loading"
      ref="rankTable"
      :data="rankList"
      tooltip-effect="dark"
      style="width: 100%"
      :row-class-name="tableRowClassName"
      :header-cell-style="{ textAlign : 'left' }"
    >
      <el-table-column label="头像" class-name>
        <template slot-scope="scope">
          <div class="rank_head">
            <img
              v-if="scope.row.target_img != null"
              v-bind:src="scope.row.target_img"
              width="42px"
              height="42px"
            >
            <img
              v-if="scope.row.target_img == null"
              src="static/images/head_default.png"
              width="42px"
              height="42px"
            >
            {{scope.row.target_name}}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="dept_name" label="部门" class-name="text-auxiliary"></el-table-column>
      <el-table-column label="排行">
        <template slot-scope="scope">
          <div style="float:left" class="table-font-number" v-if="(currentPage - 1) * 10 + scope.row.index <= 3">
            <img src="static/images/rank_01.png" width="20" v-if="scope.row.index == 1">
            <img src="static/images/rank_02.png" width="20" v-if="scope.row.index == 2">
            <img src="static/images/rank_03.png" width="20" v-if="scope.row.index == 3">
          </div>

          <div
            style="float:left"
            class="table-font-number"
            v-if="(currentPage - 1) * 10 + scope.row.index > 3"
          >No.{{ (currentPage - 1) * 10 + scope.row.index }}</div>
          <div style="float:left" v-if="scope.row.status > 0">
            <img
              style="width:9px; height:17px; margin:3px 5px 0 8px;"
              src="static/images/up_small.png"
              alt
            >
            <span
              style="display:block; float:right; color:rgb(245,108,108)"
            >{{scope.row.rank_change}}</span>
          </div>
          <div style="float:left" v-if="scope.row.status < 0">
            <img
              style="width:9px; height:17px; margin:3px 5px 0 8px;"
              src="static/images/down_small.png"
              alt
            >
            <span
              style="display:block; float:right; color:rgb(103,194,58)"
            >{{scope.row.rank_change}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="总分">
        <template slot-scope="scope">
          <div
            style="color:#409EFF; font-size: 18px;"
            v-bind:class="'table-font-xl table-font-number ' + (scope.row.p_sum < 0 ? 'point-negative' : 'point-positive')"
          >{{ scope.row.p_sum }}</div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :page-size="10"
      :page-sizes="[10, 20, 50, 100]"
      :total="totalCount"
      :current-page.sync="currentPage"
      @current-change="changePage"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      settings: this.$store.getters.system_setting,
      textTip: '选择积分分类筛选',
      show3: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      loading: false,
      filter: {
        keywords: '',
        target_id_set: [],
        category_id: [],
        point_type: 0,
        time_range: '',
        job_id: ''
      },
      profile: this.$store.getters.user_info,
      totalCount: 0,
      currentPage: 1,
      rankList: null,
      categoryTree: [],
      pointTypes: [],
      jobOptions: [],
      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()])
            }
          }
        ]
      }
    }
  },
  methods: {
    handleCheck(target , param) {
      this.textTip = ''
      this.$refs.tree.getCheckedNodes().forEach(item => {
        this.textTip += item.label + '、'
      })
      if (param.checkedKeys.length == 0) {
        this.textTip = '选择积分分类筛选'
        this.show3 = false
      }
      this.filter.category_id = param.checkedKeys
      this.onFilterChanged()
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.target_id == this.$store.getters.user_info.id) {
        return 'rank-mine'
        }
      return ''
      },
    onFilterChanged: function() {
      this.currentPage = 1
      this.loadRankList()
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false
      }
      this.loadRankList()
    },
    // 获取控件所需数据
    loadWidgetData: function(callback) {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/prepare_integral_options',{
            id: this.profile.id,
            category_tree: 1,
            job_list: 1
          })
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.categoryTree = jsonData.category_tree
              self.jobOptions = jsonData.job_list
              if (callback) {
                callback.call()
              }
            } 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)
        })
    },
    loadRankList: function() {
      const params = {
        site_id: this.profile.site_id,
        page: this.currentPage
      }
      for (const item in this.filter) {
        const value = this.filter[item]
        if (item == 'target_id_set') {
          if (!value || value.length == 0) {
            continue
          }
          params[item] = value.join(',')
        } else if (item == 'category_id' || item == 'dept_id') {
          if (!value || value.length == 0) {
            continue
          }
          params[item] = value
          // 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
      self.loading = true
      this.$http('get','/integral.php/point_data/rank_by_employee',params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false
            let jsonData = response.data
            try {
              self.totalCount = jsonData.total_count
              self.rankList = jsonData.list_data
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    }
  },
  created() {
    this.loadPointType()
    var self = this
    this.loadWidgetData(() => {
      if (self.jobOptions && self.jobOptions.length > 0) {
        self.filter.job_id = self.jobOptions[0].id
        self.loadRankList()
      }
    })
    this.$nextTick(() => {
      document.querySelector('#app').addEventListener('click', () => {
        if (this.show3) {
          this.show3 = false
        }
      })
    })
  }
}
</script>

<style>
tbody .image-container div.cell {
  height: 42px;
}
.rank_head img {
  width: 30px;
  height: 30px;
  -webkit-border-radius: 20px;
  -moz-border-radius: 20px;
  border-radius: 20px;
  margin-right: 5px;
}
.rank_head * {
  vertical-align: middle;
}
.arrRotation {
  transform: rotate(180deg);
}
.treeActice{
  color: #606266;
}
.el-tree-node__content{
  height: 34px;
}
</style>
