<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable v-no-whitespace
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <!-- 学习对象下拉 -->
      <el-form-item label="学习对象" prop="taskFor">
        <el-select v-model="queryParams.taskFor" placeholder="请选择学习对象" clearable>
          <el-option v-for="item in studyObjectList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- 培训级别下拉 -->
      <el-form-item label="培训级别" prop="trainLevel">
        <el-select v-model="queryParams.trainLevel" placeholder="请选择培训级别" clearable>
          <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="eduType">
        <el-select v-model="queryParams.eduType" placeholder="请选择教育类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_edu_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        />
      </el-form-item>

      <el-form-item class="align-right">
        <el-button size="mini" type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
        <el-button size="mini" 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="primary" size="mini" @click="handleNewTask" >新建任务</el-button>
      </el-col>
      <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="tableData" fit highlight-current-row style="width: 100%" @selection-change="selectionChange">
      <!-- <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="item in tableHeader"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        align="center"
        show-overflow-tooltip
      >
        <!-- taskFor: 1. 内部单位 2外部单位 -->
        <template v-slot="scope" v-if="item.prop === 'taskFor'">
          <span>{{ scope.row.taskFor == '1' ? '内部单位' : '外部单位' }}</span>
        </template>
        <template v-slot="scope" v-else-if="item.prop === 'totalTime'">
          <span>{{ (scope.row.totalTime / 60).toFixed(2) }}分钟</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleData(scope.row)"  icon="el-icon-document">
            数据
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="handleEdit(scope.row)"
            v-if="new Date(scope.row.updater.substr(0, 10)) >= new Date()"

            icon="el-icon-edit-outline"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="handleDelete(scope.row)"
            v-if="new Date(scope.row.updater.substr(0, 10)) >= new Date()"

            icon="el-icon-delete"
            style="color: #e47470"
          >
            删除
          </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 { learningTaskList,delStudyTaskById } from '@/api/educationalTraining/resourceAdministration'
import { indexContinuous } from '@/utils/bonus'

export default {
  dicts: ['sys_train_level', 'sys_edu_type'],
  data() {
    return {
      showSearch: true,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 关键字
        keyWord: '',
        // 学习对象
        taskFor: '',
        // 培训级别
        trainLevel: '',
        // 教育类型
        eduType: '',
        // 创建时间范围
        createTime: [],
        startDate: '', // 开始时间
        endDate: '', // 结束时间
      },
      // 学习对象下拉
      studyObjectList: [
        { label: '内部单位', value: '1' },
        { label: '外部单位', value: '2' },
      ],
      // 表格头
      tableHeader: [
        { prop: 'studyTaskName', label: '任务主题名称' },
        { prop: 'taskFor', label: '学习对象' },
        { prop: 'trainLevel', label: '培训级别' },
        { prop: 'eduType', label: '教育类型' },
        { prop: 'trainNum', label: '学习人数' },
        { prop: 'totalTime', label: '总时长' },
        { prop: 'createUserName', label: '创建人' },
        { prop: 'createTime', label: '创建时间' },
        { prop: 'updater', label: '有效期' },
      ],
      // 表格数据
      tableData: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    indexContinuous,
    // 查询
    handleSearch() {
      console.log('🚀 ~ handleSearch ~ handleSearch:', this.queryParams)
      if (this.queryParams.createTime && this.queryParams.createTime.length > 0) {
        this.queryParams.startDate = this.queryParams.createTime[0]
        this.queryParams.endDate = this.queryParams.createTime[1]
      } else {
        this.queryParams.startDate = ''
        this.queryParams.endDate = ''
      }
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.queryForm.resetFields()
      this.queryParams.startDate = ''
      this.queryParams.endDate = ''
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('获取列表')
      try {
        const param = Object.assign({}, this.queryParams)
        delete param.createTime
        const res = await learningTaskList(param)
        console.log('🚀 ~ getList ~ res-列表:', res)
        this.tableData = res.rows
        this.total = res.total
        // updater 有效期 startTime ~ endTime 有效期：2021-09-01 ~ 2021-09-30
        this.tableData.forEach((item) => {
          item.updater = `${item.startTime} ~ ${item.endTime}`
        })
      } catch (error) {
        console.log('🚀 ~ getList ~ error:', error)
      }
    },
    // 新建任务
    handleNewTask() {
      console.log('新建任务')
      this.$router.push({
        path: '/educationalTraining/learningManagement/learningTasks/newTask',
      })
    },
    // 导出
    handleExport() {
      delete this.queryParams.createTime
      this.derive('exam/learningTask/export', {
        ...this.addDateRange(this.queryParams, this.dateRange)
      }, `学习任务_${new Date().getTime()}.xlsx`)
    },
    // 数据
    handleData(row) {
      console.log('数据', row)
      this.$router.push({
        path: '/educationalTraining/learningManagement/learningTasks/dataAnalysis',
        query: {
          studyTaskId: row.studyTaskId,
          taskFor: row.taskFor,
        }
      })
    },
    // 编辑
    handleEdit(row) {
      console.log('编辑', row)
      // 路由跳转 task
      this.$router.push({
        // 路由地址
        path: '/educationalTraining/learningManagement/learningTasks/editTask',
        // 传递参数
        query: {
          studyTaskId: row.studyTaskId,
        },
      })
    },
    // 删除
    handleDelete(row) {
      console.log('删除', row)
      // 提示
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 确定
          delStudyTaskById(row).then(res => {
            let msg = res.msg ;
            let code = res.code;
            if(code === 200){
              this.$modal.msgSuccess(msg)
              this.getList()
            }
          });
          console.log('确定')
        })
        .catch(() => {
          // 取消
          console.log('取消')
        })
    },
    // 多选
    selectionChange(val) {
      console.log('selectionChange', val)
    },
  },
}
</script>

<style lang="scss" scoped>
.align-right {
  display: flex;
  justify-content: flex-end;
}
</style>
