<template>
  <div style=" background-color: #fff; padding:15px;">

    <div style="margin-top:2px;" class="inline-block-btn-list">

      <el-date-picker
        class="first-element-btn"
        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-cascader
        clearable
        :options="categoryTree"
        change-on-select
        v-model="filter.category_id"
        @change="onFilterChanged"
        placeholder="选择积分分类进行筛选"
        class="gap-right-8">
      </el-cascader>
      <el-select
        v-show="false"
        v-model="filter.point_type"
        @change="onFilterChanged">
        <el-option
          v-for="item in pointTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </div>

    <div v-show="filtersAdvShow" class="inline-block-btn-list inline-block-btn-list-adv">
      <el-checkbox class="first-element-btn" style="padding:9px 20px;" border v-model="filter.include_manager" @change="updateEmployeeRange">包含管理者进行排名
      </el-checkbox>



      <el-select
v-show="false"
        v-model="filter.target_id_set"
        filterable
        multiple
        :multiple-limit="15"
        placeholder="选择员工进行筛选（最多15个）"
        @change="onFilterChanged"
        style="width:200px;">
        <el-option
          v-for="item in employeeOptions"
          :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="姓名">
        <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 label="部门" prop="dept_name" class-name="text-auxiliary"></el-table-column>
      <el-table-column label="排行">
        <template slot-scope="scope">
          <div 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="" class="table-font-number" v-if="(currentPage - 1) * 10 + scope.row.index > 3">
            NO.{{ (currentPage - 1) * 10 + scope.row.index }}
          </div>
          <!-- <div>{{scope.row}}</div> -->
        </template>
      </el-table-column>
      <el-table-column label="总分">
        <template slot-scope="scope">
          <div 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 {
        profile: this.$store.getters.user_info,
        filtersAdvShow: false,
        filter: {
          keywords: '',
          target_id_set: [],
          category_id: [],
          dept_id: [],
          point_type: 0,
          time_range: '',
          include_manager: false
        },
        totalCount: 0,
        currentPage: 1,
        rankList: null,
        categoryTree: [],
        deptTree: [],
        employeeOptions: [],
        pointTypes: [],
        loading:false,
        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: {
      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()
      },
      updateEmployeeRange: function (currentVal) {
        if (currentVal) {
          this.loadTargetList()
          this.onFilterChanged()
        } else {
          var self = this
          this.loadTargetList(() => {
            let 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)
        })
      },
      //获取可排名的员工列表
      loadTargetList: function (callback) {
        var self = this
        this.$http('get','/integral.php/point_data/load_target_list',{
            site_id: this.profile.site_id,
            exclude_manager: this.filter.include_manager ? 0 : 1
          }).then(function (response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.employeeOptions = jsonData
              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) {
            let jsonData = response.data
            try {
              self.pointTypes = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      loadRankList: function () {
        let params = {
          site_id: this.profile.site_id,
          page: this.currentPage
        }
        this.filter.dept_id = [this.profile.dept_id]
        for (let item in this.filter) {
          let 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[value.length - 1]
          } else if (item == 'time_range') {
            if (!value || value.length < 2) {
              continue
            }
            let timeRangeArr = value.map(x => parseInt(x / 1000))
            timeRangeArr[1] += 60 * 60 * 24 - 1
            params[item] = timeRangeArr.join(",")
          } else if (item == 'include_manager') {
            params['exclude_manager'] = value ? 0 : 1
          } 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.loadWidgetData()
      this.loadTargetList()
      this.loadPointType()
      this.loadRankList()
    }
  }
</script>

<style>
  tbody .image-container div.cell {
    height: 42px;
  }

  .el-pagination {
    text-align: center;
    margin-top: 15px;
  }

  .el-tabs__header {
    margin: 0;
  }
  .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;}
</style>
