<template>
  <div style=" background-color: #fff; padding:15px;">
    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
      <el-button
        class="first-element-btn"
        v-if="profile.manager_type > 1"
        :disabled="multipleSelection.length < 1"
        @click="confirmMultipleDelete"
        type="primary"
        plain
      >批量删除</el-button>
      <el-select
        v-show="(settings.data_permission.indexOf('dept') >= 0 && profile.manager_type == 0) || (profile.manager_type > 0) || (settings.data_permission.indexOf('all') >= 0 && profile.manager_type == 0)"
        v-model="filter.target_id_set"
        filterable
        multiple
        :multiple-limit="3"
        placeholder="选择员工进行筛选（最多3个）"
        @change="onFilterChanged"
        class="gap-right-8"
        style="width:250px;"
      >
        <el-option
          v-for="item in employeeOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>

      <el-cascader
        clearable
        :options="dept_tree"
        change-on-select
        v-model="department_id"
        @change="onFilterChanged"
        placeholder="选择部门"
        style="width:120px"
        class="gap-right-8"
      ></el-cascader>

      <el-cascader
        v-if="false"
        clearable
        :options="categoryTree"
        change-on-select
        v-model="filter.category_id"
        @change="onFilterChanged"
        placeholder="分类筛选"
        style="width:120px"
        class="gap-right-8"
      ></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"
        class="gap-right-8"
        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
        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:260px;">
        <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>
      <el-button @click="downloadSheet" type="primary" plain>Excel导出</el-button>

      <IntegralCreateReviewBtn v-if="profile.manager_type > 1" :btn_type="1"></IntegralCreateReviewBtn>


    </div>
    <el-table
      @sort-change="sort_change"
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      :border="false"
      tooltip-effect="dark"
      style="width: 100%"
      @filter-change="filterHandler"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="42"
        v-if="profile.manager_type > 1"
        :selectable="selectable"
      ></el-table-column>
      <el-table-column label="类型">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.task_id!=null">任务积分</span>
            <span v-else>{{ modeTypeFormatter(scope.row.mode_type) + (scope.row.recorder_name ? '（' +
            scope.row.recorder_name + '）' : '') }}</span>
          </div>
          <div v-if="scope.row.reviewer_name">{{ '审核：' + scope.row.reviewer_name }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="target_name" label="姓名"></el-table-column>
      <el-table-column
        prop="dept_name"
        label="部门"
        column-key="dept"
        :filterMultiple="false"
        :filters="department_list"
      ></el-table-column>
      <el-table-column
        prop="category_path"
        label="积分分类"
        column-key="category"
        :filterMultiple="false"
        :filters="category_list"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <!-- get_integral_events -->
      <el-table-column label="附件">
        <template slot-scope="scope">
          <div>
            <a
              style="display: block; color:#409EFF; text-decoration: underline;"
              v-for="(item,idx) in scope.row.file_list"
              :key="idx"
              @click="fileProview(item.url, scope.row.file_list, scope.row.id, item.name)"
            >{{item.name}}</a>
          </div>

          <div style="display:none;">
            <img
              v-for="(item,index) in scope.row.file_list"
              :key="index"
              v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(item.url.split('.')[1]) >= 0"
              :src="item.url"
              :preview="scope.row.id"
              :preview-text="item.name"
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column label="积分规则" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div
            v-if="scope.row.rule_item_id > 0"
          >{{ scope.row.rule_name }}：{{ scope.row.item_content }}</div>
          <div v-if="scope.row.rule_item_id == 0">无</div>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="分值" sortable="custom" prop="point">
        <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 prop="create_time" sortable="custom" label="录入日期" :formatter="dateFormatter">
        <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 prop="event_time" sortable="custom" label="事件日期" :formatter="dateFormatter">
        <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-column label="操作" v-if="profile.manager_type > 1">
        <template slot-scope="scope">
          <el-button
            type="text"
            :disabled="scope.row.mode_type==0"
            @click="confirmDelete(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="total,sizes,prev, pager, next"
      :page-size="pageLimit"
      :page-sizes="[10, 20, 50, 100]"
      :total="totalCount"
      :current-page.sync="currentPage"
      @size-change="handleSizeChange"
      @current-change="changePage"
    ></el-pagination>
  </div>
</template>
<script>
import Vue from 'vue'
import preview from 'vue-photo-preview'
import IntegralCreateReviewBtn from '@/views/dashboard/components/IntegralCreateReviewBtn'
import 'vue-photo-preview/dist/skin.css'
Vue.use(preview, {
  tapToClose: false
})
export default {
  components:{
    IntegralCreateReviewBtn
  },
  data() {

    return {
      textTip: '选择积分分类筛选',
      show3: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      loading: false,
      profile: this.$store.getters.user_info,
      settings: this.$store.getters.system_setting,
      totalCount: 0,
      tableData: null,
      department_list: [],
      pageLimit: 10,
      category_list: [],
      currentPage: 1,
      multipleSelection: [],
      department_id: [],
      filter: {
        keywords: '',
        target_id_set: [],
        category_id: [],
        point_type: 0,
        dept_id: 0,
        time_range: '',
        sortable: { prop: null, order: null }
      },
      categoryTree: [],
      employeeOptions: [],
      pointTypes: [],
      dept_tree: [],
      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: {
    sort_change(column, prop, order) {
      // console.log(column)
      this.filter.sortable = column
      this.onFilterChanged()
    },
    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.category_id = param.checkedKeys
      this.onFilterChanged()
      this.show3 = false
    },
    fileProview(url, list, key,name) {
    // const $ext_name = name.split('.')[1]
    //   const $ext_list1 =  ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']
      // if( $ext_list1.indexOf($ext_name) >= 0) {
         window.open(
            url,
        )
      // }
    },
    handleSizeChange(val) {
      this.pageLimit = val
      this.onFilterChanged()
    },
    filterHandler: function(value) {
      if (typeof value.category !== 'undefined' && value.category.length == 0) {
        this.filter.category_id = []
      }
      if (typeof value.category !== 'undefined' && value.category.length > 0) {
        this.filter.category_id = value.category
      }

      if (typeof value.dept !== 'undefined' && value.dept.length == 0) {
        this.filter.dept_id = 0
      }
      if (typeof value.dept !== 'undefined' && value.dept.length > 0) {
        this.filter.dept_id = value.dept[0]
      }

      this.onFilterChanged()
    },

    selectable(row, index) {
      if (row.mode_type > 0) {
        return true
      } else {
        return false
      }
    },

    onFilterChanged: function() {
      this.currentPage = 1
      this.loadEventList()
    },
    modeTypeFormatter: function(value) {
      switch (value) {
        case 0:
          return '系统积分'
        case 1:
          return '积分录入'
        case 2:
          return '积分申请'
        case 3:
          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) {
            const 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() {
      const params = {
        employee_id: this.profile.id,
        page: this.currentPage,
        interval: this.pageLimit
      }

      if (this.department_id.length > 0) {
        this.filter['dept_id'] = this.department_id[
          this.department_id.length - 1
        ]
      } else {
        this.filter['dept_id'] = 0
      }

      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') {
          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/ajax_request_common/get_integral_events',params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false
            var jsonData = response.data
            try {
              if (self.profile.manager_type > 1) {
                self.department_list = jsonData.filter_list.department
              }

              self.category_list=jsonData.filter_list.category
              for(let key in jsonData.list_data){
                 if(jsonData.list_data[key].file_list && jsonData.list_data[key].file_list.length>0){
                  jsonData.list_data[key].file_list.map(a => {
                    a.url = a.url.replace(self.serverdomain, '', a.url)

                    return a
                  })
                 }

              }

              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(() => {
          const targetArr = []
          for (const index in this.multipleSelection) {
            targetArr.push(this.multipleSelection[index].id)
          }
          const 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,
            dept_tree: 1
          })
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.categoryTree = jsonData.category_tree
              self.employeeOptions = jsonData.employee_list

              self.dept_tree = jsonData.dept_tree

              if (
                (self.settings.data_permission.indexOf('dept') >= 0 &&
                  self.profile.manager_type == 0 &&
                  self.profile.is_creator == 0) ||
                (self.profile.manager_type > 0 && self.profile.is_creator == 0)
              ) {
                self.filter.target_id_set = []
                self.filter.target_id_set.push(self.profile.id)
              }

              self.loadEventList()
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 导出事件到Excel文件
    downloadSheet: function() {
      const params = {}

      let category_ids = ""
      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') {
          if (!value || value.length == 0) {
            continue
          }
          // params[item] = value[value.length - 1]
          // console.log('params[item]-------------???')
          // console.log(params[item])
          // console.log(item)
          // console.log(value)
          //params[item] = JSON.stringify(value)

          for(let i = 0; i < value.length; i++){
            category_ids += "&category_id[]="+value[i];
          }
          //console.log(category_ids);return;

        } 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
        }
      }
      const paramStrArr = new Array()
      console.log('params-----------')
      console.log(params)
      for (const it in params) {
        paramStrArr.push(it + '=' + params[it])
      }
      console.log('paramStrArr--------???')
      console.log(paramStrArr)
      const url =
        this.serverdomain +
        '/integral.php/excel_util/export_event_sheet?site_id=' +
        this.profile.site_id +
        '&' +
        paramStrArr.join('&')+category_ids
      window.open(url)
      console.log('url-----------------???')
      console.log(url)
    }
  },
  created() {
    if (this.$route.params.currentMonth) {
      // 获取本月事件
      const now = new Date()
      const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
      const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
      this.filter.time_range = [startDate.getTime(), endDate.getTime()]
    }
    if (
      (this.settings.data_permission.indexOf('dept') >= 0 &&
        this.profile.manager_type == 0) ||
      (this.profile.manager_type > 0 && this.profile.is_creator == 0)
    ) {
      this.filter.target_id_set = [this.profile.id]
    }
    if (this.profile.manager_type < 2) {
      this.dept_id = this.profile.dept_id
    }
    this.loadWidgetData()
    this.loadPointType()
    this.$nextTick(() => {
      document.querySelector('#app').addEventListener('click', () => {
        if (this.show3) {
          this.show3 = false
        }
      })
    })
  },
  mounted() {}
}
</script>
<style>
.el-pagination {
  text-align: center;
  margin-top: 15px;
}
.arrRotation {
  transform: rotate(180deg);
}
.treeActice {
  color: #606266;
}
.el-tree-node__content {
  height: 34px;
}
</style>
