<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" inline v-show="showSearch">
      <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="studyObject">
        <el-select v-model="queryParams.studyObject" placeholder="请选择学习对象" clearable filterable>
          <el-option v-for="item in studyObjectOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="培训级别" prop="trainingLevel">
        <el-select v-model="queryParams.trainingLevel" placeholder="请选择培训级别" clearable filterable>
          <el-option v-for="item in trainingLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="培训状态" prop="trainingStatus">
        <el-select v-model="queryParams.trainingStatus" placeholder="请选择培训状态" clearable filterable>
          <el-option v-for="item in trainingStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务创建时间" prop="createTime">
        <el-date-picker
          v-model="createTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
          style="width: 280px"
        />
      </el-form-item>
      <el-row>
        <el-form-item class="align-right">
          <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-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleCreate">新建培训</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="column in tableColumns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        show-overflow-tooltip
        align="center"
      >
        <template v-slot="scope" v-if="column.prop === 'trainingStatus' || column.prop === 'status'">
          <el-tag
            v-if="column.prop === 'trainingStatus'"
            :type="getTrainingStatusType(scope.row.trainingStatus)"
            size="mini"
          >
            {{ getTrainingStatusLabel(scope.row.trainingStatus) }}
          </el-tag>
          <el-tag
            v-else-if="column.prop === 'status'"
            :type="getStatusType(scope.row.startDate, scope.row.endDate)"
            size="mini"
          >
            {{ getStatusLabel(scope.row.startDate, scope.row.endDate) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.trainingStatus == '0'"
            type="text"
            size="mini"
            @click="handleSignIn(scope.row)"
            icon="el-icon-document"
          >
            开始签到
          </el-button>
          <el-button
            v-if="scope.row.trainingStatus == '1'"
            type="text"
            size="mini"
            @click="handleSignOut(scope.row)"
            icon="el-icon-document"
            style="color: #dca550"
          >
            结束签到
          </el-button>
          <el-button
            v-if="
              scope.row.trainingStatus == '0' && getStatusLabel(scope.row.startDate, scope.row.endDate) === '待开始'
            "
            type="text"
            size="mini"
            @click="handleEdit(scope.row)"
            icon="el-icon-edit-outline"
          >
            编辑
          </el-button>
          <el-button
            v-if="
              scope.row.trainingStatus == '0' && getStatusLabel(scope.row.startDate, scope.row.endDate) === '待开始'
            "
            type="text"
            size="mini"
            @click="handleDelete(scope.row)"
            icon="el-icon-delete"
            style="color: #e47470"
          >
            删除
          </el-button>
          <el-button
            v-if="scope.row.trainingStatus != '0'"
            type="text"
            size="mini"
            @click="handleSignInDetail(scope.row)"
            icon="el-icon-document"
          >
            签到详情
          </el-button>
          <el-button
            type="text"
            size="mini"
            v-if="scope.row.trainingStatus != '0'"
            @click="handleTrainData(scope.row)"
            icon="el-icon-document"
            style="color: #dca550"
          >
            培训数据
          </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"
    />

    <!-- 签到详情-弹框 -->
    <el-dialog title="签到详情" :visible.sync="dialogVisible" width="80%" center>
      <!-- 表单 -->
      <el-form :model="dialogForm" ref="dialogForm" size="mini" label-width="80px" inline>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dialogForm.name" maxlength="40" show-word-limit placeholder="请输入姓名" clearable v-no-whitespace />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleDialogQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleDialogReset">重置</el-button>
          <el-button icon="el-icon-download" @click="handleDialogExport">导出数据</el-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table
        :data="dialogTableData"
        fit
        highlight-current-row
        style="width: 100%"
        @selection-change="dialogSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          type="index"
          width="55"
          label="序号"
          align="center"
          :index="indexContinuous(dialogForm.pageNum, dialogForm.pageSize)"
        />
        <el-table-column
          v-for="column in dialogColumns"
          :key="column.prop"
          :prop="column.prop"
          show-overflow-tooltip
          :label="column.label"
          align="center"
        />
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="dialogTotal > 0"
        :total="dialogTotal"
        :page.sync="dialogForm.pageNum"
        :limit.sync="dialogForm.pageSize"
        @pagination="selectSignInList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { addDateRange, indexContinuous } from '@/utils/bonus'
import {
  changeSignStatus,
  delTrainingTaskById,
  getTrainingTasksList,
  selectTrainingDataList,
} from '@/api/educationalTraining/resourceAdministration'
import { preparationPost } from '@/api/pro/proList'

export default {
  data() {
    return {
      total: 0,
      dialogTotal: 0,
      showSearch: true,
      dialogVisible: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '',
        // 学习对象
        studyObject: '',
        // 培训级别
        trainingLevel: '',
        // 培训状态
        trainingStatus: '',
      },
      // 任务创建时间范围
      createTime: [],
      // 学习对象-下拉
      studyObjectOptions: [
        { label: '内部人员', value: '1' },
        { label: '外委人员', value: '2' },
      ],
      // 培训级别-下拉
      trainingLevelOptions: [
        { label: '公司级', value: '1' },
        { label: '班组级', value: '2' },
      ],
      // 培训状态-下拉
      trainingStatusOptions: [
        { label: '未开始', value: '1' },
        { label: '进行中', value: '2' },
        { label: '已结束', value: '3' },
      ],
      // 表头
      tableColumns: [
        { prop: 'trainingName', label: '培训主题名称' },
        { prop: 'studyObject', label: '培训对象' },
        { prop: 'trainingLevel', label: '培训级别' },
        { prop: 'trainingDate', label: '培训日期' },
        { prop: 'trainingPlace', label: '培训地点' },
        { prop: 'trainingDuration', label: '培训时长' },
        { prop: 'lecturer', label: '主讲人' },
        { prop: 'trainingNumber', label: '培训人数' },
        { prop: 'trainingStatus', label: '签到状态' },
        { prop: 'status', label: '培训状态' },
        { prop: 'createUser', label: '创建人' },
        { prop: 'createTime', label: '创建时间' },
      ],
      // 表格数据
      tableData: [],
      // 弹框表单
      dialogForm: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        id: '',
      },
      // 弹框-表头
      dialogColumns: [
        { prop: 'name', label: '姓名' },
        { prop: 'sex', label: '性别' },
        { prop: 'idCard', label: '身份证号码' },
        { prop: 'phone', label: '联系方式' },
        { prop: 'proName', label: '工程名称' },
        { prop: 'consName', label: '承包商名称' },
        { prop: 'postName', label: '岗位' },
        { prop: 'workType', label: '工种' },
        { prop: 'isSign', label: '是否签到' },
        { prop: 'signTime', label: '签到时间' },
      ],
      // 弹框-表格数据
      dialogTableData: [],
      currentRow: {},
    }
  },
  created() {
    this.getList()
  },
  methods: {
    indexContinuous,
    // 查询
    handleQuery() {
      this.getList()
    },
    // 重置
    handleReset() {
      this.createTime = []
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // ... other methods
    getTrainingStatusType(status) {
      switch (status) {
        case '0':
          return 'info'
        case '1':
          return 'success'
        case '2':
          return 'danger'
        default:
          return ''
      }
    },
    getTrainingStatusLabel(status) {
      switch (status) {
        case '0':
          return '未签到'
        case '1':
          return '签到中'
        case '2':
          return '已结束'
        default:
          return ''
      }
    },
    getStatusType(startDate, endDate) {
      const now = new Date()
      if (new Date(startDate) > now) {
        return 'info'
      } else if (new Date(startDate) <= now && new Date(endDate) >= now) {
        return 'success'
      } else if (new Date(endDate) < now) {
        return 'danger'
      }
      return ''
    },
    getStatusLabel(startDate, endDate) {
      const now = new Date()
      if (new Date(startDate) > now) {
        return '待开始'
      } else if (new Date(startDate) <= now && new Date(endDate) >= now) {
        return '进行中'
      } else if (new Date(endDate) < now) {
        return '已结束'
      }
      return ''
    },
    // 获取表格数据
    getList() {
      console.log('获取列表', this.addDateRange(this.queryParams, this.createTime))
      getTrainingTasksList(this.addDateRange(this.queryParams, this.createTime)).then(res => {
        this.tableData = res.rows
        this.total = res.total
        console.log('res', res)
      })
    },
    // 新建培训
    handleCreate() {
      console.log('新建培训')
      this.$router.push({
        path: '/educationalTraining/learningManagement/training/newTraining',
      })
    },
    // 导出数据
    handleExport() {
      try {
        const params = this.addDateRange(this.queryParams, this.createTime)
        const url = '/exam/trainingTasks/export'
        const fileName = `培训_${new Date().getTime()}.xLsx`
        console.log('🚀 ~ 导出 ~ params:', params)
        this.derive(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    // 选择
    selectionChange(val) {
      console.log('选择', val)
    },
    // 开始签到
    handleSignIn(row) {
      console.log('开始签到')
      // 弹框提醒, 内容: 确定开启签到么？开启签到后本次培训不可再次编辑；
      // this.$confirm('<strong>确定开启签到么？</strong><br>开启签到后本次培训不可再次编辑；', '开始签到', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      //   dangerouslyUseHTMLString: true, // 是否将 message 属性作为 HTML 片段处理
      // })
      //   .then(() => {
      //     // 开启签到
      //     changeSignStatus({ id: this.row.id, status: 1 }).then((res) => {
      //       this.$message.success('开启成功')
      //     }).catch((error) => {
      //       this.$message.error(error)
      //     })
      //   })
      //   .catch(() => {
      //     // 取消
      //   })
      this.$modal
        .confirm('<strong>确定开启签到么？</strong><br>开启签到后本次培训不可再次编辑；')
        .then(function () {
          return changeSignStatus({ id: row.id, taskType: 1 })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('开启成功')
        })
        .catch(() => {})
    },
    // 结束签到
    handleSignOut(row) {
      console.log('结束签到')
      // 确定结束签到么？结束签到后未进场人员不可再次签到；
      // this.$confirm('<strong>确定结束签到么？</strong><br>结束签到后未进场人员不可再次签到；', '结束签到', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      //   dangerouslyUseHTMLString: true,
      // })
      //   .then(() => {
      //     // 结束签到
      //     changeSignStatus({ id: this.row.id, status: 2 }).then((res) => {
      //       this.$message.success('开启成功')
      //     }).catch((error) => {
      //       this.$message.error(error)
      //     })
      //   })
      //   .catch(() => {
      //     // 取消
      //   })
      this.$modal
        .confirm('<strong>确定结束签到么？</strong><br>结束签到后未进场人员不可再次签到；')
        .then(function () {
          return changeSignStatus({ id: row.id, taskType: 2 })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('结束成功')
        })
        .catch(() => {})
    },
    // 编辑
    handleEdit(row) {
      console.log('编辑', row)
      // 路由跳转 task
      this.$router.push({
        // 路由地址
        path: '/educationalTraining/learningManagement/training/editTraining',
        // 传递参数
        query: {
          trainId: row.id,
        },
      })
    },
    // 删除
    handleDelete(row) {
      console.log('删除', row)
      this.$modal
        .confirm('<strong>确定删除此培训任务吗？</strong>')
        .then(function () {
          return delTrainingTaskById({ id: row.id })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    // 签到详情
    async handleSignInDetail(row) {
      this.currentRow = row
      console.log('签到详情')
      this.selectSignInList()
      await (this.dialogVisible = true)
      this.dialogForm.name = ''
    },
    selectSignInList() {
      console.log('查询签到列表')
      //查询签到列表
      this.dialogForm.id = this.currentRow.id
      selectTrainingDataList(this.dialogForm).then(res => {
        console.log('查询签到列表', res)
        this.dialogTableData = res.rows
        this.dialogTotal = res.total
      })
    },
    // 培训数据
    handleTrainData(row) {
      console.log('培训数据')
      console.log('🚀 ~ handleTrainData ~ row:', row)
      this.$router.push({
        // 路由地址
        path: '/educationalTraining/learningManagement/training/dataAnalysis',
        // 传递参数
        query: row,
      })
      // this.$router.push({ path: '/educationalTraining/learningManagement/training/dataAnalysis' })
    },
    // 弹框-查询
    handleDialogQuery() {
      this.selectSignInList(this.currentRow)
      console.log('🚀 ~ handleQuery ~ handleQuery:', this.dialogForm.name)
    },
    // 弹框-重置
    handleDialogReset() {
      console.log('弹框-重置')
      this.dialogForm.name = ''
      this.selectSignInList(this.currentRow)
    },
    // 弹框-导出数据
    handleDialogExport() {
      try {
        this.dialogForm.id = this.currentRow.id
        const params = this.dialogForm
        const url = '/exam/trainingTasks/exportCheckInDetails'
        const fileName = `签到详情_${new Date().getTime()}.xLsx`
        console.log('🚀 ~ 导出 ~ params:', params)
        this.derive(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    // 弹框-选择
    dialogSelectionChange(val) {
      console.log('弹框-选择', val)
    },
  },
}
</script>

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