const util = require('../../../utils/util.js');
const app = getApp();
Page({
  data: {
    datas:{},
    imgUrl:[],
    uploadImg:[],
    star:5,
    cusStar:5,
    aid:'',
    title:'',
    orderid:'',
    type:'',
    act:'',
    content:'',//评价
    cid:'',
    one: [{ txt: '带队技能欠佳', cet: false }, { txt: '与宣传有差距', cet: false }, { txt: '活动不合理', cet: false }, { txt: '孩子体验一般', cet: false }, { txt: '吃住有待升级', cet: false }, { txt: '性价比一般', cet: false }],
    two: [{ txt: '正能量的小黄人', cet: false }, { txt: '领队专业细心', cet: false }, { txt: '教育意义明显', cet: false }, { txt: '活动安排有序', cet: false }, { txt: '安全措施到位', cet: false }, { txt: '性价比超值', cet: false }],
    chooseIndex:[],
    option:[],
    recommendArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],//推荐值数组
    recomLevel: 0,//推荐值
  },
  onLoad(options) {
    let orderid = options.orderid, type = options.otype, act = options.act || '';

    this.setData({ orderid, type, act});
    this.getData(orderid,type,act);
  },
  getData(orderid,type,act){
    let that = this;
    util.ajax({
      func:"v2/order/detail",
      data:{"orderid":orderid,"type":(type != undefined ? type : "")}
    },function(res){
      if(res.code == 0){
        let datas = res.data, star = 5, uploadImg = [], content = '', option = [], options = that.data.two, cid = '', recomLevel=0;
        if (!util.isObjEmpty(datas.comment)){
          // star = datas.comment.arating;
          cid = datas.comment.cid;
          // recomLevel = datas.comment.recomLevel;
          // uploadImg = datas.comment.images||[];
          // content = datas.comment.content.replace(/#([^#]+)#/g,"").replace(/<br\/>/g,'\n');
          // option = datas.comment.content.match(/#([^#]+)#/g);
          // star>=3?options = that.data.two : options = that.data.one;
        //   for(let i in option){
        //     option[i] = option[i].replace(/#/g, "");
        //     for(let k in options){
        //       if(option[i] == options[k].txt){
        //         options[k].cet = true
        //       }
        //     }
        //   }
          that.updateCommentData(datas.comment)
        }
        if (that.data.act !='edit') {
          that.getlocalData();
        }
        // if(star>=3){
        //   that.setData({two:options})
        // }else{
        //   that.setData({one:options})
        // }
        // that.setData({ star, uploadImg, aid: datas.aid, cid, content, datas, title: datas.title, recomLevel})
        that.setData({aid: datas.aid, cid,  datas, title: datas.title,})
      }else
        util.showTips(res.reason);
    })
  },
  chooseImg(){
    let that = this, uploadImg = that.data.uploadImg, count = 8;
    wx.chooseImage({
      count:count, 
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'], 
      success: function (res) {
        var imgUrl = res.tempFilePaths;
        if (count - (imgUrl.length + uploadImg.length) < 0) {
          util.showTips("最多只能上传" + count + "张图片");
          return false;
        }
        wx.showLoading({ title: '上传中…' });
        let img = [];
        that.data.upImg = [];
        for(let i in imgUrl){
          wx.uploadFile({
            url: util.config.apiServer + 'user/upload_img_app.do',
            filePath: imgUrl[i],
            name: 'avatarFile',
            formData:{
              "rid":app.globalData.userInfo['rid']
            },
            success: function(reason){
              let datas = JSON.parse(reason.data);
              if(reason.statusCode==200&&datas.code==0){
                img.push(datas.data.image);
                that.setData({ uploadCount: imgUrl.length, uploadImg, upImg: img});
                if (that.data.upImg.length == that.data.uploadCount) {
                  that.data.uploadImg = [...that.data.upImg, ...that.data.uploadImg];
                  that.setData({ uploadImg: that.data.uploadImg });
                  wx.hideLoading();
                }
              }
            }
          })
        }
      }
    })
  },
  delImg(e){
    let index = e.currentTarget.dataset.index,uploadImg = this.data.uploadImg;
    uploadImg.splice(index,1);
    this.setData({uploadImg})
  },
  submit(){
    let that=this,
      data = {},
      uploadImg=this.data.uploadImg,
      act = this.data.act,
      userInfo = app.globalData.userInfo,
      star = this.data.star,
      content=this.data.content.replace(/\n/g,'<br/>'),
      option = this.data.two;
    if(star == 1 || star == 2){
      option = this.data.one;
    }
    for(let i in option){
      if(option[i].cet){
        content = content +'#'+option[i].txt+'#'
      }
    }
    let pages = getCurrentPages(), prevPage = pages[pages.length - 2];
    if (prevPage.route == "pages/order/detail/index"){
      prevPage.data.query.otype = 0;
    }
    data['aid'] = this.data.aid;
    data['orderid'] = this.data.orderid;
    data['arating'] = star;//活动评分
    data['crating'] = this.data.cusStar;//活动评分
    data['leaderrating'] = '5';//领队评分
    data['content'] = content;
    data['cid'] = this.data.cid;
    data['image'] = uploadImg?uploadImg.join(','):'';
    data['rid'] = userInfo ? userInfo['rid']:"";
    data['recomLevel'] =  this.data.recomLevel;
    if (data.recomLevel<=0&&this.data.datas.atype == 0) {
      util.showTips("请对于本次活动体验后进行打分。");
      return false;
    }
    if(util.isEmpty(data.content)){
        util.showTips(this.data.datas.atype == 0?"请填写本次活动体验后的评价。":'请填写对此商品的评价。');
        return false;
    }
    util.ajax({
      func: (act == 'edit' ? "v2/comments/order/update" :"v2/comments/order/addcomment"),
      data:data,
      method: "POST", 
      load:true,
      title:'提交中'
    },function(res){
      if(res.code == 0){
        if (act == 'edit' || that.data.datas.atype == 1){
          wx.navigateBack();
        }else{
          wx.redirectTo({
            url: '/pages/order/scratch/scratch?orderid='+that.data.orderid+'&coin='+res.data||0
          }) 
        }
      }else{
        util.showTips(res.reason);
      }
    });
  },
  // 获取的评论数据整理公共方法
  updateCommentData(commentData){
    let star = 5,cusStar=5, uploadImg = [], content = '', option = [], options = this.data.two,recomLevel=0;
    star = commentData.arating;
    cusStar = commentData.crating;
    recomLevel = commentData.recomLevel;
    uploadImg = commentData.images||[];
    content = commentData.content.replace(/#([^#]+)#/g,"").replace(/<br\/>/g,'\n');
    option = commentData.content.match(/#([^#]+)#/g);
    star>=3?options = this.data.two : options = this.data.one;
    for(let i in option){
      option[i] = option[i].replace(/#/g, "");
      for(let k in options){
        if(option[i] == options[k].txt){
          options[k].cet = true
        }
      }
    }
    if(star>=3){
      this.setData({two:options})
    }else{
      this.setData({one:options})
    }
    this.setData({star,cusStar,uploadImg,content,recomLevel})
  },
  // 获取本地草稿数据
  getlocalData(){
    if (!util.isObjEmpty(wx.getStorageSync("orderComment"))) {
      let localData=wx.getStorageSync("orderComment");
      if (localData.orderid==this.data.orderid) {
        this.updateCommentData(localData)
      }
    }
  },
  // 保存草稿至本地
  saveDataToLocal(){
    let that=this,commentData={},option = this.data.two;
    if (!util.isEmpty(this.data.content)||this.data.uploadImg.length>0) {
      commentData.orderid=this.data.orderid;
      commentData.saveDate=util.getNowFormatDate('yyyy-MM-dd hh:mm:ss');
      commentData.arating=this.data.star;
      commentData.crating=this.data.cusStar;
      commentData.recomLevel=this.data.recomLevel;
      commentData.images=this.data.uploadImg || '';
      let content=this.data.content.replace(/\n/g,'<br/>');
      if(this.data.star == 1 || this.data.star == 2){
        option = this.data.one;
      }
      for(let i in option){
        if(option[i].cet){
          content = content +'#'+option[i].txt+'#'
        }
      }
      commentData.content=content;
      wx.setStorageSync("orderComment", commentData);
    }
  },
  chooseOpt:function(e){
    var star = this.data.star,chooseIndex = this.data.chooseIndex,index=e.currentTarget.dataset.index,option = this.data.two;
    if(star == 1 || star == 2){
      option = this.data.one;
    }
    if(option[index].cet){
      option[index].cet = false;
    }else{
      option[index].cet = true;
    }
    if(star == 1 || star == 2){
      this.setData({one:option});
    }else{
      this.setData({two:option});
    }
  },
  bindblur:function(e){
    this.setData({content:e.detail.value});
  },
  bindstar:function(e){
    if (e.currentTarget.dataset.type=='star') {
      this.setData({star:e.target.dataset.index});
    }else{
      this.setData({cusStar:e.target.dataset.index});
    }
  },
  recommend(e) {
    this.setData({ recomLevel: e.target.dataset.number })
  },
  onUnload: function() {
    if (this.data.datas.atype=='0') {
      this.saveDataToLocal()
    }
  },
  onHide(){
    if (this.data.datas.atype=='0') {
      this.saveDataToLocal()
    }
  }
})