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

export default class PlayerAction extends BaseACTION {
  /* 获取章节列表信息 */
  getChapterList (cid, sid, _id) {
    return Player.getChapterList(cid, sid, _id).then(_res => {
      let i = 0
      let j = 0
      let nextVideo = {}
      let prevVideo = {}
      /* 计算上一章 和 下一章 */
      for (; i < _res.chapters.length; i++) {
        const _ = _res.chapters[i]
        for (j = 0; j < _.children.length; j++) {
          if (_.children[j].resource_id === _id) {
            // wx.setNavigationBarTitle({ title: _.children[j].name || '音视频' });
            if (j - 1 >= 0) {
              prevVideo = {
                id: _.children[j - 1].resource_id,
                time: (_.children[j - 1].video && tools.convertTime.durationToTimeString(_.children[j - 1].video.video_length)) || '',
                name: _.children[j - 1].name
              }
            } else if (i - 1 >= 0) {
              const _temp = _res.chapters[i - 1]
              prevVideo = {
                id: _temp.children[_temp.children.length - 1].resource_id,
                time: (_temp.children[_temp.children.length - 1].video && tools.convertTime.durationToTimeString(_temp.children[_temp.children.length - 1].video.video_length)) || '',
                name: _temp.children[_temp.children.length - 1].name
              }
            }
            if (j + 1 < _.children.length) {
              nextVideo = {
                id: _.children[j + 1].resource_id,
                time: (_.children[j + 1].video && tools.convertTime.durationToTimeString(_.children[j + 1].video.video_length)) || '',
                name: _.children[j + 1].name
              }
            } else if (i + 1 < _res.chapters.length) {
              const _temp = _res.chapters[i + 1]
              nextVideo = {
                id: _temp.children[0].resource_id,
                time: (_temp.children[0].video && tools.convertTime.durationToTimeString(_temp.children[0].video.video_length)) || '',
                name: _temp.children[0].name
              }
            }
          }
        }
      }
      let curJson = {}
      const json = {
        title: _res.course_name,
        sid: _res.semester_id,
        cid: _res.course_id,
        currentChapterId: _id,
        survey: _res.survey, // 判别教学评估，是否已经填写
        course: _res.chapters.map((_, i) => {
          return {
            title: _.name,
            chapters: _.children.map((__, j) => {
              const _homework = (__.type === 3 && __.homework && __.homework.work_type === 1 && __.homework) || ''
              if (_homework) {
                _homework.course_id = _res.course_id
                _homework.chapter_id = __.id
                _homework.work_id = __.resource_id
                _homework.semester_id = _res.semester_id
              }
              const _chapterWork = (__.type === 3 && __.homework && __.homework.work_type === 2 && __.homework) || ''
              const _chapterRead = (__.type === 4 && __.reading) || ''
              const _chapterVideo = (__.type === 2 && __.video) || ''
              if (_chapterVideo) {
                _chapterVideo.pdf = __.pdf || ''
              }
              if (_id === __.resource_id) {
                curJson = {
                  id: __.resource_id,
                  video_provider: (__.video && __.video.video_provider) || '',
                  time: (__.video && tools.convertTime.durationToTimeString(__.video.video_length)) || '',
                  name: __.name,
                  chapterId: __.id, // 需要chapterId 用来 提交 作业或问题 , 这个 chapterId 是 每个章节下 对应课程的 id，不是 章节id
                  type: __.type,
                  work_type: (__.homework && __.homework.work_type) || '',
                  homework: _homework,
                  chapterRead: _chapterRead,
                  chapterWork: _chapterWork,
                  chapterVideo: _chapterVideo,
                  live: __.live || ''
                }
              }
              if (__.live && __.live.id) {
                let str = ''
                switch (__.live.live_status) {
                  case 0: str = '直播未开始'; break
                  case 1: str = '正在直播'; break
                  case 2: str = '直播结束'; break
                  case 101: str = '直播结束，视频剪辑中'; break // 录制开始
                  case 102: str = '直播结束，视频剪辑中'; break // 录制结束
                  case 103: str = '观看回放'; break
                  default: str = '直播未开始'
                }
                // 5分钟内显示“即将开始”，5~1小时内“N分钟后开始”，1~24小时内“N小时后开始”，1天以上“N天后开始”天就显示年月日
                if (__.live.live_status === 0 && __.live.start_time) {
                  const time = (new Date(__.live.start_time).getTime() - new Date().getTime()) / 1000
                  if (time <= 5 * 60) {
                    str = '即将开始'
                  } else if (time <= 1 * 60 * 60) {
                    str = parseInt(time / 60) + '分钟后开始'
                  } else if (time <= 24 * 60 * 60) {
                    str = parseInt(time / (60 * 60)) + '小时' + parseInt(time / 60 % 60) + '分钟后开始'
                  } else {
                    str = parseInt(time / (24 * 60 * 60)) + '天后开始'
                  }
                }
                if (__.live.live_status === 103 && __.live.enable_record !== undefined && __.live.enable_record !== null && !__.live.enable_record) {
                  str = ''
                }
                __.live.statusStr = str
              }

              return {
                id: __.resource_id,
                video_provider: (__.video && __.video.video_provider) || '',
                time: (__.video && tools.convertTime.durationToTimeString(__.video.video_length)) || '',
                name: __.name,
                type: __.type,
                work_type: (__.homework && __.homework.work_type) || '',
                homework: _homework,
                chapterRead: _chapterRead,
                chapterWork: _chapterWork,
                chapterVideo: _chapterVideo,
                live: __.live || ''
              }
            })
          }
        }),
        nextVideo: nextVideo,
        prevVideo: prevVideo
      }
      json.course.push({
        title: '大作业及资料',
        chapters: [{
          name: '课程大作业',
          id: 'course_work'
        }, {
          name: '课程资料',
          id: 'course_info'
        }, {
          name: '教学评估',
          id: 'teach_evaluation'
        }]
      })
      if (_res.course_examination) {
        json.course[json.course.length - 1].chapters.push({
          name: '课程考试',
          type: 'exam',
          id: _res.course_examination
        })
      }
      const courseWork = _res.curriculum || {}
      courseWork.end_date = _res.end_date
      courseWork.essay_date = _res.essay_date
      // callback(json) // 可以不使用callback 因为使用then
      return {
        json: json,
        courseInfo: _res.files || [],
        courseWork: _res.curriculum || {},
        curJson: curJson
      }
    })
  }

