<template>
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 培训级别-下拉 -->
      <el-form-item label="培训级别" prop="trainLevel">
        <el-select
          v-model="queryParams.trainLevel"
          placeholder="请选择培训级别"
          style="width: 200px"
          clearable
          filterable
        >
          <el-option
            v-for="dict in dict.type.sys_train_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 培训状态-下拉 -->
      <el-form-item label="培训状态" prop="signStatus">
        <el-select
          v-model="queryParams.signStatus"
          placeholder="请选择培训状态"
          style="width: 200px"
          clearable
          filterable
        >
          <el-option v-for="item in trainStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="培训日期范围" prop="timeRange">
        <el-date-picker
          v-model="queryParams.timeRange"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="创建日期范围" prop="createTimeRange">
        <el-date-picker
          v-model="queryParams.createTimeRange"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="dataList" fit highlight-current-row style="width: 100%">
      <!-- 多选 -->
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column
        v-for="(column, index) in tableHeader"
        show-overflow-tooltip
        :key="column.prop"
        :label="column.label"
        :prop="column.prop"
        align="center"
      >
        <template v-slot="scope" v-if="column.prop == 'name'">
          <span style="cursor: pointer; color: #409eff" @click="handleDetail(scope.row)">
            {{ scope.row.name }}
          </span>
        </template>
        <template v-slot="scope" v-else-if="column.prop == 'duration'">
          <span>{{ scope.row.duration }}分钟</span>
        </template>
        <template v-slot="scope" v-else-if="column.prop == 'score'">
          <span v-if="scope.row.score >= 0">{{ scope.row.score }}</span>
          <span v-else>-</span>
        </template>
        <template v-slot="scope" v-else-if="column.prop == 'signStatus'">
          <span v-if="scope.row.status == 0">待开始</span>
          <span v-if="scope.row.status == 1">
            <span v-if="scope.row.signStatus == 0">待开始</span>
            <span v-else-if="scope.row.signStatus == 1">培训中</span>
            <span v-else-if="scope.row.signStatus == 2">已完成</span>
          </span>
          <span v-if="scope.row.status == 2">已完成</span>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleDetail(scope.row)">查看</el-button>
          <el-button
            v-if="!scope.row.signTime"
            type="text"
            size="mini"
            icon="el-icon-edit-outline"
            :disabled="scope.row.signStatus != '1'"
            @click="handleSignIn(scope.row)"
          >
            签到
          </el-button>
          <el-button v-else-if="scope.row.signTime" type="text" size="mini" disabled>已完成签到</el-button>
          <el-button v-else-if="scope.row.isNotInTime" type="text" size="mini" disabled>签到已过期</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { getMyTrainingList, webTrainingSign } from '@/api/educTrainLearn'

