<template>
  <!--打分列表-->
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页
      </el-button>
    </el-toolbar>
    <div class="">
      <div class="search-bar assess-content">
        <el-row v-if="!isComplexSearch" type="flex" class="row-bg" justify="end" :gutter="9">
          <el-col :span="8">
            <el-input v-model="searchData.query" placeholder="请输入标题" @keyup.enter.native="loadAssessListTableData"></el-input>
          </el-col>
          <el-col class="search-btn-box" :span="5">
            <el-button-group>
              <el-button type="primary" @click="loadAssessListTableData">
                <i class="fa fa-search"></i>搜索
              </el-button>
              <el-button @click="isComplexSearch=!isComplexSearch">高级搜索 ...</el-button>
            </el-button-group>
          </el-col>
        </el-row>
        <template v-else>
          <el-row type="flex" class="row-bg" justify="space-around">
            <el-col :span="10">
              <el-select v-model="searchData.userName" clearable placeholder="请选择用户名" @change="loadAssessListTableData" @clear="loadAssessListTableData" style="width:100%">
                <el-option v-for="item in contentAssessUsersData" :key="item.ID" :label="item.name" :value="item.ID">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-date-picker id="assessContent-date-picker" v-model="searchDateTimes" type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-col>
          </el-row>
          <div style="padding:3px"></div>
          <el-row type="flex" class="row-bg" justify="space-around">
            <el-col :span="10">
                <el-input v-model="searchData.query" placeholder="请输入标题" @keyup.enter.native="loadAssessListTableData"></el-input>
            </el-col>
            <el-col :span="12">
              <el-button-group style="float:left">
                <el-button  type="primary" @click="loadAssessListTableData">
                  <i class="fa fa-search"></i>高级搜索
                </el-button>
                <el-button @click="isComplexSearch=!isComplexSearch">搜索 ...</el-button>
              </el-button-group>
            </el-col>
          </el-row>
        </template>
      </div>
      <div class="padding-vertical-max">
        <el-table :data-read-url="dataReadFunc" :page-size="10" :auto-get-data="true" pagination-layout="total,sizes, ->, prev, pager, next, jumper"  ref="assessListTable" style="width: 100%" @selection-change="selectionChange">
          <el-table-column type="index" label="序号" width="60"></el-table-column>
          <el-table-column type="selection" label=""></el-table-column>
          <el-table-column prop="" label="标题" show-overflow-tooltip>
            <template slot-scope="scope">
              <a href="javascript:void(0);" @click="preview(scope.row)" target="_blank">{{ scope.row.title }}</a>
            </template>
          </el-table-column>
          <el-table-column prop="catalogName" label="所属栏目" ></el-table-column>
          <el-table-column prop="addUser" label="添加人" width="100"></el-table-column>
          <el-table-column prop="publishDate" label="发布时间" width="160" >
            <template slot-scope="scope">
              {{scope.row.publishDate | fixDateTime}}
            </template>
          </el-table-column>
          <el-table-column label="分数" width="80">
            <template slot-scope="scope">
              <el-input
              v-model="scope.row.score"
              :value="scope.row.score"
              @change="scoreInputChangeHandler"
              @focus="inputCellClick(scope.row)"
              @blur="setScoreForOne(scope.row.ID)"
              @keyup.enter.native="setScoreForOne(scope.row.ID)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import util from '@src/common/util.js'

