<template>
  <div class="app-container">
    <div v-if="!showDetails && !showStudy">
      <el-row>
        <el-col :span="16">
          <el-form :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="timeRange">
              <el-date-picker
                v-model="queryParams.timeRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                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-col>
      </el-row>
      <el-row :gutter="20" style="margin-left: 30px">
        <el-col :span="20">
          <el-tag class="tag-item" @click="handleQuery('')">全部（{{ totalNum }}）</el-tag>
          <el-tag class="tag-item" type="success" @click="handleQuery(1)">已完成（{{ finishNum }}）</el-tag>
          <el-tag class="tag-item" type="info" @click="handleQuery(2)">未完成（{{ unFinishNum }}）</el-tag>
          <el-tag class="tag-item" type="danger" @click="handleQuery(3)">逾期（{{ overdueNum }}）</el-tag>
        </el-col>
      </el-row>

      <div class="card-wrapper">
        <div class="card-item" v-for="(item, index) in dataList" :key="index" @click="handleCard(item)">
          <CardModule :isLearn="true" :dataObj="item" />
        </div>
        <el-divider v-if="dataList.length == 0">暂无数据</el-divider>
      </div>
    </div>

    <!-- 详情页 -->
    <LearnTaskDetails
      ref="learnTaskDetails"
      v-else-if="showDetails && !showStudy"
      @handleBack="handleBack"
      @handleStudy="handleStudy"
    />

    <!-- 学习页 -->
    <StudyTemplate v-else-if="!showDetails && showStudy" @backDetail="backDetail" :params="videoParams" />
  </div>
</template>

<script>
import CardModule from '../components/CardModule'
import LearnTaskDetails from './learnTaskDetails'
import StudyTemplate from './StudyTemplate'
import { getLearningList, getStudyTaskStatusNum } from '@/api/educTrainLearn'

export default {
  components: { CardModule, LearnTaskDetails, StudyTemplate },
  name: 'learnTask',
  data() {
    return {
      userType: this.$store.state.user.userType,
      proId: this.$store.state.user.thisIds.proId,
      showDetails: false, // 是否显示详情
      showStudy: false, // 是否显示学习
      queryParams: {
        keyWord: '',
        timeRange: [],
      },
      totalNum: 0, // 总数
      finishNum: 0, // 已完成
      unFinishNum: 0, // 未完成
      overdueNum: 0, // 逾期
      dataList: [],
      videoParams: {
        isVideo: false, // 是否是视频
        studyUrl: '', // 学习地址
        videoInitialTime: 15,
      },
      taskStatus: '',
    }
  },
  created() {
    this.getList()
    this.getTaskStatusNum()
  },
  methods: {
    handleQuery(taskStatus) {
      this.taskStatus = taskStatus || ''
      this.getList()
      this.getTaskStatusNum()
    },
    handleReset() {
      this.queryParams = {
        keyWord: '',
        timeRange: [],
      }
      this.taskStatus = ''
      this.getList()
      this.getTaskStatusNum()
    },
    // 获取列表
    async getList() {
      console.log('🚀 ~ 获取列表-参数', this.queryParams)
      try {
        this.dataList = []
        this.finishNum = 0
        this.unFinishNum = 0
        let startTime = ''
        let endTime = ''
        if (this.queryParams.timeRange && this.queryParams.timeRange.length > 0) {
          startTime = this.queryParams.timeRange[0]
          endTime = this.queryParams.timeRange[1]
        }
        const params = {
          pageNum: 1,
          pageSize: 999,
          userType: this.userType,
          proId: this.proId,
          keyWord: this.queryParams.keyWord,
          startTime,
          endTime,
          taskStatus: this.taskStatus
        }
        console.log('🚀 ~ getList ~ params:', params)
        const res = await getLearningList(params)
        console.log('🚀 ~ getList ~ data:', res)
        this.dataList = res.data
        this.dataList.forEach(item => {
          if (item.isStudyFinish == 1) {
            item.finish = true
            item.unFinish = false
            item.overdue = false
          } else {
            item.finish = false
            item.unFinish = true
            item.overdue = false
          }
          if (item.overdueOrNot == '1') {
            item.finish = false
            item.unFinish = false
            item.overdue = true
          }
        })
        // this.finishNum = this.dataList.filter(item => item.finish).length
        // this.unFinishNum = this.dataList.filter(item => item.unFinish).length
        // console.log('🚀 ~ getList ~ this.unFinishNum:', this.unFinishNum)
        // this.overdueNum = this.dataList.filter(item => item.overdue).length
      } catch (error) {
        console.log('🚀 ~ 获取列表-错误', error)
      }
    },
    // 获取任务状态数量
    async getTaskStatusNum() {
      try {
        const params = {
          proId: this.proId,
          userType: this.userType,
        }
        const res = await getStudyTaskStatusNum(params)
        console.log('🚀 ~ 获取任务状态数量 ~ res', res)
        this.totalNum = res.data.totalNum
        this.finishNum = res.data.finishNum
        this.unFinishNum = res.data.unFinishNum
        this.overdueNum = res.data.overdueNum
      } catch (error) {
        console.log('🚀 ~ 获取任务状态数量 ~ error', error)
      }
    },
    // 点击卡片
    async handleCard(item) {
      console.log('🚀 ~ 点击卡片', item)
      // learningDate: "2024-10-31 ~ 2024-11-02" 不在时间段内 不能学习
      if (item.learningDate) {
        const dateArr = item.learningDate.split(' ~ ')
        const startTime = new Date(dateArr[0] + ' 00:00:00').getTime()
        const endTime = new Date(dateArr[1] + ' 23:59:59').getTime()
        const nowTime = new Date().getTime()
        if (nowTime < startTime || nowTime > endTime) {
          this.$message.error('不在学习时间范围内')
          return
        }
      }
      this.showDetails = true
      this.showStudy = false
      setTimeout(() => {
        this.$refs.learnTaskDetails.getList(item)
      }, 100)
    },
    // 返回
    handleBack() {
      this.showDetails = false
      this.showStudy = false
      setTimeout(() => {
        this.$tab.refreshPage()
      }, 100)
    },
    // 返回详情
    backDetail(item) {
      console.log('🚀 ~ backDetail ~ 文件学习返回:')
      this.showDetails = true
      this.showStudy = false
      setTimeout(() => {
        this.$refs.learnTaskDetails.getList(item)
      }, 100)
    },
    // 学习
    handleStudy(row, isVideo, item) {
      console.log('🚀 ~ 开始学习', row, item, isVideo)
      this.showDetails = false
      this.showStudy = true
      this.videoParams = {
        isVideo: isVideo,
        ...row,
        studyUrl: row.url,
        videoInitialTime: Number(row.learningProgress) || 0,
        learnContent: row.fileName, // 学习内容
        learnDuration: row.duration, // 学习总时长
        item: item,
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.card-wrapper {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  .card-item {
    width: 33.33%;
    margin: 20px
  }
}
.tag-item {
  margin-right: 10px;
  cursor: pointer;
}
</style>
