var WxParse = require('../../wxParse/wxParse.js');
const app = getApp();
var that;
var Interval;
var wechat;
var id;
var intt;
const baseUrl = getApp();
const api = require('../../config/api.js');
const util = require('../../config/util.js');
var startX, endX;
var moveFlag = true; // 判断执行滑动事件
Page({
  startX: 0,
  startY: 0,
  isClear: false,
  startPageX: 0,
  /**
   * 页面的初始数据 --解释笔记
   */
  data: {

    title: '我的试题解释',
    time: 2 * 60 * 60 * 1000, //初始时间
    paystatus: 1, //1未开始时间开始状态，2开始
    collection: 1, //1不收藏，2已收藏
    singdouble: 1, //1单选，2多选
    paiduanactive: 1, //1不是判断，2是判断题
    activeopen: true,
    baseurl:baseUrl.globalData.baseimgurl,
    paystatus: 1, //1未开始时间开始状态，2开始
    collection: 1, //1不收藏，2已收藏
    singdouble: 1, //1单选，2多选
    paiduanactive:1,//1不是判断，2是判断题
    zstime:1, //1正计，0倒计
    typeid:1, //0练习1正式
    activeopen:true,
    coursetypefour_id:1,
    itemdatacurrent:[], //当前数据
    itemdataall:[], //全部数据
    itemdata: [],  //选项数据
    content:"",//富文本数据
    replylist:[],
    showModalStatus: false,
    pen: 3,
    color: '#FFFFFF',
    currentTab: 0,
    now: 1, //当前页码
    all: 15, //总页码
    height: 0,
    Timer_state: 1,
    Answer_card: false,
    Draft_paper: false,
    false_analysis: false,
    stem_height: 150,
    jiexi: false,
    field: {
      analysis_text: "",
    },
    img: [],
    scroll: "scroll",
    index: 0,
    drag_line: false,
    coursetypefour_id:1,
    grouppaper_id:1,
    typeid:1,
    courseid:1,//试题ID
    explainlist:[], //试题类型名称
    duicuo:1 //试题作答对与错1全部，2错的题
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: this.data.title
    })
    baseUrl.islogin();
    console.log(options);
    this.setData({
          coursetypefour_id:options.coursetypefour_id,
          grouppaper_id:options.grouppaper_id,
          typeid:options.id,
          duicuo:options.id
    });
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getcoursetypefourexam(this.data.coursetypefour_id,this.data.grouppaper_id,this.data.duicuo);
    this.wrodtypelist();
    // this.getexamexplantypelist(this.data.courseid); //试题类型列表
  },

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

  },

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

  },

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

  },

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

  },

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

  },
  //-----------------------------
  //	手机触摸开始
  //-----------------------------
  touchStart: function (e) {
    //得到触摸点的坐标
    this.startX = e.changedTouches[0].x
    this.startY = e.changedTouches[0].y
    this.context = wx.createContext()
    this.context.setStrokeStyle(this.data.color)
    this.context.setLineWidth(this.data.pen)
    this.context.setLineCap('round') // 让线条圆润
    this.context.beginPath()

  },
  //-----------------------------
  //	触摸后移动
  //-----------------------------
  touchMove: function (e) {

    var startX1 = e.changedTouches[0].x
    var startY1 = e.changedTouches[0].y
    this.context.moveTo(this.startX, this.startY)
    this.context.lineTo(startX1, startY1)
    this.context.stroke()
    this.startX = startX1;
    this.startY = startY1;
    wx.drawCanvas({
      canvasId: 'myCanvas',
      reserve: true,
      actions: this.context.getActions()
    })
  },
  penSelect: function (e) {
    this.setData({
      pen: parseInt(e.currentTarget.dataset.param)
    });
    this.isClear = false;
  },
  colorSelect: function (e) {
    this.setData({
      color: e.currentTarget.dataset.param
    });
    this.isClear = false;
  },
  cleardraw: function (e) {
    this.setData({
      showModalStatus: false
    });
    this.setData({
      showModalStatus: true
    });
  },
  caogaoclick: function () {

    this.setData({
      showModalStatus: true,
    })
  },
  //-----------------------------
  //	草稿纸
  //-----------------------------
  shows: function () {
    const that = this;
    console.log(that.data.Draft_paper);
    that.data.Draft_paper = !that.data.Draft_paper;
    if (that.data.Draft_paper == false) {
      that.setData({
        Draft_paper: true,
      })
      this.util('open');
    } else {
      that.setData({
        Draft_paper: false,
        showModalStatus: false
      })
    }
  },
  util: function (currentStatu) {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0,
    });
    this.animation = animation;
    animation.opacity(0).rotateX(-100).step();
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.opacity(1).rotateX(0).step();
      this.setData({
        animationData: animation
      })
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)
    // 显示  
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },
  touchStart1: function (e) {
    startX = e.touches[0].pageX; // 获取触摸时的原点
    moveFlag = true;
  },
  // 触摸移动事件
  touchMove1: function (e) {
    endX = e.touches[0].pageX; // 获取触摸时的原点
    if (moveFlag) {
      if (endX - startX > 50) {
        console.log("move right");
        this.move2right();
        moveFlag = false;
      }
      if (startX - endX > 50) {
        console.log("move left");
        this.move2left();
        moveFlag = false;
      }
    }

  },
  // 触摸结束事件
  touchEnd1: function (e) {
    moveFlag = true; // 回复滑动事件    
  },
  move2left() {
    const that = this;
    const index = that.data.index + 1;
    const all = that.data.all;   
    if (index < all) {
      
     console.log(that.data.itemdataall[index].id);
      this.setData({
        index: index,
        now: index + 1,
        itemdata: that.data.itemdataall[index].examitem,
        itemdatacurrent:that.data.itemdataall[index],
        content:that.data.itemdataall[index].name.replace(/\<img/gi, '<img style="width:80%;height:auto"'),
        singdouble:that.data.itemdataall[index].examtype,
        paiduanactive:that.data.itemdataall[index].examtype,
        zstime:that.data.itemdataall[index].reverset,
        typeid:that.data.itemdataall[index].typeid,
        courseid:that.data.itemdataall[index].id
      });

      this.wrodtypelist(that.data.itemdataall[index].id);
      this.getexamexplantypelist(that.data.itemdataall[index].id); //试题类型列表
    }else{
      let examtype=this.data.singdouble;
      let id=this.data.coursetypefour_id;
      let typeid=this.data.typeid;
      let grouppaper_id=this.data.itemdatacurrent.grouppaper_id;
      if(typeid==1){
        wx.navigateTo({
          url: '/pages/exampaper/exampaper?id='+id+'&grouppaper_id='+grouppaper_id,
        })
      }else{
        wx.navigateTo({
          url: '/pages/exampaper2/exampaper2?id='+id+'&grouppaper_id='+grouppaper_id,
        })
      }
    }
   
  },
  move2right() {
    var that = this;
    var index	=	that.data.index-1;
    const all = that.data.all;
    console.log(that.data.itemdata2);
    if(index>=0){

     console.log(that.data.itemdataall[index].id);
      that.setData({
      	index:index,
        now:index+1,    
        itemdata: that.data.itemdataall[index].examitem,
        itemdatacurrent:that.data.itemdataall[index],
        content:that.data.itemdataall[index].name.replace(/\<img/gi, '<img style="width:80%;height:auto"'),
        singdouble:that.data.itemdataall[index].examtype,
        paiduanactive:that.data.itemdataall[index].examtype,
        zstime:that.data.itemdataall[index].reverset,
        typeid:that.data.itemdataall[index].typeid,
        courseid:that.data.itemdataall[index].id
      });
      this.wrodtypelist(that.data.itemdataall[index].id); 
      this.getexamexplantypelist(that.data.itemdataall[index].id); //试题类型列表
    }  
  },
  getcoursetypefourexam:function(params,grouppaper_id,duicuo) {
        
    //得到练习题目
    const that = this;
      let url = baseUrl.globalData.baseUrl + '/exam/examexplaininfo';
      let user_id=wx.getStorageSync('wxuserid')==''?3:wx.getStorageSync('wxuserid');
      var param = {
        coursetypefour_id: params,
        user_id:user_id,
        grouppaper_id:grouppaper_id,
        duicuo:duicuo
      };
      //此处为使用封装的post请求
      util.post(url, param).then((res) => {
        console.log(res.data);
        that.setData({
          itemdataall: res.data.item,
          itemdata:res.data.item[0].examitem,
          all:res.data.item.length,
          itemdatacurrent:res.data.item[0],
          content:res.data.item[0].name.replace(/\<img/gi, '<img style="width:80%;height:auto"'),
          singdouble:res.data.item[0].examtype,
          paiduanactive:res.data.item[0].examtype,
          zstime:res.data.reverset,
          typeid:res.data.typeid,
          courseid:res.data.item[0].id
        });

      }).catch((errMsg) => {
        console.log(errMsg);
      });      
  },   //解释开始    
  collectionclickdata:function(collection_id,user_id) {
    const that = this;
    let url = baseUrl.globalData.baseUrl + '/course/coursecollection';
    var param = {
      id: collection_id,
      user_id:user_id
    };
    //此处为使用封装的post请求
    util.get(url, param).then((res) => {
       console.log(res);     
       this.getcoursedata(that.data.courseid);

    }).catch((errMsg) => {
      console.log(errMsg);
    });
  },
  displayview:function() {
    console.log(this.data.showview);
    this.setData({
      showview:(!this.data.showview)
    })  
  },
  wrodtypelist:function(params){

    //获取课程留言
    const that = this;
    let url = baseUrl.globalData.baseUrl + '/exam/wordsexamuser';
    var param = {
      user_id: wx.getStorageSync('wxuserid')==null?3:wx.getStorageSync('wxuserid')
    };
    //此处为使用封装的post请求
    util.get(url, param).then((res) => {
       console.log(res);
      that.setData({
        replylist: res.data
      });

    }).catch((errMsg) => {
      console.log(errMsg);
    });
  },
  wordsclick:function(ee){
  
    let e1=ee.currentTarget.id;
    let e2=baseUrl.globalData.currentuserinfo.id;
    const that = this;
    let url = baseUrl.globalData.baseUrl + '/wordslist/wordscourseclickcount';
    var param = {
      words_id: e1,
      user_id: e2,
    };
    //此处为使用封装的post请求
    util.get(url, param).then((res) => {
       console.log(res);   

    }).catch((errMsg) => {
      console.log(errMsg);
    });
  },
  uploadpic:function(){
    var that = this;
    let imagesList = [];
    let maxSize = 1024 * 1024;
    let maxLength = 6;
    let flag = true;
    wx.chooseImage({
      count: 9, //最多可以选择的图片总数
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 500
        })
        for (let i = 0; i < res.tempFiles.length; i++) {
          if (res.tempFiles[i].size > maxSize) {
            flag = false;
            console.log(111)
            wx.showModal({
              content: '图片太大，不允许上传',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            });
          }
        }
        if (res.tempFiles.length > maxLength) {
          console.log('222');
          wx.showModal({
            content: '最多能上传' + maxLength + '张图片',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('确定');
              }
            }
          })
        }
        if (flag == true && res.tempFiles.length <= maxLength) {
          that.setData({
            imagesListp: res.tempFilePaths
          })
          that.data.imagestr=[];
          var arr='';
          for (let i = 0; i < that.data.imagesListp.length; i++) {       
            wx.uploadFile({ 
              url: baseUrl.globalData.baseUrl + '/wordslist/uploadpics', 
              filePath: that.data.imagesListp[i], 
              name: 'file', 
              success:function(res){ 
                //打印
                console.log("------------响应数据：");
                console.log(res.data);
              
                var message = JSON.parse(res.data);
                that.data.imagestr.push(message);
                that.setData({
                   imagestr:that.data.imagestr
                });
              },
            })
        
          }
        

        }
        console.log(res);
      },
      fail: function (res) {
        console.log(res);
      }
    })
 
  },    
  formSubmit:function(e) {

    if(wx.getStorageSync('wxuserid')==''){
       wx.navigateTo({
         url: '/pages/userlogin/userlogin',
       })
    }
  
    let content = this.data.wordstextname;
    console.log(content)
    if (content == '') {
      wx.showToast({
        title: '留言内容为空,请填写内容',
        icon: 'none',
        duration: 1500
      })
      return false;     
    }
    // console.log(this.data.imagestr);
    this.wordsadd(content,this.data.imagestr);
   
  },
  bindTextAreaBlur: function(e) {
    this.setData({
     wordstextname:e.detail.value
    })  
 }, 
 uploadpicsimage:function(e){

  const that = this;
  let url = baseUrl.globalData.baseUrl + '/wordslist/uploadpics';
  var param = {
    url: e
  };
  //此处为使用封装的post请求
  util.post(url, param).then((res) => {
     console.log(res);   

  }).catch((errMsg) => {
    console.log(errMsg);
  });
 },
 wordsadd:function(content,imagestr){

        const that = this;
        let url = baseUrl.globalData.baseUrl + '/exam/examexplainadd';
        var param = {
          content: content,
          imagestr:imagestr,
          userid:wx.getStorageSync('wxuserid')==''?3:wx.getStorageSync('wxuserid'),
          exam_id:that.data.courseid
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
          console.log(res.data);   
          if(res.data>0){
            wx.showToast({
              title: '留言内容成功',
              icon: 'none',
              duration: 1500
            })
            
            that.wrodtypelist(that.data.courseid); //试题留言
            that.getexamexplantypelist(that.data.courseid); //试题类型列表
            that.setData({
              wordstextname:''
            })
            
          }

        }).catch((errMsg) => {
          console.log(errMsg);
        });
 },contentclick:function(params) {

     console.log(params);
       let id=params.currentTarget.id;
       let xid=params.currentTarget.dataset.xid;
       console.log(id);
       this.setData({
        wordstextname:'回复@'+id,
        showview:true
       });

      this.addinccomment(xid);

       wx.showToast({
        title: '@成功，留言请移底部留言',
        icon: 'none',
        duration: 1500
      })


 },rdclick:function(params) {
    wx.navigateTo({
      url: '/pages/communityinfo/communityinfo?id='+params.currentTarget.id,
    })
 },addinccomment:function(params) {
     //增加评论数
      console.log(params);
      let userid=wx.getStorageSync('wxuserid');
      const that = this;
      let url = baseUrl.globalData.baseUrl + '/exam/addcommentcount';
      var param = {
        id:params
      };
      //此处为使用封装的post请求
      util.get(url, param).then((res) => {
        console.log(res);   
          // this.wrodtypelist(this.data.courseid)
          this.wrodtypelist(that.data.courseid);
          this.getexamexplantypelist(that.data.courseid);
      }).catch((errMsg) => {
        console.log(errMsg);
      });
 },
 clickbtn:function(params) {
        console.log(params);
        let userid=wx.getStorageSync('wxuserid');
        const that = this;
        let url = baseUrl.globalData.baseUrl + '/exam/wordscourseclickcount';
        var param = {
          words_id:params.currentTarget.id,
          user_id: userid
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {
          console.log(res);   
            // this.wrodtypelist(this.data.courseid)
            this.wrodtypelist(this.data.courseid);
            this.getexamexplantypelist(this.data.courseid);
        }).catch((errMsg) => {
          console.log(errMsg);
        });
 },
 preview:function (params) {
  let that=this;
       console.log(params)
       let currentUrl = params.currentTarget.dataset.src;
       let arrindex=params.currentTarget.dataset.id;
      
       let rearr=that.data.replylist[arrindex].pics;
       console.log(rearr);
       let arr=[];
       rearr.forEach(function (item,index) {       
             arr[index]=that.data.baseurl+item
       });
       console.log(arr);
       wx.previewImage({
         current: currentUrl, // 当前显示图片的http链接
         urls: arr // 需要预览的图片http链接列表
       })
     },
     getexamexplantypelist:function(params) {
      
          console.log(params);
          let userid=wx.getStorageSync('wxuserid');
          const that = this;
          let url = baseUrl.globalData.baseUrl + '/exam/examexplaintypelist';
          var param = {
            exam_id:params
          };
          //此处为使用封装的post请求
          util.get(url, param).then((res) => {
            console.log(res);   
            this.setData({

              explainlist:res.data

            })
              // this.wrodtypelist(this.data.courseid)
              // this.wrodtypelist(this.data.courseid);
          }).catch((errMsg) => {
            console.log(errMsg);
          });

     }


})