export default {
  props: {
    ID: {
      type: [String, Number],
      default: 0
    }
  },
  filters: {
    fixDateTime: function(val) {
      if (!val) {
        return ''
      }
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      isComplexSearch: false,
      score: null, // 分数
      selectedRows: [], // 表格选中行数据
      scoreValidateForm: {
        score: null
      }, // 打分表单数据
      searchDateTimes: [],
      // 搜索条件
      emptySearchData: {},
      assessListData: [],
      contentAssessUsersData: [], // 用户下拉框数据
      tableDataLoading: false, // 右侧表格数据加载状态
      okSetScoreBtnLoading: false, // 打分Dialog确定按钮加载状态
      scoreHasChange: false,
      searchData: {
        query: '',
        userName: '',
        startDate: '',
        endDate: ''
      }
    }
  },
  created() {
    this.loadContentAssessUserList()
  },
  methods: {
    preview(row) {
      window.open(`preview.html?id=${row.ID}&type=content`)
    },
    dataReadFunc() {
      return [`/ui/contentassess`,
        { params: Object.assign({catalogID: this.ID}, this.searchData, {query: encodeURIComponent(this.searchData.query)}) }]
    },
    // 加载右侧表格上方工具栏用户下拉列表数据
    async loadContentAssessUserList() {
      let res = await axios.get('/ui/contentassess/userlist')
      let data = res.data
      this.contentAssessUsersData = data.status === 1 ? data.data : this.contentAssessUsersData
    },
    inputCellClick(row) {
      // this.$refs.assessListTable.clearSelection()
      this.$refs.assessListTable.toggleRowSelection(row, false)
    },
    // 加载表格数据
    async loadAssessListTableData() {
      this.scoreHasChange = false
      this.tableDataLoading = true

      if (!!this.searchDateTimes && !!this.searchDateTimes.length && !!this.searchDateTimes[0]) {
        let startDate = util.formatDate(this.searchDateTimes[0], 'yyyy-MM-dd HH:mm:ss')
        Object.assign(this.searchData, { startDate })
      } else {
        Object.assign(this.searchData, { startDate: '' })
      }
      if (!!this.searchDateTimes && this.searchDateTimes.length > 1 && !!this.searchDateTimes[1]) {
        let endDate = util.formatDate(this.searchDateTimes[1], 'yyyy-MM-dd HH:mm:ss')
        Object.assign(this.searchData, { endDate })
      } else {
        Object.assign(this.searchData, { endDate: '' })
      }

      !!this.$refs.assessListTable && this.$refs.assessListTable.getData()
    },
    // 设置单个记录分值
    async setScoreForOne(val) {
      if (!this.scoreHasChange) {
        return
      }
      if (isNaN(this.score)) {
        this.Dialog('必须是0-100的数字 ！')
        return
      }

      this.score = Math.min(100, Math.max(0, this.score))

      let dc = {
        contentID: val,
        score: this.score,
        catalogID: this.ID
      }
      let res = await axios.put(`/ui/contentassess/${val}`, dc)
      let data = res.data
      if (data.status === 1) {
        this.MsgPop(data.message, 'success')
        this.loadAssessListTableData()
      } else {
        this.Dialog(data.message)
      }
    },
    // 确认打分
    async setScore(formName) {
      let flag = false
      this.$refs[formName].validate(valid => {
        if (valid) {
          flag = true
        } else {
          this.Dialog('必须是0-100的数字 ！')
          flag = false
        }

        if (isNaN(this.scoreValidateForm.score)) {
          this.Dialog('必须是0-100的数字 ！')
          flag = false
        }
      })

      if (!flag) {
        return
      }

      this.scoreValidateForm.score = Math.min(100, Math.max(0, this.scoreValidateForm.score))

      let idsArr = []
      for (var arr of this.selectedRows) {
        idsArr.push(arr.ID)
      }

      let dc = {
        contentID: idsArr.join(),
        score: this.scoreValidateForm.score,
        catalogID: this.ID
      }

      this.okSetScoreBtnLoading = true

      let res = await axios.put(`/ui/contentassess/${dc.contentID}`, dc)
      let data = res.data
      if (data.status === 1) {
        this.setScoreDialogVisible = false
        this.MsgPop(data.message, 'success')
        this.loadAssessListTableData()
      } else {
        this.Dialog(data.message)
      }
      this.okSetScoreBtnLoading = false
    },

    // 表格行数据选中事件
    selectionChange(selection) {
      this.selectedRows = selection
    },

    // 重置搜索条件
    resetsearchData() {
      Object.assign(this.searchData, this.emptySearchData)
    },

    // 表格中分数输入框改变事件
    scoreInputChangeHandler(val) {
      this.scoreHasChange = true
      val = val - 0
      this.score = isNaN(val) || typeof val !== 'number' ? 0 : val
    },

    // 消息Dialog封装
    Dialog(msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    },
    // 消息显示封装
    MsgPop(msg, type) {
      if (!type) {
        this.$message(msg)
        return
      }
      this.$message({
        message: msg,
        type: type
      })
    }
  }
}
</script>

<style scope>
.assess-content {text-align: right;padding-right: 0;}
</style>
