<template>
  <div class="app-container">
    <el-form ref="searchArr" :inline="true" :model="search" class="demo-form-inline">
      <el-form-item label="用戶名">
        <el-input v-model="search.nickname" clearable />
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker
          v-model="search.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="序號">
        <el-input v-model="search.sign" clearable />
      </el-form-item>
      <el-form-item label="版本">
        <el-input v-model="search.version" clearable />
      </el-form-item>
      <el-form-item label="完成度">
        <el-input v-model="search.schedule" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="nextPage()">搜素</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="download()">下載</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="deleteC()">删除</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="back()">返回</el-button>
      </el-form-item>
    </el-form>
    <el-table
      ref="gamelog"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="40"
      />
      <el-table-column align="center" label="ID" width="55">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="nickname" label="用戶名">
        <template slot-scope="scope">
          {{ scope.row.nickname }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="sign" label="序號">
        <template slot-scope="scope">
          {{ scope.row.sign }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="startTime" label="日期">
        <template slot-scope="scope">
          {{ scope.row.startTime.substring(0,10) }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="version" label="版本">
        <template slot-scope="scope">
          {{ scope.row.version }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="version" label="正確率">
        <template slot-scope="scope">
          {{ (scope.row.realCorrectRate != null ? (scope.row.realCorrectRate * 100).toFixed(2) : 0) + "" }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="version" label="錯誤率">
        <template slot-scope="scope">
          {{ ((scope.row.wrongRate * 100).toFixed(2)) + "" }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="version" label="錯失率">
        <template slot-scope="scope">
          {{ ((scope.row.missRate * 100).toFixed(2)) + "" }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="version" label="反應時間">
        <template slot-scope="scope">
          {{ (changeTwoDecimal_f(scope.row.avgReaction)) + "" }}
        </template>
      </el-table-column>
      <el-table-column align="center" sortable label="主观正確率" prop="realCorrectRate">
        <template slot-scope="scope">
          {{ scope.row.correctRate * 100 }}
        </template>
      </el-table-column>
      <el-table-column align="center" sortable label="主觀信度" prop="realCorrectRate">
        <template slot-scope="scope">
          {{ scope.row.confidence * 100 }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="startTime" label="開始時間">
        <template slot-scope="scope">
          {{ scope.row.startTime.substring(11,19) }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="endTime" label="完成時間">
        <template slot-scope="scope">
          {{ scope.row.endTime.substring(11,19) }}
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="sign" label="完成度">
        <template slot-scope="scope">
          {{ scope.row.schedule * 100 }}%
        </template>
      </el-table-column>
      <el-table-column align="center" label="設備號">
        <template slot-scope="scope">
          {{ scope.row.deviceId }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="260">
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(['admin'])" size="mini" @click="openDel(row)">
            删除
          </el-button>
          <el-button v-if="checkPermission(['admin'])" size="mini" @click="openDetail(row)">
            查看詳情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="page.total"
      :page.sync="page.pageNum"
      :limit.sync="page.size"
      @pagination="nextPage"
    />
    <el-dialog title="遊戲詳情" :visible.sync="gameVisible" width="80%">
      <span>用戶名:{{ detailNickName }}</span>>
      <span>序號:{{ detailId }}}</span>>
      <span>日期:{{ detailDate }}}</span>>
      <span>版本:{{ detailVersion }}}</span>>
      <span>正確率:{{ detailCorrectRate != null ? detailCorrectRate * 100 : 0 }}, </span>
      <span>錯誤率:{{ (getDetailWrongRate() * 100).toFixed(2) }}, </span>
      <span>錯失率:{{ (getDetailMissRate() * 100).toFixed(2) }}, </span>
      <span>反應時間:{{ changeTwoDecimal_f(detailReaction) }}</span>
      <el-table :data="detail" size="mini">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
<!--        <el-table-column align="center" label="用戶名">-->
<!--          <template slot-scope="scope">-->
<!--            {{ scope.row.nickname }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column align="center" label="日期">-->
<!--          <template slot-scope="scope">-->
<!--            {{ scope.row.startTime.substring(0,10) }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column align="center" label="版本">-->
<!--          <template slot-scope="scope">-->
<!--            {{ scope.row.version }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column align="center" label="序號">-->
<!--          <template slot-scope="scope">-->
<!--            {{ scope.row.sign }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column align="center" label="開始時間">-->
<!--          <template slot-scope="scope">-->
<!--            {{ scope.row.startTime.substring(11,19) }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column align="center" label="完成時間">-->
<!--          <template slot-scope="scope">-->
<!--            {{ scope.row.endTime.substring(11,19) }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column align="center" label="完成度">-->
<!--          <template slot-scope="scope">-->
<!--            {{ scope.row.schedule*100 }}%-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column align="center" label="抽取數字">
          {{ detailSelected }}
        </el-table-column>
        <el-table-column align="center" label="出現數字">
          <template slot-scope="scope">
            {{ scope.row.showNum }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="用戶回答">
          <template slot-scope="scope">
            {{ scope.row.answer === 1 ? 'press' :'N-press' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="true/false/omission">
          <template slot-scope="scope">
            {{ scope.row.correct === 1 ? 'true' : scope.row.correct === 2 ? 'false' : 'omission' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="反應時間">
          <template slot-scope="scope">
            {{ scope.row.reaction }}
          </template>
        </el-table-column>

      </el-table>

    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import checkPermission from '@/utils/permission'
import GameApi from '@/api/game'

export default {
  name: 'List',
  components: { Pagination },
  data() {
    return {
      list: [],
      search: {},
      order: {},
      detail: [],
      page: { total: 0, size: 0, pageNum: 0 },
      listLoading: false,
      gameVisible: false,
      detailSelected: '',
      detailCorrectRate: 0.0,
      detailReaction: 0,
      detailNickName: '',
      detailId: 0,
      detailDate: '',
      detailVersion: ''
    }
  },
  created() {
    this.nextPage()
  },
  mounted() {

  },
  methods: {
    checkPermission,
    openDel(r) {
      this.$confirm('此操作将永久id爲 ' + r.id + '的遊戲記錄, 是否继续?', '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delGameLog(r)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    delGameLog(r) {
      GameApi.del({ id: r.id }).then(response => {
        Message({
          message: '刪除成功',
          type: 'success',
          duration: 2 * 1000
        })
        if (response.code === 200) {
          this.nextPage()
        }
      })
    },
    changeTwoDecimal_f(x) {
      var f_x = parseFloat(x)
      if (isNaN(f_x)) {
        return 0
      }
      f_x = Math.round(x * 100) / 100
      var s_x = f_x.toString()
      var pos_decimal = s_x.indexOf('.')
      if (pos_decimal < 0) {
        pos_decimal = s_x.length
        s_x += '.'
      }
      while (s_x.length <= pos_decimal + 2) {
        s_x += '0'
      }
      return s_x
    },
    openDetail(r) {
      GameApi.detail({ id: r.id }).then(response => {
        if (response.code === 200) {
          this.detail = response.data
          this.detailSelected = r.selected
          this.detailCorrectRate = r.realCorrectRate
          this.detailReaction = this.getAvgReaction()
          this.detailNickName = r.nickname
          this.detailDate = r.startTime.substring(0, 10)
          this.detailId = r.sign
          this.detailVersion = r.version
          this.gameVisible = true
        }
      })
    },
    nextPage() {
      this.listLoading = true
      GameApi.getList({ page: this.page.pageNum, search: JSON.stringify(this.search), order: JSON.stringify(this.order) }).then(response => {
        this.list = response.data.list
        this.page.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      })
    },
    getDetailWrongRate() {
      if (this.detail) {
        let size = 0
        this.detail.forEach((item, index) => {
          if (item.correct === 2) {
            size += 1
          }
        })
        return size === 0 ? 0 : size / this.detail.length
      } else {
        return 0
      }
    },
    getDetailMissRate() {
      if (this.detail) {
        let size = 0
        this.detail.forEach((item, index) => {
          if (item.correct === 3) {
            size += 1
          }
        })
        return size === 0 ? 0 : size / this.detail.length
      } else {
        return 0
      }
    },
    getAvgReaction() {
      if (this.detail) {
        let size = 0
        let react = 0
        this.detail.forEach((item, index) => {
          if (item.reaction !== -1) {
            react += item.reaction
            size += 1
          }
        })
        return react === 0 ? 0 : react / size
      } else {
        return 0
      }
    },
    sortChange(column) {
      this.order[column.prop] = column.order
      this.nextPage()
    },
    download() {
      GameApi.download({ search: JSON.stringify(this.search), order: JSON.stringify(this.order) }).then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', response.headers['filename'])
        document.body.appendChild(link)
        link.click()
      })
    },
    deleteC() {
      const ids = this.$refs.gamelog.selection.map(function(elem, index) {
        return elem.id
      }).join(',')

      GameApi.deleteIds({ ids: ids }).then(response => {
        this.nextPage()
      })
    },
    back() {
      this.search = {}
      this.order = {}
      this.nextPage()
    }
  }
}
</script>

<style scoped>

</style>
