// pages/yuezhan/pay_page/index.js
const {
  request,
  serverName
} = require('../../../utils/services');
// const WxParse = require('../../../common/component/wxParse/wxParse.js');
const {
  Toast,
  removeArrItem
} = require('../../../utils/util.js');
const {
  defaultImg
} = require('../../../utils/images');
const WxParse = require('../../../common/component/wxParse/wxParse.js');
const app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    isAgree: true,
    logo_img: serverName +"/company_logo.jpg",
    half_star_img: "../../../imgs/icon/half.png",
    empty_star_img: "../../../imgs/icon/empty.png",
    full_star_img: "../../../imgs/icon/full.png",
    show_star: [{

    }],


    exhibitionDetail: {}
  },
  clickCell: function() {
    console.log(this.data.active);
    this.setData({
      active: !this.data.active
    })
  },
  fix_starImg: function(points) {
    let strPoints = String(Number(points).toFixed(2));
    let show_Arr = [];

    let ten = strPoints.split('.')[0] || 0;
    let unit = strPoints.split('.')[1] || 0;
    let surPlus = 0;
    if (strPoints < 0) {
      return
    }
    if (ten) {
      for (let i = 0; i < Number(ten); i++) {
        show_Arr.push({
          'img': this.data.full_star_img
        })
      }
      surPlus = 5 - Number(ten);
    }
    
    if (unit && surPlus>0) {
      let numUnit = Number(unit.substr(0, 1)) || 0
      if (numUnit > 0) {
        // let fix_unit = Math.round(numUnit);
        // switch (true) {
        //   case numUnit > 5:
        //     show_Arr.push({
        //       'img': this.data.half_star_img
        //     })
        //     break;
        //   case numUnit <= 5:
        //     show_Arr.push({
        //       'img': this.data.half_star_img
        //     })
        //     break;
        //   default:
        //     break
        // }
        show_Arr.push({
          'img': this.data.half_star_img
        })
      } else if (numUnit == 0) {
        show_Arr.push({
          'img': this.data.empty_star_img
        })
      } else {
        return
      }
    }
    if (surPlus>0){
      for (let i = 0; i < surPlus - 1; i++) {
        show_Arr.push({
          'img': this.data.empty_star_img
        })
      }
    }
    
    return show_Arr
  },
  readMore: function() {
    this.setData({
      readActive: !this.data.readActive
    })
  },

  addCommentLike: function(e) {
    let {
      type,
      id,
      idx
    } = e.currentTarget.dataset;
    console.log(idx, type, id)
    let {
      comments
    } = this.data;

    Toast.showToast2('loading');

    let loginSessionKey = wx.getStorageSync('token') || "";
    // if (loginSessionKey){
    request['commentLike']({
      loginSessionKey,
      commentId: id,
      type: Number(type),
    }, "post", res => {
      if (res.data.code > -1) {
        console.log("asdw", comments.content[idx].hasLike)
        comments.content[idx].hasLike = res.data.data.hasLike
        if (res.data.data.hasLike) {
          comments.content[idx].likeCount += 1;
        } else {
          comments.content[idx].likeCount -= 1;

        }
        this.setData({
          comments: comments
        })
      }

    }, err => {

    }, complete => {

      Toast.hideLoading();
    })
    // }


  },

  addLike: function() {
    // if (this.data.isLike) {
    //   this.setData({
    //     isLike: !this.data.isLike,
    //     likeNum: this.data.likeNum - 1
    //   })
    // } else {
    //   this.setData({
    //     isLike: !this.data.isLike,
    //     likeNum: this.data.likeNum + 1
    //   })
    // }

    let loginSessionKey = wx.getStorageSync('token') || "";
    let {
      exhibitionId,
      exhibitionDetail,
      type:isChange
    } = this.data;
    let {
      collectedArr,
      collectedChange
    } = app.globalData, hasItem = true;
    let type = exhibitionDetail.hasCollect
    // if (loginSessionKey){
    request['isCollect']({
      loginSessionKey,
      exhibitionId: exhibitionId,
      type: Number(type),
    }, "post", res => {
      if (res.data.code > -1) {
        for (let i = 0; i < collectedArr.length; i++) {
          if (collectedArr[i].collectedId && exhibitionId == collectedArr[i].collectedId) {
            console.log("true")
            collectedArr[i] = {
              collectedId: exhibitionId,
              status: res.data.data.hasCollect,
            }
            hasItem = false;
          }
        }
        if (hasItem) {
          collectedArr.push({
            collectedId: exhibitionId,
            status: res.data.data.hasCollect,
          })
        }

        app.globalData.collectedArr = collectedArr;
        console.log(isChange, res.data.data.hasCollect)
        if (isChange == res.data.data.hasCollect){
          app.globalData.collectedChange = false;
        }else{
          app.globalData.collectedChange = true;
          
        }
       

        exhibitionDetail.hasCollect = res.data.data.hasCollect
        if (exhibitionDetail.hasCollect) {
          exhibitionDetail.collectionsCount += 1;
        } else {
          exhibitionDetail.collectionsCount -= 1;
        }
        this.setData({
          exhibitionDetail: exhibitionDetail,
        })
      }

    }, err => {

    }, complete => {
      Toast.hideLoading();
    })
    // }
  },

  tapToCommentDetail: function() {
    let {
      exhibitionId
    } = this.data;
    console.log('detail')
    wx.navigateTo({
      // url: `../../zl_detail/create_evaluation/index?id=${exhibitionId}`,

      url: `../comment_detail/index?id=${exhibitionId}`,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  navigateToLocation: function() {
    let {
      latitude,
      longitude
    } = this.data;
    wx.openLocation({
      exhibitionId: 0,
      latitude: latitude,
      longitude: longitude,
      scale: 28,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {}
    });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    this.setData({
      defaultImg,
      exhibitionId: options.id,
      serverName
    })
    // this.getExhibitionDetail();

    let {
      cookieIDs = []
    } = app.globalData;
    let id = options.id;
    let hasItem = true;

    for (let i = 0; i < cookieIDs.length; i++) {
      if (cookieIDs[i] && id == cookieIDs[i]) {
        cookieIDs = removeArrItem(cookieIDs, cookieIDs[i])

      }
    }

    if (hasItem && id != undefined && (typeof(Number(id)) == 'number')) {
      cookieIDs.unshift(id)
    }
    console.log(id)

    app.globalData.cookieIDs = cookieIDs


    console.log(app.globalData.cookieIDs)
  },

  getExhibitionDetail: function() {
    let exhibitionId = this.data.exhibitionId;
    request["getExhibitionDetail"]({
      exhibitionId: exhibitionId
    }, "", res => {
      let {
        data: exhibitionDetail
      } = res.data;
      let {
        description,
        openTime,
        comments,
        imageUrl
      } = exhibitionDetail;
      app.globalData.currentShareImg = imageUrl

      let _show_star = this.fix_starImg(exhibitionDetail.score || '0.0')
      if (comments){
        let commentsCon = comments.content;
        for (let i = 0; i < commentsCon.length; i++) {
          let comments_star = this.fix_starImg(commentsCon[i].score || '0.0')
          commentsCon[i]['imgObj'] = comments_star
        }
      }
      // console.log('asdasd', commentsCon)
      this.setData({
        exhibitionDetail,
        likeNum: exhibitionDetail.collectionsCount,
        type: exhibitionDetail.hasCollect,
        comments,
        show_star: _show_star
      });
      WxParse.wxParse('description', 'html', description, this, 5);
      WxParse.wxParse('openTime', 'html', openTime, this, 5);

      console.log(exhibitionDetail)
    })
  },

  bindAgreeChange: function(e) {
    this.setData({
      isAgree: !!e.detail.value.length
    });
  },
  tapToComement: function() {
    let {
      exhibitionId
    } = this.data;
    wx.navigateTo({
      url: `../../zl_detail/create_evaluation/index?id=${exhibitionId}`,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  tapToDetail: function() {
    wx.navigateTo({
      url: './rule_detail/index',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  doWeChatPay: function() {
    let loginSessionKey = wx.getStorageSync("token");
    let {
      exhibitionId,
      isAgree,
      exhibitionDetail
    } = this.data;
    let {
      hasPay
    } = exhibitionDetail;
    let {
      productPrice,
      showLink
    } = this.data.exhibitionDetail.product;
    console.log(productPrice)
    console.log(isAgree)
    if (hasPay) {
      app.globalData.currentUrl = showLink
      // console.log('dwdwdw', app.globalData.currentUrl)
      wx.navigateTo({
        url: `../../wv_page/index`,
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    } else {
      if (isAgree) {
        if (productPrice) {
          request['orderPay']({
            amount: productPrice,
            loginSessionKey,
            exhibitionId
          }, "post", res => {
            const {
              data: wechatPayModel
            } = res.data;
            const {
              timeStamp,
              nonceStr,
              signType,
              paySign,
              package: packageStr
            } = wechatPayModel;
            console.log(timeStamp,
              nonceStr,
              signType,
              paySign)
            // prettier-ignore
            wx.requestPayment({
              timeStamp,
              nonceStr,
              signType,
              paySign,
              'package': packageStr,
              success: res => {
                console.log(res);
                app.globalData.currentUrl = showLink
                // console.log('dwdwdw', app.globalData.currentUrl)
                wx.navigateTo({
                  url: `../../wv_page/index`,
                  success: function (res) { },
                  fail: function (res) { },
                  complete: function (res) { },
                })
              },
              fail: err => {
                console.log(err);
                Toast.showToast2('warn', '支付取消');
              }
            });
          })
        } else {
          app.globalData.currentUrl = showLink

          wx.navigateTo({

            url: `../../wv_page/index`,
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
          })
          // Toast.showToast('tip', "暂时无法支付", () => {
          //   return;
          // })
        }


      } else {
        Toast.showToast('tip', "购买/查看需要同意相关条款", () => {
          return;
        })
      }
    }





  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getExhibitionDetail();
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})