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
                  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 === 2 && __.live.enable_record && __.live.record_url) {
                  str = '观看回放'
                }
                __.live.statusStr = str
              }

              return {
                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 || ''
              }
            })
          }
        }),
        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,
        rawResponse: _res
      }
    })
  }

  /* 获取对应某个章节的详细信息 */
  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) }
  /* 获取考卷信息 */
  getExamInfo (cid, sid) {
    return Player.getExamInfo(cid, sid).then(_res => {
      const exam = {}
      exam.id = _res.id
      exam.title = _res.title
      exam.score = {}
      exam.examination = _res.examination.map(exam => {
        for (let i = 0; i < exam.radioList.length; i++) {
          exam.radioList[i].user_answer = ''
          exam.radioList[i].right_answer = ''
          exam.radioList[i].get_score = -1
        }
        for (let i = 0; i < exam.checkboxList.length; i++) {
          exam.checkboxList[i].user_answer = []
          exam.checkboxList[i].right_answer = []
          exam.checkboxList[i].get_score = -1
        }
        for (let i = 0; i < exam.shortAnswerList.length; i++) {
          exam.shortAnswerList[i].user_answer = ''
          exam.shortAnswerList[i].get_score = -1
          exam.shortAnswerList[i].attachments = []
          exam.shortAnswerList[i].upload = {
            type: 'upload-form',
            label: '附件上传：',
            model: 'attachments',
            action: webConf.apiBaseURL + '/util/upload-file',
            data: {
              special: 'exam'
            },
            attrs: {
              multiple: true,
              headers: {
                tenant: 'sofia'
              }
            },
            html: `
              <div style="color: #72818c; font-size: 14px;">
                <p style="margin: 0;">支持doc,docx,ppt,xls,txt,rar,zip,pdf,jpg,pic,png格式的文件，文件小于30M。</p>
              </div>
            `
          }
        }
        return exam
      })
      return exam
    })
  }

  /* 获取考卷结果 */
  getExamAnswer (cid, sid, eid, obj) {
    return Player.getExamAnswer(cid, sid, eid, obj).then(_res => {
      if (_res.code) { return _res }
      const exam = {}
      let tmp = null
      exam.id = _res.id
      exam.title = _res.title
      exam.type = _res.type
      exam.score = _res.score
      exam.isPublished = _res.is_published || ''
      exam.submitted_time = _res.submitted_time
      exam.examination = _res.sheet.map(exam => {
        exam.radioList = exam.radioList || []
        for (let i = 0; i < exam.radioList.length; i++) {
          tmp = exam.radioList[i]
          if (!tmp.user_answer) tmp.user_answer = ''
          if (!tmp.right_answer) tmp.right_answer = ''
          if (!tmp.get_score) tmp.get_score = -1
        }
        exam.checkboxList = exam.checkboxList || []
        for (let i = 0; i < exam.checkboxList.length; i++) {
          tmp = exam.checkboxList[i]
          if (!tmp.user_answer || !tmp.user_answer.length) tmp.user_answer = []
          // if (!tmp.right_answer || !tmp.right_answer.length) tmp.right_answer = []
          tmp.right_answer = tmp.right_answer || []
          if (!tmp.get_score) tmp.get_score = -1
        }
        exam.shortAnswerList = exam.shortAnswerList || []
        for (let i = 0; i < exam.shortAnswerList.length; i++) {
          tmp = exam.shortAnswerList[i]
          tmp.user_answer = tmp.user_answer ? Base64.decode(tmp.user_answer.replace(/ /gi, '+')) : ''
          if (!tmp.attachments || !tmp.attachments.length) tmp.attachments = []
          tmp.upload = {
            type: 'upload-form',
            label: '附件上传：',
            model: 'attachments',
            action: webConf.apiBaseURL + '/util/upload-file',
            data: {
              special: 'exam'
            },
            attrs: {
              multiple: true,
              headers: {
                tenant: 'sofia'
              }
            },
            html: `
              <div style="color: #72818c; font-size: 14px;">
                <p style="margin: 0;">支持doc,docx,ppt,xls,txt,rar,zip,pdf,jpg,pic,png格式的文件，文件小于30M。</p>
              </div>
            `
          }
        }
        return exam
      })
      return exam
    })
  }

  /* 获取考试状态 */
  getExamStatus (cid, sid, eid) {
    return Player.getExamStatus(cid, sid, eid).then(_res => {
      /* 00: 考场未开放，不允许进入
      10：考场开放，允许进入
      20：开始答题
      90：考试已结束 */
      return _res
    })
  }

  /* 提交考卷 */
  submitExam (cid, sid, eid, obj) {
    return Player.submitExam(cid, sid, eid, obj).then(_res => {
      return _res
    })
  }
}
