<template>
  <div class="page">
    <h6 class="page-name">筛选</h6>
    <div class="tool">
      <ul class="filter">
        <li>
          <label>评阅时间</label>
          <el-radio-group v-model="month" @change="monthChange">
            <el-radio v-for="(item, index) in dateList" :key="index" :label="item.id" border>{{ item.name
              }}</el-radio>
          </el-radio-group>
          <el-date-picker class="m-l-10" v-model="date" align="right" unlink-panels type="daterange"
            start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" clearable
            @change="dateChange"></el-date-picker>
        </li>
        <li>
          <label>评阅阶段</label>
          <el-select v-model="filter.evaluationStatus" clearable placeholder="请选择评阅阶段" @change="initData">
            <el-option v-for="(item, i) in reviewStage" :key="i" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </li>
        <li>
          <label>评阅情况</label>
          <el-select v-model="filter.evaluationResult" clearable placeholder="请选择评阅情况" @change="initData">
            <el-option v-for="(item, i) in reviewStatus" :key="i" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </li>
        <li>
          <label>搜索</label>
          <el-input style="width: 300px;" :placeholder="`请输入${fromNakadai ? '大赛名称、阶段赛名称、比赛内容' : '考核名称、考核内容'}`"
            prefix-icon="el-icon-search" v-model="filter.keyword" clearable />
        </li>
      </ul>
    </div>

    <el-table :data="list" v-loading="loading" class="table" ref="table" stripe header-align="center" row-key="id">
      <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
      <el-table-column :key="1" prop="competitionName" :label="fromNakadai ? '大赛名称' : '考核名称'" align="center"
        min-width="120" show-overflow-tooltip></el-table-column>
      <el-table-column v-if="fromNakadai" :key="2" prop="stageName" label="阶段赛名称" align="center"
        min-width="100"></el-table-column>
      <el-table-column :key="3" prop="competitionContent" :label="fromNakadai ? '比赛内容' : '考核内容'" align="center"
        min-width="100"></el-table-column>
      <el-table-column prop="totalAnswer" label="分配答卷数" align="center" width="90"></el-table-column>
      <el-table-column prop="unReviewedAnswer" label="待评答卷数" align="center" width="90"></el-table-column>
      <el-table-column prop="reviewedAnswer" label="已评答卷数" align="center" width="90"></el-table-column>
      <el-table-column prop="time" label="评阅时间" align="center" width="300"></el-table-column>
      <el-table-column prop="stage" label="评阅阶段" align="center" width="90"></el-table-column>
      <el-table-column prop="reviewStatusName" label="评阅情况" align="center" width="90"></el-table-column>
      <el-table-column label="操作" align="center" width="90" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" :disabled="scope.row.stage !== '进行中'" @click="toReview(scope.row)">评阅</el-button>
          <el-button type="text" @click="toReview(scope.row, 1)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background :page-sizes="[10, 30, 50, 100, 200]" @current-change="currentChange"
        @size-change="sizeChange" :current-page="page" layout="total, prev, pager, next, sizes"
        :total="total"></el-pagination>
    </div>
  </div>
</template>

<script>
import Util from '@/libs/util'
import Setting from '@/setting'
import Const from '@/const/ques'
import Qs from 'qs'
import dayjs from 'dayjs'

