
<template>
  <div class="content-container">
    <el-row class="tool-bar">
      <el-col :span="6" class="left">
        <div class="content-title">
          <span>{{ title }}</span>
        </div>
      </el-col>
      <el-col :span="10">
        <span class="tip">说明：红色未达标，黄色表示未评价。</span>
      </el-col>
      <el-col :span="8" class="right flex-rt">
        <p class="current-score"> 当月分值: <span> {{ hosScore }} </span>分</p>
        <el-button type="primary" icon="el-icon-document" size="mini" @click="handleExport">导出</el-button>
        <el-button style="margin-left: 10px;" type="primary" icon="el-icon-printer" size="mini" @click="handlePrint">打印</el-button>
      </el-col>
    </el-row>

    <el-row id="print_view" class="content-body storyTable">
      <el-table v-loading="listLoading" :data="dataList" border height="calc(100vh - 150px)" :span-method="objectSpanMethod">
        <el-table-column prop="targetTitle" label="评价指标" width="100">
          <template v-slot="{row}">
            <span>{{ row.targetTitle }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="itemTitle" label="评价项目" width="100">
          <template v-slot="{row}">
            <span>{{ row.itemTitle }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="pointContent" label="评价内容">
          <template v-slot="{row}">
            <span>{{ row.pointContent }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="pointScore" label="最高分值" width="80" align="center">
          <template v-slot="{row}">
            <span>{{ row.pointScore }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="scoreCriterion" label="考评方法" width="160">
          <template v-slot="{row}">
            <span>{{ row.scoreCriterion }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="assessTime" label="评价时间" width="160" header-align="center" align="center">
          <template v-slot="{row}">
            <span v-if="row.assessTime" :class="row.assessTime">{{ row.assessTime }}</span>
            <span v-else :class="row.assessTime">-</span>
          </template>
        </el-table-column>

        <el-table-column prop="hosScore" label="得分" width="80" header-align="center" align="center">
          <template v-slot="{row}">
            <span v-if="row.isAssessed > 0" class="hosScore" :class="row|hosScoreClass">{{ row.hosScore }}</span>
            <span v-else class="notappraise">未评价</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" header-align="center" align="center">
          <template v-slot="{row,$index}">
            <el-button v-if="conditions.year === curYear && conditions.month === curMonth" type="primary" size="mini" @click="handleAssess(row,$index)">评价</el-button>
            <el-button size="mini" type="info" @click="handleViewRecord(row)">评价记录</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <PointAssess ref="PointAssess" title="自评" @formSuccess="formSuccess" />
    <AssessRecord ref="AssessRecord" title="评价记录" />
  </div>
</template>
<script>

import PointAssess from '@/views/hos/components/PointAssess'
import AssessRecord from '@/views/hos/components/AssessRecord'
import commonMethodMixin from '@/mixin/commonMethodMixin'
import { getAssessByList, getAssessById } from '@/api/hos/hosAssessApi'
import { getMonthScoreOfStory } from '@/api/hos/hosStatisApi'
export default {
  name: 'AssessList',
  components: {
    PointAssess,
    AssessRecord
  },
  filters: {
    isCurrentMonth(time) {
      if (!time) return
      return new Date(time).getMonth() === new Date().getMonth() ? 'isCurrentMonth' : 'isNotCurrentMonth'
    },
    hosScoreClass(row) {
      const pointScore = row.pointScore
      const hosScore = row.hosScore
      if (!hosScore) return ''
      const isStandards = hosScore >= pointScore * 0.6
      if (isStandards) return 'standards'
      return 'belowStandards'
    }
  },
  mixins: [commonMethodMixin],
  data() {
    return {
      title: '',
      listLoading: false,
      total: 0,
      dataList: [],
      spanArr: [],
      position: 0,
      spanArr2: [],
      position2: 0,
      hosScore: 0,
      conditions: {
        year: 2022,
        month: 9,
        storyId: 1,
        keywords: ''
      },
      curYear: 0,
      curMonth: 0,
      handleAssessRows: undefined
    }
  },
  mounted() {
    var now = new Date()
    this.curYear = now.getFullYear()
    this.curMonth = now.getMonth() + 1
  },
  methods: {
    loadData(data) {
      if (!data) return
      this.conditions.year = data.year
      this.conditions.month = data.month
      this.conditions.storyId = data.storyId
      this.getData()
      this.getMonthScore()
    },
    getMonthScore() {
      getMonthScoreOfStory(this.conditions.year, this.conditions.month, this.conditions.storyId).then((res) => {
        if (res.data) {
          this.hosScore = res.data.hosScore
          return
        }
        this.hosScore = 0
      })
    },
    getData() {
      this.listLoading = true
      this.position = 0
      this.position2 = 0
      this.dataList = []
      this.$set(this, 'spanArr', [])
      this.$set(this, 'spanArr2', [])
      getAssessByList(this.conditions).then((resp) => {
        this.listLoading = false
        const { code, msg, data, total } = resp
        if (code === 200) {
          this.total = total
          if (Array.isArray(data) && data.length > 0) {
            this.dataList = this.sortArray(data, 'targetId')
            this.rowspan('targetId')
            this.rowspan2('itemId') // amount1列合并信息缓存
          }
        } else {
          this.$message.error(msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (columnIndex === 1) {
        return {
          rowspan: this.spanArr2[rowIndex],
          colspan: this.spanArr2[rowIndex] > 0 ? 1 : 0
        }
      }
    },
    rowspan(name) {
      this.dataList.forEach((item, index) => {
        if (index === 0) {
          this.spanArr.push(1)
          this.position = 0
        } else {
          if (this.dataList[index][name] === this.dataList[index - 1][name]) {
            this.spanArr[this.position] += 1
            this.spanArr.push(0)
          } else {
            this.spanArr.push(1)
            this.position = index
          }
        }
      })
    },
    rowspan2(name) {
      this.dataList.forEach((item, index) => {
        if (index === 0) {
          this.spanArr2.push(1)
          this.position2 = 0
        } else {
          if (this.dataList[index][name] === this.dataList[index - 1][name]) {
            this.spanArr2[this.position2] += 1
            this.spanArr2.push(0)
          } else {
            this.spanArr2.push(1)
            this.position2 = index
          }
        }
      })
    },
    sortArray(ary, key) {
      return ary.reduce((total, next) => {
        const index = total.findIndex((item, index, self) => {
          return item[key] === next[key]
        })
        return index === -1 ? total.push(next) && total : total.splice(index, 0, next) && total
      }, [])
    },

    // 结果评估
    handleViewRecord(row) {
      this.$nextTick(() => {
        this.$refs['AssessRecord'].handler(row)
      })
    },

    // 结果评估
    handleAssess(row, index) {
      this.handleAssessRows = { row, index }
      this.$nextTick(() => {
        this.$refs['PointAssess'].handler(row)
      })
    },

    formSuccess() {
      this.updateRow()
      this.$emit('actionUpdate')
    },
    updateRow() {
      var year = this.conditions.year
      var month = this.conditions.month
      const { storyId, targetId, itemId, pointId } = this.handleAssessRows.row
      const index = this.handleAssessRows.index
      getAssessById(year, month, storyId, targetId, itemId, pointId).then((res) => {
        this.$set(this.dataList, index, res.data)
        this.getMonthScore()
      })
    },
    // 导出评价报告
    handleExport() {
      const loading = this.$loading({
        lock: true,
        text: '导出中……',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['年度', '月份', '得分']
        const filterVal = ['year', 'month', 'hosScore']
        const data = this.formatJson(filterVal, this.dataList)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '',
          autoWidth: true,
          bookType: 'xlsx'
        })
        loading.close()
      })
    },
    handlePrint() {
      let iframe = document.getElementById('print-iframe')
      if (!iframe) {
        const el = document.querySelector('#print_view')
        iframe = document.createElement('IFRAME')
        let doc = null
        iframe.setAttribute('id', 'print-iframe')
        iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;')
        document.body.appendChild(iframe)
        doc = iframe.contentWindow.document
        const styleHtml = 'table{color:#fff;background-color:#0C3444;-webkit-print-color-adjust: exact;}' +
        'td,th{padding:10px;}' +
        'th{background:#306379;-webkit-print-color-adjust: exact;}' +
        'td{background:#0C3444;-webkit-print-color-adjust: exact; }'
        doc.write(`<html><head><style media="print">@media print {${styleHtml}}</style></head><body style="zoom: 60%;">${el.innerHTML}</body></html>`)
        doc.close()
        iframe.contentWindow.focus()
      }
      iframe.contentWindow.print()
      document.body.removeChild(iframe)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.content-container {
  margin: 10px 10px 0 10px;
  overflow: hidden;
  background: #193142;
  height: calc(100vh - 95px);

  p {
    margin: 0;
    line-height: 2em;
    padding: 0;
  }

  .tool-bar {
    .tip{
      color: #9e9595;
      font-size: 12px;
      padding-left: 10px;
    }

    .current-score {
      text-align: right;
      font-size: 12px;
      font-weight: 400;
      color: #FFFFFF;
      padding-right: 20px;

      span {
        font-size: 20px;
        font-weight: 400;
        color: #FFFFFF;
      }
    }
  }

  .hosScore{
    font-size: 18px;
    font-weight: 600;
    Font-style:oblique

  }
  .belowStandards{
    color: red;
  }
  .notappraise{
    color: yellow;
  }
  .isNotCurrentMonth{
    color: red;
    font-weight: 800;
  }
}
</style>
