<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-kpi__kpipublicopinion}">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-form-item label="部门">
            <el-cascader
              v-model="deptIdList"
              :options="options"
              :props="{ checkStrictly: true }"
              filterable
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form-item>
        <el-form-item label="考核周期起始月">
          <el-date-picker v-model="dataForm.monthYear"
              type="month" clearable placeholder="选择月"
              value-format="yyyy-MM"  format="yyyy-MM">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="部门类型" prop="deptTypeKey">
          <el-select v-model="dataForm.deptTypeKey" placeholder="部门类型" clearable>
            <el-option v-for="item in paramNameArr" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataListNew()">{{ $t('query') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addOrUpdateHandle()">{{ $t('add') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button 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-item>
          <el-button v-if="$hasPermission('kpi:kpipublicopinion:delete')" type="danger" @click="deleteHandle()">{{ $t('deleteBatch') }}</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="dataListLoading" :data="dataList" border @selection-change="dataListSelectionChangeHandle" style="width: 100%;">
        <el-table-column label="序号" header-align="center" align="center" width="50px">
            <template slot-scope="scope">
                {{scope.$index+1}}
            </template>
        </el-table-column>
        <el-table-column prop="deptName" label="部门名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="deptTypeKey" label="部门类型" header-align="center" align="center" :formatter = "stateFormat"></el-table-column>
        <el-table-column prop="monthYear" label="年月" header-align="center" align="center"></el-table-column>
        <el-table-column prop="publicityFoundation" label="宣传基础分数" header-align="center" align="center"></el-table-column>
        <el-table-column prop="innovationBreakthrough" label="创新突破分数" header-align="center" align="center"></el-table-column>
        <el-table-column prop="publicOpinionResponse" label="舆情应对分数" header-align="center" align="center"></el-table-column>
        <el-table-column prop="parentDeptNames" label="上级部门" header-align="center" align="center"></el-table-column>
        <el-table-column prop="allDeptNames" 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 type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">{{ $t('update') }}</el-button>
            <el-button v-if="$hasPermission('kpi:kpipublicopinion: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>
    </div>
  </el-card>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import AddOrUpdate from './kpipublicopinion-add-or-update'
import Cookies from 'js-cookie'
import qs from 'qs'
export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/kpi/kpipublicopinion/page',
        getDataListIsPage: true,
        deleteURL: '/kpi/kpipublicopinion',
        deleteIsBatch: true,
        exportTemplateURL: '/kpi/kpipublicopinion/exportTemplate'
      },
      dataForm: {
        id: '',
        deptTypeKey: '',
        monthYear: '',
        deptId: ''
      },
      // 所属机构配置
      deptIdList: [],
      options: [],
      paramNameArr: []
    }
  },
  components: {
    AddOrUpdate
  },
  watch: {
    'deptIdList': function (val) {
      if (val.length === 0) {
        this.dataForm.deptId = ''
      } else if (val.length > 0) {
        this.dataForm.deptId = this.deptIdList[val.length - 1]
      }
    }
  },
  created: function () {
    this.getOptions()
    this.getParamListInfo('dept_type')
    this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/kpi/kpipublicopinion/importManualScoreExcel?token=${Cookies.get('token')}`
  },
  methods: {
    getDataListNew () {
      this.page = 1
      this.getDataList()
    },
    stateFormat (row, column) {
      for (var i = 0; i < this.paramNameArr.length; i++) {
        if (row.deptTypeKey === this.paramNameArr[i].dictValue) {
          return this.paramNameArr[i].dictName
        }
      }
    },
    getOptions () {
      this.$http
        .get(`/sys/user/deptOptions/getAllDeptPartyByUser`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.options = res.data.options
        })
        .catch(() => {})
    },
    // 获取参数名称code下拉信息
    getParamListInfo (dictType) {
      this.$http.get(`/sys/dict/listSimple/` + dictType).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (dictType === 'dept_type') {
          this.paramNameArr = res.data
        }
      }).catch(() => {})
    },
    exportTemplate () {
      let remindInfo = ''
      let monthYear = this.dataForm.monthYear
      let deptTypeKey = this.dataForm.deptTypeKey
      let deptId = this.dataForm.deptId
      if (!deptId) {
        remindInfo += '部门、'
      }
      if (!monthYear) {
        remindInfo += '考核周期起始月、'
      }
      if (!deptTypeKey) {
        remindInfo += '部门类型、'
      }
      if (remindInfo.length > 0) {
        remindInfo = remindInfo.substring(0, remindInfo.length - 1)
        return this.$message.error(remindInfo + '不能为空!')
      }
      let params = qs.stringify({
        'token': Cookies.get('token'),
        'monthYear': monthYear,
        'deptTypeKey': deptTypeKey,
        'deptId': deptId
      })
      window.location.href = `${window.SITE_CONFIG['apiURL']}${this.mixinViewModuleOptions.exportTemplateURL}?${params}`
    },
    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()
        }
      })
    }
  }
}
</script>
