<template>
  <div style=" background-color: #fff; padding:15px;">
    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">

      <el-select
        class="gap-right-8 first-element-btn"
        clearable
        filterable
        placeholder="选择奖扣对象进行筛选"
        v-model="filter.target_id"
        @change="onFilterChanged">
        <el-option
          v-for="item in employeeList"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <el-date-picker
        class="gap-right-8"
        v-model="filter.time_range"
        type="daterange"
        value-format="timestamp"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="instantPickerOptions"
        @change="onFilterChanged">
      </el-date-picker>
      <div class="gap-right-8" style="display:inline-block; width:220px;">
        <el-input
          placeholder="输入关键词查找"
          ref="search-bar"
          v-model="filter.keywords"
          class="input-with-select"
          @keyup.enter.native="onFilterChanged">
          <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
        </el-input>
      </div>
    </div>
    <el-table
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      :border="false"
      tooltip-effect="dark"
      style="width: 100%">
      <el-table-column label="类型">
        <template slot-scope="scope">
          <div>{{modeTypeFormatter('','',scope.row.mode_type,scope.row.task_id)}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="target_name" label="姓名"></el-table-column>
      <el-table-column prop="recorder_name" label="录入者"></el-table-column>
      <el-table-column prop="category_path" label="积分分类"></el-table-column>


      <el-table-column label="附件">
        <template slot-scope="scope">
          <div>
            <a
              style="display: block; color:#409EFF; text-decoration: underline;"
              v-for="item in scope.row.file_list"
              @click="fileProview(item.url, scope.row.file_list, scope.row.id)"
            >{{item.name}}</a>
          </div>

          <div style="display:none;">
            <img
              v-for="(item,index) in scope.row.file_list"
              v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(item.url.split('.')[1]) >= 0"
              :src="serverdomain+item.url"
              :preview="scope.row.id"
              :preview-text="item.name"
            >
          </div>
        </template>
      </el-table-column>


      <el-table-column label="积分规则">
        <template slot-scope="scope">
          <div v-if="scope.row.rule_name && scope.row.item_content">
            {{ scope.row.rule_name }}：<br/>
            {{ scope.row.item_content }}
          </div>
          <div v-else>未指定</div>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="多人审批">
        <template slot-scope="scope">
            <span v-for="review_item of scope.row.review_list" :key="review_item.reviewer_id" v-if="review_item.status === 0" style="color: #aaa">
              <el-tooltip :content="review_item.name+'待审核'" placement="top">
                <span>
                  {{review_item.name+' '}}
                </span>
              </el-tooltip>
            </span>
            <span v-for="review_item of scope.row.review_list" :key="review_item.reviewer_id" v-if="review_item.status === 1" style="color: green">
                  <el-tooltip :content="review_item.name+'审核通过，得分'+review_item.point+'分'" placement="top">
                   <span>
                    {{review_item.name+' '}}
                   </span>
                 </el-tooltip>
            </span>
            <span v-for="review_item of scope.row.review_list" :key="review_item.reviewer_id" v-if="review_item.status === -1" style="color: red">
                <el-tooltip :content="review_item.name+'驳回,原因:'+review_item.comment" placement="top">
                <span>
                  {{review_item.name+' '}}
                </span>
               </el-tooltip>
            </span>

          <!-- <span v-bind:class="scope.row.point < 0 ? 'point-negative' : 'point-positive'">{{ scope.row.point }}</span> -->
        </template>
      </el-table-column>
      <el-table-column prop="point_type" label="积分">

        <template slot-scope="scope">
          <div v-html="pointTypeFormatter(scope.row)"></div>
        </template>

      </el-table-column>
      <el-table-column label="事件日期">
        <template slot-scope="scope">
          <i v-if="scope.row.event_time" class="el-icon-time"></i>
          <span v-html="dateFormatter(scope.row,'',scope.row.event_time)"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="sendReviewRecallRequest(scope.row.id)"
                     :disabled="checkExpire(scope.row.finish_time)">撤消
          </el-button>
        </template>
      </el-table-column>
    </el-table>
     <el-pagination
      background
      @size-change="handleSizeChange"

      layout="total,sizes, prev, pager, next"
      :page-size="pageLimit"
      :page-sizes="[10, 20, 50, 100]"
      :total="totalCount"
      :current-page.sync="currentPage"
      @current-change="changePage"
    ></el-pagination>
  </div>
</template>
<script>
  import Vue from 'vue'
  import preview from 'vue-photo-preview'
  import 'vue-photo-preview/dist/skin.css'
  Vue.use(preview, {
    tapToClose: false
  })
  export default {

    data() {
      return {
        profile: this.$store.getters.user_info,
        totalCount: 0,
        currentPage: 1,
        pageLimit: 10,
        tableData: null,
        employeeList: [],
        filter: {
          keywords: '',
          target_id: '',
          time_range: []
        },
        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()])
            }
          }]
        }
      }
    },
    methods: {
      handleSizeChange(val) {
        this.pageLimit = val
        this.onFilterChanged()
      },
      reviewTip() {

      },
      onFilterChanged: function() {
        this.currentPage = 1
        this.loadReviewList()
      },
      modeTypeFormatter: function(row, column, cellValue, task_id) {
        switch (cellValue) {
          case 1:
            return '积分录入'
        case 2:
            if (task_id) { return '任务审核' }
            return '积分申请'
        default:
            return ''
      }
      },
      fileProview(url, list, key) {
        const $ext_list = ['doc', 'docx', 'pptx', 'xls', 'xlsx', 'ppt', 'txt']
        const $ext_name = url.split('.')[1]
        if ($ext_list.indexOf($ext_name) >= 0) {
          console.log(
            'https://view.officeapps.live.com/op/view.aspx?src=' +
            this.serverdomain +
            url
          )
          window.open(
            'https://view.officeapps.live.com/op/view.aspx?src=' +
            this.serverdomain +
            url,
            '_blank'
          )
        }
        const $ext_list1 =  ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']
        const $ext_name1 = url.split('.')[1]
        if ($ext_list1.indexOf($ext_name1) >= 0) {
          console.log(this.serverdomain + url)

          let ii = 0
          for (const i in list) {
            if (
               ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG'].indexOf(list[i].url.split('.')[1]) >=
              0
            ) {
              if (list[i].url == url) {
                console.log(ii)
                this.openPhotoSwipe(
                  ii,
                  document.querySelectorAll('img[preview="' + key + '"]')
                )

                return
              }
              ii++
            }
          }
        }
      },
      pointTypeFormatter: function(row) {
        for (let index = 0; index < this.pointTypes.length; index++) {
          const pointType = this.pointTypes[index]

          console.log(row, pointType.value)

          if (row.point_type == pointType.value) {
            if(row.point > 0){
              return '<span style="color:#f00;">+' +row.point +pointType.label+ '</span>'
            }else if(row.point < 0){
              return '<span style="color:#1a8dff;">' +row.point +pointType.label+ '</span>'
            }else{
              return row.point +pointType.label
            }
          }
        }
        return ''
      },
      task_status: function(time){
        if(time >= 0 && time <= 60){
          return '按时完成';
        }else if(time > 60){
          return '提前'+(time/3600).toFixed(2)+'小时';
        }else if(time < 0 && time > -60){
          return '按时完成'
        }else if(time < -60){
          return '延期'+(Math.abs(time)/3600).toFixed(2)+'小时'
        }
      },

      dateFormatter: function(row, column, cellValue) {
        let ret = this.$moment(cellValue * 1000).format('MM月DD日')

        if(row.task_id > 0){
          ret = ret + '<br/>('+this.task_status(row.task_expiretime)+')'
        }
        return ret
      },
      checkExpire: function(timestamp) {
        if (timestamp && !isNaN(timestamp)) {
          if (new Date().getTime() - timestamp * 1000 < 15 * 60 * 60 * 1000) {
            return false
          }
        }
        return true
      },
      changePage(current) {
        if (isNaN(current) || current < 1) {
          return false
        }
        this.loadReviewList()
      },
      loadReviewList: function() {
        const params = {
          reviewer_id: this.profile.id,
          status: 1,
          page: this.currentPage,
          interval: this.pageLimit
        }
        for (const item in this.filter) {
          const value = this.filter[item]
          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/ajax_request_common/get_review_list',params).then(function(response) {
          if (response.status == 200) {
            self.loading = false
            var jsonData = response.data
            try {
              self.totalCount = jsonData.total_count
              self.tableData = jsonData.list_data
            } 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)
        })
      },
      // 获取员工列表
      loadEmployeeList: function() {
        var self = this
        this.$http('get','/integral.php/ajax_request_common/prepare_integral_options', {
            id: this.profile.id,
            employee_list: 1
          }).then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.employeeList = jsonData.employee_list
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function(error) {
          console.log(error)
        })
      },
      sendReviewRecallRequest: function(reviewId) {
        const params = {
          id: reviewId
        }
        var self = this
        this.$http('post','/integral.php/ajax_request_common/review_recall', params,'','',
          {transformRequest: [(data) => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]))
            }
            return paramArray.join('&')
          }]},
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded'
          // }
        ).then(function(response) {
          let message = ''
          let status = 0
          if (response.status == 200) {
            const 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.currentPage = 1
            self.loadReviewList()
            self.$emit('update-count-indicator')
          }
        }).catch(function(error) {
          console.log(error)
        })
      }
    },
    created() {
      this.loadPointType()
      this.loadEmployeeList()
      this.loadReviewList()
    }
  }
</script>

<style>
  .el-pagination {
    text-align: center;
    margin-top: 15px;
  }
</style>