export default {
  name: 'trainTask',
  dicts: ['sys_train_level'],
  data() {
    return {
      userId: this.$store.state.user.id,
      userType: this.$store.state.user.userType,
      proId: this.$store.state.user.thisIds.proId,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '',
        timeRange: [], // 日期范围
        createTimeRange: [], // 创建时间
        trainLevel: '', // 培训级别
        signStatus: '', // 培训状态
      },
      total: 0,
      showSearch: true,
      // 培训状态下拉
      trainStatusOptions: [
        { label: '待开始', value: '0' },
        { label: '培训中', value: '1' },
        { label: '已完成', value: '2' },
      ],
      // 表格头
      tableHeader: [
        { label: '培训主题名称', prop: 'name' },
        { label: '培训级别', prop: 'trainLevel' },
        { label: '培训日期', prop: 'time' },
        { label: '培训地点', prop: 'location' },
        { label: '培训时长', prop: 'duration' },
        { label: '主讲人', prop: 'speaker' },
        { label: '培训人数', prop: 'trainNum' },
        { label: '培训状态', prop: 'signStatus' },
        { label: '创建时间', prop: 'createTime' },
        { label: '是否需要考试', prop: 'isExam' },
        { label: '考试成绩', prop: 'score' },
      ],
      dataList: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleQuery() {
      this.getList()
    },
    handleReset() {
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    async getList() {
      try {
        let startTime = ''
        let endTime = ''
        if (this.queryParams.timeRange && this.queryParams.timeRange.length > 0) {
          startTime = this.queryParams.timeRange[0]
          endTime = this.queryParams.timeRange[1]
        }
        let createStartTime = ''
        let createEndTime = ''
        if (this.queryParams.createTimeRange && this.queryParams.createTimeRange.length > 0) {
          createStartTime = this.queryParams.createTimeRange[0]
          createEndTime = this.queryParams.createTimeRange[1]
        }
        const params = {
          ...this.queryParams,
          startTime,
          endTime,
          createStartTime,
          createEndTime,
          userId: this.userId,
          userType: this.userType,
          proId: this.proId,
        }
        console.log('🚀 ~ 获取列表-参数-params', params)
        const res = await getMyTrainingList(params)
        console.log('🚀 ~ 获取培训列表', res)
        this.dataList = res.rows
        this.total = res.total
        this.dataList.forEach(item => {
          // time 2021-07-01 09:00:00 ~ 2021-07-01 12:00:00 去后面的日期 需要精确到秒, 判断当前时间是否在培训时间内, 不在时间内添加属性 isNotInTime=true
          const time = item.time.split(' ~ ')[1]
          const endTime = new Date(time).getTime()
          const nowTime = new Date().getTime()
          if (nowTime > endTime) {
            item.isNotInTime = true
          }
        })
      } catch (error) {
        console.error('🚀 ~ 培训列表', error)
      }
    },
    // 查看详情
    handleDetail(row) {
      console.log('🚀 ~ 查看详情', row)
      this.$router.push({
        path: '/educTrainLearn/trainTask/trainDetail',
        query: row,
      })
    },
    // 签到确认
    handleSignIn(row) {
      console.log('🚀 ~ 签到', row)
      const timeArr = row.time.split(' ~ ')
      const startTime = new Date(timeArr[0]).getTime()
      const endTime = new Date(timeArr[1]).getTime()
      const nowTime = new Date().getTime()
      if (nowTime < startTime || nowTime > endTime) {
        this.$message.error('不在签到时间范围内')
        return
      }
      // 弹框确认签到
      this.$confirm('是否确认签到?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.signIn(row)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          })
        })
    },
    // 签到
    async signIn(row) {
      try {
        const params = {
          userId: this.userId,
          id: row.id,
        }
        console.log('🚀 ~ 签到-参数', params)
        const res = await webTrainingSign(params)
        console.log('🚀 ~ 签到', res)
        this.getList()
        this.$message.success('签到成功')
      } catch (error) {
        console.error('🚀 ~ 签到', error)
      }
    },
    // 导出数据
    handleExport() {
      try {
        let startTime = ''
        let endTime = ''
        if (this.queryParams.timeRange && this.queryParams.timeRange.length > 0) {
          startTime = this.queryParams.timeRange[0]
          endTime = this.queryParams.timeRange[1]
        }
        let createStartTime = ''
        let createEndTime = ''
        if (this.queryParams.createTimeRange && this.queryParams.createTimeRange.length > 0) {
          createStartTime = this.queryParams.createTimeRange[0]
          createEndTime = this.queryParams.createTimeRange[1]
        }
        const params = {
          ...this.queryParams,
          startTime,
          endTime,
          createStartTime,
          createEndTime,
          userId: this.userId,
          userType: this.userType,
          proId: this.proId,
        }

        let fileName = `培训任务_${new Date().getTime()}.xLsx`
        let url = '/exam/learningTask/exportTrainingList'
        console.log('🚀 ~ 导出 ~ params:', params)
        this.derive(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
