<template>
  <div style=" background-color: #fff; padding:15px; padding-top:0; height: 370px; overflow: hidden" v-loading="loading">

    <el-table
      v-show="tableData.length!=0"
      @sort-change="sort_change"
      ref="multipleTable"
      :data="tableData"
      :border="false"
      tooltip-effect="dark"
      style="width: 100%"
      :row-class-name="tableRowClassName"
      @filter-change="filterHandler"
      @selection-change="handleSelectionChange">


      <el-table-column prop="target_name" label="姓名"></el-table-column>

      <el-table-column prop="remark" :show-overflow-tooltip="true" label="备注" v-if="false"></el-table-column>
      <el-table-column label="分值">
        <template slot-scope="scope">
          <span v-bind:class="scope.row.point < 0 ? 'point-negative' : 'point-positive'"><i v-if="scope.row.point > 0">+</i>{{ scope.row.point }}</span>
        </template>
      </el-table-column>

      <el-table-column label="录入时间" sortable="custom" prop="create_time">
        <template slot-scope="scope">
          <i v-if="scope.row.create_time" class="el-icon-time"></i>
          <span>{{dateFormatter('','',scope.row.create_time)}}</span>
        </template>
      </el-table-column>

      <el-table-column label="事件时间" sortable="custom" prop="event_time">
          <template slot-scope="scope">
          <i v-if="scope.row.event_time" class="el-icon-time"></i>
          <span>{{dateFormatter('','',scope.row.event_time)}}</span>
        </template>
      </el-table-column>

    </el-table>


    <div v-if="tableData.length == 0" style="
    position: absolute;
    width: 100%;
    top: 50%;
    margin-top: -115px;
">
      <img v-if="tableData.length == 0" src="static/images/nodata.png" style="display: block; margin:0 auto;">
      <p style="color:#ccc; text-align: center">暂无积分事件</p>
    </div>


  </div>
</template>
<script>

  export default {
    data() {
      return {
        loading:false,
        profile: this.$store.getters.user_info,
        totalCount: 0,
        tableData: [],
        department_list:[],
        pageLimit:10,
        category_list:[],
        currentPage: 1,
        multipleSelection: [],
        filter: {
          keywords: '',
          target_id_set: [],
          category_id: [],
          point_type: 0,
          time_range: '',
          sortable:{prop:null,order:null}
        },
        categoryTree: [],
        employeeOptions: [],
        pointTypes: [],
        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()])
            }
          }]
        }
      }
    },
    methods: {
      sort_change(column, prop, order){
        //console.log(column)
        this.filter.sortable = column
        this.onFilterChanged()
      },
      tableRowClassName({row, rowIndex}) {
        if (row.target_id == this.$store.getters.user_info.id) {
          return 'rank-mine';
        }
        return '';
      },
      handleSizeChange(val) {
        this.pageLimit = val
        this.onFilterChanged()
      },



      filterHandler:function(value) {
        console.log(value)
        this.filter.category_id=(value['el-table_1_column_5'])
        this.onFilterChanged()
      },



      onFilterChanged: function () {
        this.currentPage = 1
        this.loadEventList()
      },
      modeTypeFormatter: function (value) {
        switch (value) {
          case 1:
            return '积分录入'
          case 2:
            return '积分申请'
          default:
            return ''
        }
      },
      reviewStatusFormatter: function (row, column, cellValue) {
        return cellValue == 1 ? '待审核' : '已生效'
      },
      dateFormatter: function (row, column, cellValue) {
        return this.$moment(cellValue * 1000).format('MM月DD日')
      },
      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)
        })
      },
      toggleSelection: function (rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      handleSelectionChange: function (val) {
        this.multipleSelection = val
      },
      //获取积分事件列表
      loadEventList: function () {


        if(this.$store.getters.user_info.manager_type == 0){
          this.filter.target_id_set = [this.$store.getters.user_info.id]
        }

        let params = {
          employee_id: this.profile.id,
          page: this.currentPage,
          interval: 7
        }
        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') {
            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 {
            params[item] = value
          }
        }
        var self = this
        self.loading = true
        this.$http('get','/integral.php/ajax_request_common/get_integral_events',params).then(function (response) {
          if (response.status == 200) {
            self.loading = false
            var jsonData = response.data
            try {
              self.department_list=jsonData.filter_list.department
              self.category_list=jsonData.filter_list.category
              self.totalCount = jsonData.total_count
              self.tableData = jsonData.list_data
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      changePage: function (current) {
        if (isNaN(current) || current < 1) {
          return false
        }
        this.loadEventList()
      },
      confirmDelete(eventId) {
        this.$confirm('确定要删除此积分事件吗?', '删除积分事件', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteItem(eventId)
        }).catch(() => {
          //console.log('已取消删除');
        })
      },
      confirmMultipleDelete() {
        if (this.multipleSelection.length < 1) {
          return false
        }
        this.$confirm('确定要删除选中的积分事件吗?', '批量删除积分事件', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let targetArr = []
          for (let index in this.multipleSelection) {
            targetArr.push(this.multipleSelection[index].id)
          }
          let targetIds = targetArr.join(",")
          this.deleteItem(targetIds, true)
        }).catch(() => {
          //console.log('已取消删除');
        })
      },
      deleteItem(eventId, isMultiple) {
        if (!eventId) {
          return false
        }
        isMultiple = isMultiple || false
        let url = ""
        let params = null
        if (isMultiple) {
          url = '/integral.php/ajax_request_common/delete_event_multiple'
          params = {
            ids: eventId
          }
        } else {
          url = '/integral.php/ajax_request_common/delete_event'
          params = {
            id: eventId
          }
        }
        var self = this
        this.$http('get',url,params).then(function (response) {
          let message = ""
          let status = 0
          if (response.status == 200) {
            var data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            switch (status) {
              case 1:
                message = "删除积分事件成功"
                break
              case -1:
                message = "表单参数错误"
                break
              default:
                message = data.info ? data.info : "删除积分事件失败"
            }
          } else {
            message = "服务器出现问题"
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.loadEventList()
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      //获取控件所需数据
      loadWidgetData: function () {
        var self = this
        this.$http('get','/integral.php/ajax_request_common/prepare_integral_options',{id: this.profile.id,category_tree: 1,employee_list: 1}).then(function (response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.categoryTree = jsonData.category_tree
              self.employeeOptions = jsonData.employee_list
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      //导出事件到Excel文件
      downloadSheet: function () {
        let params = {}
        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') {
            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 {
            params[item] = value
          }
        }
        let paramStrArr = new Array()
        for (let it in params) {
          paramStrArr.push(it + '=' + params[it])
        }
        let url = '/integral.php/excel_util/export_event_sheet?site_id='
          + this.profile.site_id + "&" + paramStrArr.join("&")
        window.open(url)
      }
    },
    created() {
      //this.loadWidgetData()
      //this.loadPointType()
      this.loadEventList()
    }
  }
</script>
<style>
  .el-pagination {
    text-align: center;
    margin-top: 15px;
  }
</style>
