<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-__manualscore}">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataListSearch()">
        <el-form-item>
          <el-form-item label="所属机构" label-width="120px">
            <el-cascader
              v-model="deptIdList"
              :options="options"
              :props="{ checkStrictly: true }"
              filterable
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form-item>
        <el-form-item label="考核周期起始月" label-width="120px">
          <el-date-picker v-model="dataForm.month"
              type="month" clearable placeholder="选择月"
              value-format="yyyy-MM"  format="yyyy-MM">
          </el-date-picker>
        </el-form-item>
        <br>
        <el-form-item label="被打分机构类型" label-width="120px">
          <el-select v-model="dataForm.deptType">
            <el-option
              v-for="item in kpiManualRuleList"
              :key="item.id"
              :label="item.deptName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="getDataListSearch()">{{ $t('query') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('manualscore-zlph:save')" type="primary" @click="addOrUpdateHandle()">{{ $t('add') }}</el-button>
        </el-form-item>
          <el-form-item>
          <el-button type="success" @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 type="index"
                         width="50"
                         label="序号" align="center"></el-table-column> 
        <el-table-column prop="deptName" label="被打分部门" header-align="center" align="center"></el-table-column>
        <el-table-column prop="month" :formatter="showMonthYMD" label="考核起始日" header-align="center" align="center" width="180"></el-table-column>
        <!-- <el-table-column prop="year" label="考核年度" header-align="center" align="center"></el-table-column> -->
        <el-table-column prop="scoreType" label="考核打分类型" header-align="center" align="center" width="120"></el-table-column>
        <el-table-column prop="creatorDeptName" label="打分的部门名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="score" label="得分" header-align="center" align="center" width="120"></el-table-column>
        <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">{{ $t('update') }}</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>
    </div>
  </el-card>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import AddOrUpdate from './manualscore-add-or-update-zlph'
import Cookies from 'js-cookie'
import qs from 'qs'
export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/kpi/manualscore-zlph/page',
        getDataListIsPage: true,
        deleteURL: '/kpi/manualscore-zlph',
        deleteIsBatch: true,
        exportTemplateURL: '/kpi/manualscore-zlph/exportTemplate'
      },
      dataForm: {
        id: '',
        deptType: 'street_party', // 被打分的机构类型
        month: '',
        deptId: '',
        scoreType: '0' // 考核打分类型 0-月，1-年
      },
      upLoadUrl: '',
      // 所属机构配置
      deptIdList: [],
      options: [],
      kpiManualRuleList: [
        {
          'id': 'street_party',
          'deptName': '街道'
        },
        {
          'id': 'community_party',
          'deptName': '社区'
        },
        {
          'id': 'grid_party',
          'deptName': '网格'
        }
      ]
    }
  },
  components: {
    AddOrUpdate
  },
  created () {
    this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/kpi/manualscore-zlph/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: {
    // 导出录入模板
    exportTemplate () {
      let month = this.dataForm.month
      let deptType = this.dataForm.deptType
      let scoreType = this.dataForm.scoreType
      let deptId = this.dataForm.deptId
      let params = qs.stringify({
        'token': Cookies.get('token'),
        'month': month,
        'deptType': deptType,
        'scoreType': scoreType,
        'deptId': deptId
      })
      // let paramsJson = {
      //   'month': month, 'deptType': deptType, 'scoreType': scoreType
      // }
      if (!deptType) {
        return this.$message.error('考核规则不能为空')
      }
      if (!month) {
        return this.$message.error('考核周期起始月不能为空')
      }
      // 表格检查
      // this.$http.get(`/kpi/manualscore-zlph/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.exportTemplateURL}?${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()
        }
      })
    },
    showMonthYMD (row, column) {
      return row.month.substring(0, 10)
    }
  },
  watch: {
    'deptIdList': function (val) {
      if (val.length === 0) {
        this.dataForm.deptId = ''
      } else if (val.length > 0) {
        this.dataForm.deptId = this.deptIdList[val.length - 1]
      }
    }
  }
}
</script>
