// pages/taskDetail/taskDetail.js
const app = getApp()
const util = require("../../utils/util")
const urlDef = require("../../utils/urls")

// const recordManager = wx.getRecorderManager() //录音对象
const audioContext = wx.createInnerAudioContext() //音频播放对象
Page({

  /**
   * 页面的初始数据
   */
  data: {
    curStu: null,
    homeworkId: null,
    curVideo: '',
    videoFlag: 0,
    videoContext: '',
    curAudio: '',
    curAudioIndex: -1,
    audioPause: false,
    doTaskFlag: false,
    entity: null,
    teacherFace: '/images/head.png',
  },

  bindfullscreenchange: function () {
    if (this.data.videoFlag == 0) {
      this.setData({
        videoFlag: 1
      })
    } else {
      this.setData({
        videoFlag: 0,
        curVideo: ""
      })
    }
  },

  videoShow: function (e) {
    this.setData({
      curVideo: e.currentTarget.dataset.url
    })

    this.videoContext.requestFullScreen({	// 设置全屏时视频的方向,不指定则根据宽高比自动判断。
      direction: 90						// 屏幕逆时针90度
    });
  },

  showImg: function (e) {
    var list = [];
    this.data.entity.images.map(o => {
      list.push(o.url);
    });

    wx.previewImage({
      urls: list,
      current: e.currentTarget.dataset.url
    })
  },
  showDoneImg: function (e) {
    var list = [];
    this.data.entity.done.images.map(o => {
      list.push(o.url);
    });
    wx.previewImage({
      urls: list,
      current: e.currentTarget.dataset.url
    })
  },
  showMarkImg: function (e) {
    var list = [];
    this.data.entity.mark.images.map(o => {
      list.push(o.url);
    });
    wx.previewImage({
      urls: list,
      current: e.currentTarget.dataset.url
    })
  },

  showAudio: function (e) {
    const index = e.currentTarget.dataset.index
    if (this.data.curAudioIndex != index) {
      this.setData({
        curAudioIndex: index,
      })
      audioContext.src = this.data.audioList[index]
      audioContext.play()
      audioContext.onEnded((res) => {
        this.setData({
          curAudioIndex: '-1',
        })
      })
    } else {
      if (this.data.audioPause) {
        audioContext.play()
        this.setData({
          audioPause: false
        })
      } else {
        audioContext.pause()
        this.setData({
          audioPause: true
        })
      }
    }
  },

  bindended: function () {
    this.setData({
      audioPause: 0,
      curAudioIndex: -1,
      curAudio: ''
    })
  },

  bindpause: function () {
    this.setData({
      audioPause: 1
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = options.id;
    this.setData({ homeworkId: id });
    // this.audioContext = wx.createAudioContext('audio-play')
    this.videoContext = wx.createVideoContext('play-video');// 	创建 video 上下文 VideoContext 对象。
    const type = options.type
    if (type == 0) {
      this.setData({
        doTaskFlag: true
      })
    }

    this.loadHomework()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  loadHomework: function () {
    const urls = urlDef.urls;
    let stu = wx.getStorageSync('student');
    if (stu) {
      const body = { 'q.homeworkId': this.data.homeworkId, 'q.studentId': stu.studentId }
      // 接收作业(第一次查看有效)
      util.apiPost(urls.homework_receive, body).then((rs) => {
        console.log('接收作业')
      })
      util.apiPost(urls.my_homework, body).then((rs) => {
        let o = rs[0];

        // 解析内容
        let workContents;
        try {
          workContents = JSON.parse(o.homeworkContent);
        } catch (e) {
          workContents = {
            content: o.homeworkContent,
            images: [],
            records: [],
            videos: []
          };
          console.error(e);
        }
        o.homeworkContent = workContents.content;
        if (o.receiveDate) {
          o.receiveDate = o.receiveDate.substring(0, 16).replace('T', ' ')
        }
        o.images = workContents.images == null ? [] : workContents.images;
        o.images.forEach(rs => {
          rs.url = urls.oss_file + 'image/' + rs.url
        });

        o.records = workContents.records == null ? [] : workContents.records;
        o.records.forEach(rs => {
          rs.url = urls.oss_file + 'file/' + rs.url
        });

        o.videos = workContents.videos == null ? [] : workContents.videos;
        o.videos.forEach(v => {
          util.apiPost(urls.video_loadInfo + v.url).then((rs) => {
            v.imgUrl = rs.img
            v.playUrl = rs.url
            this.reloadVideo(v)
          });
        });


        // 完成情况
        let doneContents;
        try {
          doneContents = o.content ? JSON.parse(o.content) : {};
        } catch (e) {
          doneContents = {
            images: [],
            records: [],
            videos: [],
            content: ''
          };
          console.error(e);
        }
        o.done = doneContents;
        o.done.images = doneContents.images == null ? [] : doneContents.images;
        o.done.images.forEach(rs => {
          rs.url = urls.oss_file + 'image/' + rs.url
        });

        o.done.records = doneContents.records == null ? [] : doneContents.records;
        o.done.records.forEach(rs => {
          rs.url = urls.oss_file + 'file/' + rs.url
        });

        o.done.videos = doneContents.videos == null ? [] : doneContents.videos;
        o.done.videos.forEach(v => {
          util.apiPost(urls.video_loadInfo + v.url).then((rs) => {
            v.imgUrl = rs.img
            v.playUrl = rs.url
            this.reloadDoneVideo(v)
          });
        });
        // 批阅情况
        let markContents;
        try {
          markContents = o.markResult ? JSON.parse(o.markResult) : {};
        } catch (e) {
          markContents = {
            images: [],
            records: [],
            videos: [],
            content: ''
          };
          console.error(e);
        }
        o.mark = markContents;
        o.mark.score = o.markScore ? o.markScore : 0
        o.mark.images = markContents.images == null ? [] : markContents.images;
        o.mark.images.forEach(rs => {
          rs.url = urls.oss_file + 'image/' + rs.url
        });

        o.mark.records = markContents.records == null ? [] : markContents.records;
        o.mark.records.forEach(rs => {
          rs.url = urls.oss_file + 'file/' + rs.url
        });

        o.mark.videos = markContents.videos == null ? [] : markContents.videos;
        o.mark.videos.forEach(v => {
          util.apiPost(urls.video_loadInfo + v.url).then((rs) => {
            v.imgUrl = rs.img
            v.playUrl = rs.url
            this.reloadMarkVideo(v)
          });
        });

        this.setData({ entity: o })
        util.apiPost(urls.get_user_head + '&q.personId=' + rs[0].teacherId).then((fs) => {
          if (fs && fs.length > 0) {
            this.setData({ teacherFace: urls.oss_file + 'image/' + fs[0] })
          }
        });
      })
    }
  },
  reloadVideo: function (t) {
    let o = this.data.entity
    let vs = o.videos
    vs.map(v => {
      if (t.url == v.url) {
        v.imgUrl = t.imgUrl
        v.playUrl = t.playUrl
      }
    })
    this.setData({ entity: o })
  },
  reloadDoneVideo: function (t) {
    let o = this.data.entity
    let vs = o.done.videos
    vs.map(v => {
      if (t.url == v.url) {
        v.imgUrl = t.imgUrl
        v.playUrl = t.playUrl
      }
    })
    this.setData({ entity: o })
  },
  reloadMarkVideo: function (t) {
    let o = this.data.entity
    let vs = o.mark.videos
    vs.map(v => {
      if (t.url == v.url) {
        v.imgUrl = t.imgUrl
        v.playUrl = t.playUrl
      }
    })
    this.setData({ entity: o })
  },
  toTask: function(e) {
    wx.navigateTo({
      url:  '/pages/doTask/doTask?homeworkId='+ this.data.homeworkId
    })
  }
})