import BaseACTION from './base_action'
import { Course } from '@api'
import tool from '@tool'

/**
 * 小程序 跟 PC 区别
 * 1. PC 直接使用 then，小程序 需要 callback
 * 2. PC 直接返回 对象，小程序 外层再保证一次返回 { status: xxx, data: data }
 */

export default class CourseAction extends BaseACTION {
  /* 获取学期分类信息 */
  getLearnFind () {
    return Course.getLearnFind().then(data => {
      data = data || []
      let json = [{ val: '-1', name: this.getVueInstance().$t('action.courseAction.all') }]
      if (!data.length) json = []
      for (let i = 0; i < data.length; i++) {
        const _list = data
        json.push({
          val: _list[i].id,
          name: _list[i].semester_name
        })
      }
      return json
    })
  }

  /* 获取所有课程列表 - 选课广场 和 我的课程 共用同一个,通过 isMy判断 */
  getCourseList (isMy, param) {
    const _vIn = this.getVueInstance()
    /**
     * 区别：
     * 1. progress 是 number
     */
    return Course.getCourseList(isMy, param).then(data => {
      data = data || []
      const json = []
      for (let i = 0; i < data.length; i++) {
        const cur = data[i]
        const _cur = data[i].curriculum
        /* 课程类型 */
        const _type = parseInt(cur.course_type)
        const str1 = _type === 1 ? _vIn.$t('action.courseAction.mustLearn')
          : (_type === 2 ? _vIn.$t('action.courseAction.changeLearn')
            : (_type === 3 ? _vIn.$t('action.courseAction.repeatLearn') : ''))
        json.push({
          id: cur.course_id,
          sid: cur.semester_id,
          src: (_cur && _cur.curriculum_picture) || '',
          title: cur.course_name,
          arrTab: [(((_cur && _cur.curriculum_credit) || 0) + _vIn.$t('action.courseAction.credit')), str1, cur.semester_name],
          status: _cur.is_enabled ? _vIn.$t('action.courseAction.publish') : _vIn.$t('action.courseAction.noPublish'),
          time: cur.begin_date.split(' ')[0] + _vIn.$t('action.courseAction.to') + cur.end_date.split(' ')[0],
          myStatus: cur.selected !== 0 ? (cur.grade ? (_vIn.$t('action.courseAction.totalScore') + cur.grade) : _vIn.$t('action.courseAction.alreadyChange'))
            : _vIn.$t('action.courseAction.noChange'),
          progress: cur.video_progress
        })
      }
      // callback(json) // 可以不使用callback 因为使用then
      return json
    })
  }

