<!--
 * @Author: ysh
 * @Date: 2025-03-05 15:01:52
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-03-27 13:37:00
-->
<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="资料名称" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入资料名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="title">
        <el-select v-model="queryParams.type" @change="handleQuery" clearable>
          <el-option label="视频" value="视频"></el-option>
          <el-option label="文档" value="文档"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <right-toolbar :search="false" @queryTable="getRecordsList"></right-toolbar>
    <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="addTrainRecord">添加参培记录</el-button>
    <el-button type="success" plain size="mini" icon="el-icon-view" @click="trainOpen = true">查看参培记录</el-button>
    <el-table :data="studyList" style="width: 100%" v-loading="loading" height="430px">
      <el-table-column align="center" label="序号" type="index" />
      <el-table-column align="center" label="资料名称" prop="resource.title" />
      <el-table-column align="center" label="类型" prop="resource.type"></el-table-column>
      <el-table-column align="center" label="学习进度" prop="lastPoint">
        <template slot-scope="scope">
          <el-progress :text-inside="true" :stroke-width="26" :status="formatStatus(scope.row.lastPoint)"
            :percentage="Number(scope.row.lastPoint)" text-color="#fff"></el-progress>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上次学习时间" prop="lastTime" />
      <el-table-column align="center" label="获得学时" prop="getHours" />
      <el-table-column align="center" label="操作" width="100px">
        <template slot-scope="{row}">
          <el-button type="text" @click="startStudy(row)">
            {{ row.lastPoint == 0 ? '开始学习' : row.lastPoint == 100 ? '复习' : '继续学习' }}
          </el-button>
          <el-button style="color: #F56C6C;" type="text" @click="cancelStudy(row)">
            取消学习
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
      :layout="'total, prev, pager, next,jumper'" :limit.sync="queryParams.pageSize" :autoScroll="false"
      @pagination="getRecordsList" />
    <el-dialog title="个人参培记录" :visible.sync="trainOpen" width="60%" append-to-body>
      <el-table :data="trainList" style="width: 100%" v-loading="loading" height="430px">
        <el-table-column label="序号" type="index" />
        <el-table-column label="上报人" align="center" prop="reportUser.nickName" />
        <el-table-column label="上报日期" align="center" prop="reportTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="培训名称" align="center" prop="trainName" />
        <el-table-column label="主要内容" align="center" prop="content" />
        <el-table-column label="学时" align="center" prop="hours" />
        <el-table-column label="部门审核人" align="center" prop="deptUser.nickName" />
        <el-table-column label="部门审核时间" align="center" prop="deptTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.deptTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门审核意见" align="center" prop="deptComment" />
      </el-table>
      <pagination v-show="trainTotal > 0" :total="trainTotal" :page.sync="trainQueryParams.pageNum"
        :layout="'total, prev, pager, next,jumper'" :limit.sync="trainQueryParams.pageSize" :autoScroll="false"
        @pagination="getTrainList" />
    </el-dialog>
  </div>
</template>

<script>
import { listStudy, getStudy, delStudy, addStudy, updateStudy } from "@/api/oa/study/myStudy";
import { listTrainApproval, getTrainApproval, delTrainApproval, addTrainApproval, updateTrainApproval } from "@/api/oa/study/trainApproval";
import { Snowflake } from '@/utils/snowFlake.js';
import { listDefinition, definitionStart } from "@/api/flowable/definition";
import { todoList, getNextFlowNodeByStart } from "@/api/flowable/todo";

export default {
  data() {
    return {
      loading: true,
      studyList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      trainOpen: false,
      trainLoading: true,
      trainList: [],
      trainTotal: 0,
      trainQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: this.$store.getters.userId
      }
    }
  },
  created() {
    this.getRecordsList();
    this.getTrainList();
  },
  methods: {
    getRecordsList() {
      this.loading = true;
      this.queryParams.userId = this.$store.getters.userId;
      listStudy(this.queryParams).then(response => {
        this.studyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询参培审核列表 */
    getTrainList() {
      this.trainLoading = true;
      listTrainApproval(this.trainQueryParams).then(response => {
        this.trainList = response.rows;
        this.trainTotal = response.total;
        this.trainLoading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getRecordsList();
    },
    startStudy(record) {
      if (record.lastPoint == 100 && record.resource.type === '视频') {
        this.$router.push({
          name: 'reviewStudy',
          params: { id: record.studyId }
        })
        return
      }
      const routeName = record.resource.type === '视频' ? 'VideoStudy' : 'PdfStudy';
      this.$router.push({
        name: routeName,
        params: { id: record.studyId }
      })
    },
    cancelStudy(row) {
      this.$modal.confirm('是否删除资料名称为"' + row.resource.title + '"的学习记录？').then(res => {
        delStudy(row.studyId).then(res => {
          this.$message.success(res.msg);
          this.getRecordsList();
        });
      })
    },
    formatStatus(row) {
      if (!row) {
        row = 0
        return 'exception'
      }
      if (row <= 20) {
        return 'exception'
      } else if (row > 20 && row <= 50) {
        return 'warning'
      } else if (row > 50 && row <= 80) {
        return null
      } else {
        return 'success'
      }
    },
    async addTrainRecord() {
      let response = await listDefinition({
        pageNum: 1,
        pageSize: 9999,
        name: "参培审核",
        category: "assess",
      })
      console.log(response);
      if (response.data.total == 1) {
        let obj = response.data.records[0]
        this.$confirm("是否发起参培审核？", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleStartProcess(obj)
        }).catch(() => { });
      }
    },
    handleStartProcess(row) {
      let formId = new Snowflake(1n, 1n, 0n).nextId().toString();
      getNextFlowNodeByStart({ deploymentId: row.deploymentId, variables: { formId: formId } }).then(res => {
        let data = res.data;
        const variables = {};
        const formData = {};
        formData.disabled = true;
        formData.formBtns = false;
        formData.formId = formId
        if (row.id) {
          variables.variables = formData;
          let routePath = this.getRoutePath(row);
          definitionStart(row.id, JSON.stringify(variables)).then(res => {
            this.$modal.msgSuccess(res.msg);
            let procInstanceId = res.data;
            todoList({
              pageNum: 1,
              pageSize: 99999999, processInsId: procInstanceId
            }).then(toDoRes => {
              let records = toDoRes.data.records;
              if (records.length == 1) {
                records = records[0]
              }
              this.$router.push({
                path: routePath,
                query: {
                  procInsId: records.procInsId,
                  executionId: records.executionId,
                  deployId: records.deployId,
                  taskId: records.taskId,
                  taskName: records.taskName,
                  startUser: records.startUserName + '-' + records.startDeptName,
                  formId: formData.formId,
                  procDefName: records.procDefName
                }
              })
            })
          })
        }
      })
    },
    getRoutePath(row) {
      let path;
      for (let p of this.publicData.pathRoute) {
        if (p.name == row.name) {
          path = p.path
          break
        } else {
          path = '/flowable/task/todo/detail/index'
        }
      }
      return path
    },
  },
}
</script>

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