const fromNakadai = localStorage.getItem('reviewFromNakadai') // 来自中台
export default {
  data () {
    return {
      fromNakadai,
      difficults: Const.difficults,
      questionTypes: Const.questionTypes,
      loading: false,
      dateList: [
        {
          id: '',
          name: '全部'
        },
        {
          id: 0,
          name: '不限时'
        },
        {
          id: 1,
          name: '近一个月'
        },
        {
          id: 3,
          name: '近三个月'
        },
        {
          id: 6,
          name: '近六个月'
        }
      ],
      reviewStage: [
        {
          id: 0,
          name: '未开始'
        },
        {
          id: 1,
          name: '进行中'
        },
        {
          id: 2,
          name: '已结束'
        },
      ],
      reviewStatus: [
        {
          id: 0,
          name: '未完成'
        },
        {
          id: 1,
          name: '已完成'
        },
      ],
      month: '',
      date: [],
      filter: {
        startTime: '',
        endTime: '',
        evaluationResult: '',
        evaluationStatus: '',
        keyword: '',
      },
      now: '',
      timer: null,
      list: [],
      page: +this.$route.query.page || 1,
      pageSize: 10,
      total: 0,
    };
  },
  watch: {
    'filter.keyword': function () {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(this.initData, 500)
    },
  },
  mounted () {
    this.$once('hook:beforeDestroy', function () {
      clearInterval(this.timer)
    })

    const { query } = this.$route
    if (query.page) {
      const { month, startTime, endTime, evaluationResult, evaluationStatus, keyword } = query
      this.filter = {
        evaluationResult: evaluationResult ? +evaluationResult : '',
        evaluationStatus: evaluationStatus ? +evaluationStatus : '',
        keyword: keyword || '',
      }
      this.month = !startTime && month !== '' ? +month : ''
      if (startTime) this.date = [startTime, endTime]

      this.$router.push(`/myReview`).catch(() => { })
    }

    this.getList()
  },
  methods: {
    async getList () {
      try {
        this.loading = true
        const { page } = await this.$post(this.api[fromNakadai ? 'myReviewTask' : 'myReviewTaskForAssessment'], {
          ...this.filter,
          isTimed: this.month === 0 ? 0 : '',
          pageNum: this.page,
          pageSize: this.pageSize,
        })
        const list = page.records
        list.forEach(e => {
          // e.reviewStageName = this.reviewStage.find(n => n.id === e.reviewStage).name
          if (e.reviewStatus !== null && e.reviewStatus !== undefined) e.reviewStatusName = this.reviewStatus.find(n => n.id === +e.reviewStatus).name
          // e.reviewStageName = this.reviewStage.find(n => n.id === e.reviewStage).name
          e.stage = '-'
          e.time = e.isTimed ?
            e.startTime + ' ~ ' + e.endTime :
            '不限时'
        })
        this.list = list
        this.getNow()
        this.total = page.total
      } finally {
        this.loading = false
      }
    },
    // 切换页码
    currentChange (val) {
      this.page = val
      this.getList()
    },
    sizeChange (val) {
      this.pageSize = val
      this.initData()
    },
    initData () {
      this.$refs.table.clearSelection()
      this.page = 1
      this.getList()
    },
    // 处理评阅阶段的显示
    async handleStage () {
      this.list.forEach(e => {
        let stage = '-'
        if (e.isTimed) {
          if (e.startTime && e.endTime) {
            const startTime = new Date(e.startTime)
            const endTime = new Date(e.endTime)
            stage = this.now < startTime ?
              '未开始' :
              this.now > endTime ?
                '已结束' :
                '进行中'
          }
        } else {
          stage = '进行中'
        }
        e.stage = stage
      })
    },
    // 获取最新时间自动计算
    async getNow () {
      if (!this.now) {
        this.now = await Util.getNow()
        this.handleStage()
        clearInterval(this.timer)
        this.timer = setInterval(() => {
          this.now = new Date(this.now.setSeconds(this.now.getSeconds() + 1))
          this.handleStage()
        }, 1000)
      }
    },
    // 评阅月份选择回调
    monthChange (val) {
      if (val) {
        const unit = 24 * 60 * 60 * 1000
        this.date = [dayjs(new Date(Date.now() - unit * 30 * val)).format('YYYY-MM-DD'), dayjs(new Date(Date.now() + unit)).format('YYYY-MM-DD')]
      } else {
        this.date = []
      }
      this.dateChange(this.date)
    },
    // 评阅日期选择回调
    dateChange (val) {
      if (val && val.length) {
        this.filter.startTime = val[0]
        this.filter.endTime = val[1]
      } else {
        this.filter.startTime = ''
        this.filter.endTime = ''
      }
      this.initData()
    },

    // 评阅
    toReview (row, readonly = 0) {
      this.$store.commit('user/setReferrer', {
        i: 1,
        url: `${this.$route.path}?${Qs.stringify(this.filter)}&month=${this.month}&page=${this.page}&pageSize=${this.pageSize}`
      })

      this.$router.push(`records?competitionId=${row.competitionId || ''}&stageId=${row.stageId || ''}&assessmentId=${row.assessmentId || ''}&readonly=${row.stage !== '进行中' && readonly ? 1 : 0}`)
    },
  }
};
</script>

<style lang="scss" scoped>
.tool {
  margin-bottom: 0;

  .filter {
    flex-wrap: wrap;

    li {
      margin-bottom: 15px;
    }

    /deep/.el-radio {
      margin-right: 0;
    }
  }
}
</style>