  /* 获取某个课程详细信息 - 课程考核 和 课程讨论单独获取 */
  getCourseDetail (cid, sid) {
    const _vIn = this.getVueInstance()
    return Course.getCourseDetail(cid, sid).then(data => {
      const cur = data
      const _cur = cur.curriculum
      /* 课程类型 */
      const _type = cur.course_type
      const str1 = _type === 1 ? _vIn.$t('action.courseAction.mustLearn')
        : (_type === 2 ? _vIn.$t('action.courseAction.changeLearn')
          : (_type === 3 ? _vIn.$t('action.courseAction.repeatLearn') : ''))
      const json = {
        course_check_type: cur.course_check_type,
        headerInfo: {
          isStart: !!cur.selected, // 是否为开始学习按钮 或者 选课按钮
          id: cur.course_id,
          sid: cur.semester_id,
          bgSrc: (_cur && _cur.curriculum_picture) || '../icons/home/default.jpg',
          title: cur.course_name,
          arrTab: [(((_cur && _cur.curriculum_credit) || 0) + _vIn.$t('action.courseAction.credit')), str1, cur.semester_name],
          status: _cur.is_enabled ? _vIn.$t('action.courseAction.publish') : _vIn.$t('action.courseAction.noPublish'),
          time: cur.begin_date.split(' ')[0] + _vIn.$t('action.courseAction.to') + cur.end_date.split(' ')[0],
          progress: cur.video_progress,
          survey: cur.survey // 判别教学评估，是否已经填写
        },
        tabs0Content: {},
        tabs1ChapterList: {}
      }
      /* 课程简介 */
      json.tabs0Content = {
        text: _cur && _cur.curriculum_represent,
        teachers: []
      }
      for (let i = 0; i < cur.lecturers.length; i++) {
        const item = cur.lecturers[i]
        json.tabs0Content.teachers.push({
          src: item.lecturer_avatar,
          name: item.lecturer_name,
          edu: item.lecturer_education || '',
          job: item.lecturer_office || '',
          unit: item.lecturer_title || ''
        })
      }
      const findChapter = function (id, list) {
        for (const item of list) {
          if (item.resource_id === id) {
            return item
          }
          if (item.children && item.children.length) {
            const found = findChapter(id, item.children)
            if (found) {
              return found
            }
          }
        }
      }
      /* 课程内容 */
      json.tabs1ChapterList = {
        currentChapter: findChapter(cur.latest_play, data.chapters),
        currentChapterId: cur.latest_play || '',
        currentVideoProvider: cur.latest_play_type || '1',
        course: cur.chapters.map((_, i) => {
          return {
            id: _.id,
            title: _.name,
            isUp: true,
            chapters: _.children.map((__, j) => {
              const _homework = (__.type === 3 && __.homework && __.homework.work_type === 1 && __.homework) || ''
              if (_homework) {
                _homework.course_id = data.course_id
                _homework.chapter_id = __.id
                _homework.work_id = __.resource_id
                _homework.semester_id = data.semester_id
              }
              if (__.live && __.live.id) {
                __.live.live_status = parseInt(__.live.live_status)
                let str = ''
                switch (__.live.live_status) {
                  case 1: str = _vIn.$t('live.notStarted'); break
                  case 2: str = _vIn.$t('live.liveStreaming'); break
                  case 3: str = _vIn.$t('live.liveEnd'); break
                  case 4: str = _vIn.$t('live.start'); break
                  case 5: str = _vIn.$t('live.liveEnd'); break
                  default: str = _vIn.$t('live.notStarted')
                }
                // 5分钟内显示“即将开始”，5~1小时内“N分钟后开始”，1~24小时内“N小时后开始”，1天以上“N天后开始”天就显示年月日
                if (__.live.live_status === 1 && __.live.start_time) {
                  const time = (new Date(__.live.start_time).getTime() - new Date().getTime()) / 1000
                  if (time <= 5 * 60) {
                    str = _vIn.$t('live.start')
                  } else if (time <= 1 * 60 * 60) {
                    str = _vIn.$t('live.startInMinutes', { minutes: parseInt(time / 60) })
                  } else if (time <= 24 * 60 * 60) {
                    str = _vIn.$t('live.startInHours', { h: parseInt(time / (60 * 60)), min: parseInt(time / 60 % 60) })
                  } else {
                    str = _vIn.$t('live.startInDay', { day: parseInt(time / (24 * 60 * 60)) })
                  }
                }
                if (__.live.live_status === 3 && __.live.enable_record && __.live.record_url) {
                  str = _vIn.$t('live.watchReplay')
                }
                __.live.statusStr = str
              }

              return {
                cid: cur.course_id,
                sid: cur.semester_id,
                vid: __.resource_id,
                id: __.id,
                video_provider: (__.video && __.video.video_provider) || '',
                duration: (__.video && __.video.video_length) || 0,
                time: (__.video && tool.convertTime.durationToTimeString(__.video.video_length)) || '',
                name: __.name,
                type: __.type,
                work_type: (__.homework && __.homework.work_type) || '',
                homework: _homework,
                live: __.live || ''
              }
            })
          }
        })
      }
      cur.curriculum.curriculum_essay && json.tabs1ChapterList.course.push({
        title: _vIn.$t('action.courseAction.courseWork'),
        isUp: true,
        chapters: [],
        id: 'course_work',
        sid: sid,
        cid: cid,
        type: 99
      })
      json.tabs1ChapterList.course.push({
        title: _vIn.$t('action.courseAction.courseData'),
        isUp: true,
        chapters: [],
        id: 'course_info',
        sid: sid,
        cid: cid,
        type: 100
      })
      // json.tabs1ChapterList.course.push({
      //   title: _vIn.$t('action.courseAction.teachingEvaluation'),
      //   isUp: true,
      //   chapters: [],
      //   id: 'teach_evaluation',
      //   sid: sid,
      //   cid: cid,
      //   type: 102
      // })
      if (cur.course_examination) {
        let courseExamChildren = []
        if (data.exist_examination && data.exist_examination.length > 1) {
          courseExamChildren = data.exist_examination.map((item, index) => {
            const map = ['一', '二', '三']
            return {
              name: `第${map[index]}次考试`,
              id: 'course_exam',
              offset: index,
              sid: sid,
              cid: cid,
              examId: cur.course_examination,
              type: 101
            }
          })
        }
        json.tabs1ChapterList.course.push({
          title: _vIn.$t('action.courseAction.courseExam'),
          isUp: true,
          chapters: courseExamChildren,
          id: 'course_exam',
          sid: sid,
          cid: cid,
          examId: cur.course_examination,
          type: 101
        })
      }
      /* 课程考核 考核标准文案读取  */
      json.tabs3richTest = cur.course_evaluation
      // callback(json) // 可以不使用callback 因为使用then
      return json
    })
  }

