<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-kpi__kpimanualscore}">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item label="所属机构">
          <el-cascader
            v-model="deptIdList"
            :options="options"
            :props="{ checkStrictly: true }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="考核规则名称">
          <el-select clearable v-model="dataForm.ruleId">
            <el-option
              v-for="item in kpiManualRuleList"
              :key="item.id"
              :label="item.ruleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考核周期起始月">
          <el-date-picker v-model="dataForm.scoreStartDate"
              type="month" clearable placeholder="选择月"
              value-format="yyyy-MM"  format="yyyy-MM">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">{{ $t('query') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('kpi:kpimanualscore:save')" type="primary" @click="addOrUpdateHandle()">{{ $t('add') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('kpi:kpimanualscore:delete')" type="danger" @click="deleteHandle()">{{ $t('deleteBatch') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('kpi:kpimanualscore:export')" type="info" @click="exportTemplate()">导出录入模板</el-button>
        </el-form-item>
        <el-form-item>
          <el-upload class="upload-demo"
                     ref="upload"
                     v-loading="dataListLoading"
                     :action="uploadUrl"
                     :limit="1"
                     :on-success='uploadSuccess'
                     :on-error='errorExceed'
                     accept=".xls,.xlsx">
            <el-button type="primary">导入打分结果</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-table v-loading="dataListLoading" :data="dataList" border @selection-change="dataListSelectionChangeHandle" style="width: 100%;">
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column prop="allDeptNames" label="部门名称" header-align="center" align="center"  min-width="300" show-overflow-tooltip></el-table-column>
        <el-table-column prop="ruleName" width="110" label="考核规则名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="kpiCycle" label="考核周期" header-align="center" align="center"  width="100" :formatter="showKpiCycleFormatter"></el-table-column>
        <el-table-column prop="scoreStartDate" width="120" label="考核起始日" header-align="center" align="center"></el-table-column>
        <el-table-column prop="scoreEndDate" width="120" label="考核终止日" header-align="center" align="center"></el-table-column>
        <el-table-column prop="score" label="得分" header-align="center" align="center"  width="50"></el-table-column>
        <el-table-column prop="createdTime" width="180" label="打分时间" header-align="center" align="center"></el-table-column>
        <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="150">
          <template slot-scope="scope">
            <el-button v-if="$hasPermission('kpi:kpimanualscore:update')" type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">{{ $t('update') }}</el-button>
            <el-button v-if="$hasPermission('kpi:kpimanualscore:delete')" type="text" size="small" @click="deleteHandle(scope.row.id)">{{ $t('delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="limit"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="pageSizeChangeHandle"
        @current-change="pageCurrentChangeHandle">
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
      <!-- 错误信息 -->
      <el-dialog :visible.sync="faultDataVisible" title="请修改后重新提交">
        <el-table :data="errordataList" border style="width: 100%;">
          <el-table-column prop="rowNum" width="50" label="行" header-align="center" align="center"></el-table-column>
          <el-table-column prop="errorMsg" label="错误信息" header-align="center" align="center"></el-table-column>
        </el-table>
        <template slot="footer">
          <el-button type="primary" @click="faultDataVisible = false">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import AddOrUpdate from './manualScore-add-or-update'
import Cookies from 'js-cookie'
import qs from 'qs'
export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/kpi/manualScore/page',
        getDataListIsPage: true,
        deleteURL: '/kpi/manualScore',
        deleteIsBatch: true,
        exportURL: '/kpi/manualScore/exportTemplate'
      },
      dataForm: {
        ruleId: '',
        scoreStartDate: ''
      },
      upLoadUrl: '',
      faultDataVisible: false,
      errordataList: [],
      kpiManualRuleList: [], // 已绑定手动打分的考核规则列表
      kpiCycleList: [], // 考核周期字典表值
      // 所属机构配置
      deptIdList: [],
      options: [],
      streetList: [],
      communityList: [],
      gridList: []
    }
  },
  components: {
    AddOrUpdate
  },
  created () {
    this.getKpiManualRule()
    this.getKpiCycleList()
    this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/kpi/manualScore/importManualScoreExcel?token=${Cookies.get('token')}`
    // 所属机构创建
    this.$http
      .get(`/sys/user/deptOptions/getByLoginUser`)
      .then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.options = res.data.options
      })
      .catch(() => {})
  },
  // 已绑定手动打分的考核规则
  methods: {
    getKpiManualRule () {
      this.$http.get(`/kpi/rule/getKpiManualRule/`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.kpiManualRuleList = res.data
      }).catch(() => { })
    },
    // 获取绩效考核周期下拉框集合
    getKpiCycleList () {
      this.$http.get(`/sys/dict/listSimple/kpi_cycle`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.kpiCycleList = res.data
      }).catch(() => { })
    },
    showKpiCycleFormatter: function (row, column) {
      if (row.kpiCycle) {
        let dict = this.kpiCycleList.filter(item => item.dictValue === row.kpiCycle)[0]
        if (dict) {
          return dict.dictName
        }
      }
      return ''
    },
    // 导出录入模板
    exportTemplate () {
      let scoreStartDate = this.dataForm.scoreStartDate
      let ruleId = this.dataForm.ruleId
      let params = qs.stringify({
        'token': Cookies.get('token'),
        'scoreStartDate': scoreStartDate,
        'ruleId': ruleId
      })
      let paramsJson = {
        'scoreStartDate': scoreStartDate, 'ruleId': ruleId
      }
      if (!ruleId) {
        return this.$message.error('考核规则不能为空')
      }
      if (!scoreStartDate) {
        return this.$message.error('考核周期起始月不能为空')
      }
      this.$http.get(`/kpi/manualScore/checkExportTemplate`, { params: paramsJson }).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        } else {
          window.location.href = `${window.SITE_CONFIG['apiURL']}${this.mixinViewModuleOptions.exportURL}?${params}`
        }
      }).catch(() => { })
    },
    errorExceed (file, fileList) {
      this.$message.error('上传失败请重试')
    },
    uploadSuccess (response, file, fileList) {
      this.dataListLoading = false
      this.$refs.upload.clearFiles()
      if (response.code !== 0 || (response.data !== null && response.data.length > 0)) {
        this.errordataList = response.data
        if (this.errordataList != null && this.errordataList.length > 0) {
          this.faultDataVisible = true
        } else {
          this.$message.error(response.msg)
        }
        return
      }
      this.$message({
        message: this.$t('prompt.success'),
        type: 'success',
        duration: 500,
        onClose: () => {
          this.getDataList()
        }
      })
    }
  },
  watch: {
    'deptIdList': function (val) {
      if (val.length === 0) {
        this.dataForm.streetId = ''
        this.dataForm.communityId = ''
        this.dataForm.gridId = ''
      }
      if (val.length === 1) {
        this.dataForm.streetId = this.deptIdList[0]
        this.dataForm.communityId = ''
        this.dataForm.gridId = ''
      }
      if (val.length === 2) {
        this.dataForm.streetId = this.deptIdList[0]
        this.dataForm.communityId = this.deptIdList[1]
        this.dataForm.gridId = ''
      }
      if (val.length === 3) {
        this.dataForm.streetId = this.deptIdList[0]
        this.dataForm.communityId = this.deptIdList[1]
        this.dataForm.gridId = this.deptIdList[2]
      }
    }
  }
}
</script>
