<template>
  <div style=" background-color: #fff; padding:15px;" @click="show3=false;show4=false">
    <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
        v-if="false"
        v-show="profile.manager_type > 0"
        clearable
        :options="deptTree"
        change-on-select
        v-model="filter.dept_id"
        @change="onFilterChanged"
        placeholder="选择部门进行筛选"
        class="gap-right-8"
        style="width:160px;"
      ></el-cascader>
      <!-- 部门 tree -->
      <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="deptTree"
              :accordion="true"
              :highlight-current="true"
              :props="defaultProps"
              show-checkbox
              @check="handleCheck"
            ></el-tree>
          </div>
        </el-collapse-transition>
      </div>

      <el-button
        @click="filtersAdvShow = true"
        v-show="filtersAdvShow==false"
        type="primary"
        plain
      >高级</el-button>
      <el-button @click="filtersAdvShow = false" v-show="filtersAdvShow" type="primary" plain>取消</el-button>
      <el-select
        style="width:70px;"
        v-show="settings.point_set.indexOf('a') >= 0"
        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_init_point"
        @change="onFilterChanged"
      >包含初始积分</el-checkbox>
      <!-- 工龄分 -->
      <el-checkbox
        class="first-element-btn"
        style="padding:9px 20px;"
        border
        v-model="filter.include_seniority_point"
        @change="onFilterChanged"
      >包含工龄分</el-checkbox>
      <el-checkbox
        class="first-element-btn"
        style="padding:9px 20px;"
        border
        v-model="filter.include_manager"
        @change="updateEmployeeRange"
      >包含管理者进行排名</el-checkbox>
      <el-cascader
        clearable
        v-show="false"
        :options="categoryTree"
        change-on-select
        v-model="filter.category_id"
        @change="onFilterChanged"
        placeholder="选择积分分类进行筛选"
        class="gap-right-8"
      ></el-cascader>

      <!-- <el-collapse-transition> -->
        <div style="position:relative; display:inline-block;" @click.stop="show4=true">
          <el-button @click="show4 = !show4" style="color:rgb(192 196 204); padding-right:25px;">
            <span
              style="max-width: 150px; display: inline-block; overflow: hidden;"
              :class="{'treeActice':textTip1 != '选择分类进行筛选'}"
            >{{textTip1}}</span>
            <span class="el-input__suffix">
              <span class="el-input__suffix-inner">
                <i :class="{'arrRotation': show4}" class="el-input__icon el-icon-arrow-down"></i>
              </span>
            </span>
          </el-button>
          <el-collapse-transition>
            <div
              v-show="show4"
              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;
             box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);"
            >
              <el-tree
                node-key="value"
                ref="tree4"
                :data="categoryTree"
                :accordion="true"
                :highlight-current="true"
                :props="defaultProps"
                show-checkbox
                @check="handleCheck4"
              ></el-tree>
            </div>
          </el-collapse-transition>
        </div>
      <!-- </el-collapse-transition> -->

      <!-- <el-select
        v-show="true"
        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>-->
      <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>



      <el-button type="primary" plain @click="get_excel_token">导出Excel</el-button>

    </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
            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>
          <!-- <div style="float:left; color:rgb(204,204,204);" v-if="scope.row.status === 0"><img style="width:9px; height:3px; margin:0 5px 3px 8px;" src="static/images/equal.png" alt=""></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>
  import qs from 'qs'
export default {
  data() {
    return {
      initPointTypes: [{
        label: '不包含初始分', value: 0
      }, {
        label: '包含初始分', value: 1
      }],
      seniorityPointTypes: [{
        label: '不包含工龄分', value: 0
      }, {
        label: '包含工龄分', value: 1
      }],
      show3: false,
      show4: false,
      textTip: '选择部门进行筛选',
      textTip1: '选择分类进行筛选',
      settings: this.$store.getters.system_setting,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      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,
        include_init_point: false,
        include_seniority_point: 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())
              const start =
                now.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000
              const end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '上周',
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString())
              const start =
                now.getTime() - (now.getDay() + 6) * 24 * 60 * 60 * 1000
              const end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '本月',
            onClick(picker) {
              const now = new Date()
              const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
              const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          },
          {
            text: '上月',
            onClick(picker) {
              const now = new Date()
              const startDate = new Date(
                now.getFullYear() - (now.getMonth() > 0 ? 0 : 1),
                (now.getMonth() + 11) % 12,
                1
              )
              const endDate = new Date(now.getFullYear(), now.getMonth(), 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          },
          {
            text: '本年',
            onClick(picker) {
              const now = new Date()
              const startDate = new Date(now.getFullYear(), 0, 1)
              const endDate = new Date(now.getFullYear() + 1, 0, 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          }
        ]
      }
    }
  },
  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.dept_id = param.checkedKeys
      this.onFilterChanged()
      // this.show3 = false;
    },

    handleCheck4(target, param) {
      this.textTip1 = ''
      const textTip1 = []
      this.$refs.tree4.getCheckedNodes().forEach(item => {
        textTip1.push(item.label)
      })
      this.textTip1 = textTip1.join('、')
      if (param.checkedKeys.length == 0) {
        this.textTip1 = '选择分类进行筛选'
      }
      this.filter.category_id = param.checkedKeys
      this.onFilterChanged()
      // this.show4 = false;
    },
    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(() => {
          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)
        })
    },
    // 获取可排名的员工列表
    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)
        })
    },

    get_excel_token: function() {
      var self = this

      const params = {
        site_id: this.profile.site_id,
      }
      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 if (item == 'include_manager') {
          params['exclude_manager'] = value ? 0 : 1
        } else if (item == 'include_init_point') {
          params['include_init_point'] = value ? 1 : 0
        } else if (item == 'include_seniority_point') {
          params['include_seniority_point'] = value ? 1 : 0
        } else {
          params[item] = value
        }
      }



      this.$http('get','/integral.php/token_create/generateEffective')
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data

            params['token'] = jsonData.data.token
            params['employee_id'] = jsonData.data.employee_id
            let url = self.serverdomain+'/integral.php/integral_excel/rank_by_employee?'+qs.stringify(params)
            window.open(url, '_blank')


          }
        })
        .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 if (item == 'include_manager') {
          params['exclude_manager'] = value ? 0 : 1
        } else if (item == 'include_init_point') {
          params['include_init_point'] = value ? 1 : 0
        } else if (item == 'include_seniority_point') {
          params['include_seniority_point'] = value ? 1 : 0
        } 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
            const 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)
        })
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.target_id == this.$store.getters.user_info.id) {
        return 'rank-mine'
      }
      return ''
    }
  },
  created() {
    this.loadWidgetData()
    this.loadTargetList()
    this.loadPointType()
    this.loadRankList()
    this.$nextTick(() => { // 点击body关闭筛选组件
      document.querySelector('#app').addEventListener('click', e => {
        if (this.show3) {
          this.show3 = false
        }
      })
    })
  }
}
</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;
}
.arrRotation {
  transform: rotate(180deg);
}
.treeActice {
  color: #606266;
}
.el-tree-node__content {
  height: 34px;
}
</style>