  /* 获取课程考核信息 */
  getCourseAssess (cid, sid) {
    const _vIn = this.getVueInstance()
    return Course.getCourseAssess(cid, sid).then(data => {
      const cur = data
      const video = []
      for (const i in cur.video_evaluation) {
        const _ = cur.video_evaluation[i]
        const tempArr = []
        for (const j in _.sections) {
          const __ = _.sections[j]
          tempArr.push({
            name: __.title,
            time: (__.duration && tool.convertTime.durationToTimeString(__.duration)) || '00:00',
            progress: (__.progress && (__.progress + '%')) || '0%',
            id: __.id
          })
        }
        video.push({
          title: _.title,
          arr: tempArr,
          sid: sid,
          cid: cid
        })
      }
      const homewrok = []
      for (const i in cur.homework_evaluation) {
        const _ = cur.homework_evaluation[i]
        const tempArr = []
        for (const j in _.sections) {
          const __ = _.sections[j]
          tempArr.push({
            name: __.title,
            created_time: __.created_time || '',
            score: __.score === null ? _vIn.$t('action.courseAction.none') : __.score
          })
        }
        homewrok.push({
          title: _.title,
          arr: tempArr
        })
      }
      const json = {
        raw: cur,
        score: cur.course_score,
        duration: tool.convertTime.durationToTimeString(cur.course_duration || 0),
        progress: cur.course_progress,
        video: video,
        homewrok: homewrok,
        essay: {
          created_time: cur.essay_evaluation.created_time || '',
          status: cur.essay_evaluation.status || _vIn.$t('action.courseAction.none'),
          score: cur.essay_evaluation.score || _vIn.$t('action.courseAction.none')
        }
      }
      // callback(json) // 可以不使用callback 因为使用then
      return json
    })
  }

  /* 选课 */
  selectCourse (cid, sid) {
    return Course.selectCourse(cid, sid).then(res => {
      // callback(res) // 可以不使用callback 因为使用then
      return res
    })
  }

  /* 退课 */
  outSelectCourse (cid, sid) {
    return Course.outSelectCourse(cid, sid).then(res => {
      // callback(res) // 可以不使用callback 因为使用then
      return res
    })
  }
}