  /* 获取对应某个章节的详细信息 */
  getCurrentChapterDetail (vid) {
    return Player.getCurrentChapterDetail(vid).then(_res => {
      const json = {
        video: {
          src: _res.video[0].playurl,
          spareSrc: 'http://pd4t7ae3m.bkt.clouddn.com/test.mp4' // 正式环境时，需要将 contentVideo 中 spareSrc 改成 src
        },
        audio: {
          src: _res.audio[0].url,
          poster: (_res.ppts && _res.ppts[0] && _res.ppts[0].ppt_url) || ''
        },
        image: {
          imgUrls: (_res.ppts && _res.ppts.map(function (_, i) { return _.ppt_url })) || [],
          current: 0,
          selectIndex: 0,
          timeArr: (_res.ppts && _res.ppts.map(function (_, i) { return _.ppt_point })) || []
        },
        rData: _res
      }
      // callback(json) // 可以不使用callback 因为使用then
      return json
    })
  }

  /* 获取对应某个章节的详细信息 */
  getCurrentChapterDetailAliyun (vid) {
    return Player.getCurrentChapterDetailAliyun(vid).then(_res => {
      window.G && (window.G.m3u8RequestId = _res.request_id)
      const json = {
        video: {
          FD: _res.video.FD,
          LD: _res.video.LD,
          SD: _res.video.SD
        },
        audio: {
          src: _res.video.SQ,
          poster: (_res.ppts && _res.ppts[0] && _res.ppts[0].ppt_url) || ''
        },
        image: {
          imgUrls: (_res.ppts && _res.ppts.map(function (_, i) { return _.ppt_url })) || [],
          current: 0,
          selectIndex: 0,
          timeArr: (_res.ppts && _res.ppts.map(function (_, i) { return _.ppt_point })) || []
        },
        rData: _res
      }
      // callback(json) // 可以不使用callback 因为使用then
      return json
    })
  }

  /* 获取进度信息 */
  getProgress (vid, did, sid) {
    return Player.getProgress(vid, did, sid).then(res => {
      // callback(res) // 可以不使用callback 因为使用then
      return {
        id: res.id,
        cpt: parseInt(res.cpt),
        mpt: parseInt(res.mpt),
        pt: parseInt(res.pt),
        progress: res.progress,
        sign: res.sign,
        map: res.map || []
      }
    })
  }

  /* 提交进度信息 */
  updateProgress (obj) {
    return Player.updateProgress(obj).then(res => res)
    // return new Promise((resolve, reject) => { resolve({ success: true }) }) // 测试 视频时，不上传 视频数据
  }

  /* 获取试题信息 */
  getExamDetail (sid, cid, eid) {
    return Player.getExamDetail(sid, cid, eid).then(res => {
      // callback(res) // 可以不使用callback 因为使用then
      return res
    })
  }

  /* 提交考试信息 */
  submitExamDetail (param) {
    return Player.submitExamDetail(param).then(res => {
      // callback(res) // 可以不使用callback 因为使用then
      return res
    })
  }

  /* 获取对应 作业或问题 回答 */
  getHomework (sid, cid, id) {
    return Player.getHomework(sid, cid, id).then(res => res)
  }

  /**
   * 文件上传
   */
  uploadFile (obj) { return Player.uploadFile(obj).then(res => res) }
  /* 提交作业 */
  updateHomework (obj) { return Player.updateHomework(obj).then(res => res) }
  /* 获取大作业 回答 */
  getCourseHomework (sid, cid) { return Player.getCourseHomework(sid, cid).then(res => res) }
  /* 获取作业截止时间 */
  getHomeworkStopTime (sid, cid, chapterId) { return Player.getHomeworkStopTime(sid, cid, chapterId).then(res => res) }
  /* 提交大作业 */
  updateCourseHomework (sid, cid, obj) { return Player.updateCourseHomework(sid, cid, obj).then(res => res) }
  /* 提交课程考核 */
  updateSurveyAnswer (obj) { return Player.updateSurveyAnswer(obj).then(res => res) }
  /* 获取当前最新直播提醒 */
  getNewLiveMsg () { return Player.getNewLiveMsg().then(res => res) }
  /* 获取手机直播列表 */
  getLiveList () { return Player.getLiveList().then(res => res) }
  /* 获取云课堂 url */
  getCloudUrl () { return Player.getCloudUrl().then(res => res) }
}
