const util = require('../../../utils/util.js');
const app = getApp();
Page({
  data: {
    nav: [{
      id: 0,
      title: '宝贝详情'
    }, {
      id: 1,
      title: '商品参数'
    }],
    current: 0,
    chatShow: false,
    skuShow: false,
    nodes: '',
    datas: {},
    comments: {},
    bottom: false,
    imgPath: util.config.imgPath,
    aid: '',
    title: '',
    score: 0,
    viode: [], //视频
    showBack: false, //是否显示返回顶部
    currentPages: 0,
    isColumn: false, //导航条是否到顶部
    onshow: true,
    skuHeight: '50%',
  },
  onLoad(options) {
    this.setData({
      aid: options.aid,
      currentPages: getCurrentPages().length,
      onshow: true
    });

    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
  },
  onShow() {
    let that = this;
    if (that.data.onshow) {
      if (!util.isObjEmpty(app.globalData.city)) {
        that.getData();
      } else {
        // var getLocation = util.promise(true);
        // getLocation.then(function (value) {
          that.getData();
        // }, function (error) {});
      }
    }
  },
  onUnload() {
    this.setData({
      skuShow: false
    });
  },
  onHide() {
    this.setData({
      skuShow: false
    });
  },
  onPageScroll(e) {
    var query = wx.createSelectorQuery();
    var isColumn = this.data.isColumn,
      that = this,
      showBack = this.data.showBack;
    query.select('#content').boundingClientRect();
    query.select('#notes').boundingClientRect();
    query.exec(function (res) {
      if (res && !that.data.isScroll) {
        if (res[1].top <= 0) {
          that.setData({
            current: 1
          });
        } else if (res[0].top <= 37) {
          that.setData({
            current: 0
          });
        }
        that.setData({
          isColumn: res[0].top <= 0 ? true : false
        });
      }
    });
    if (e.scrollTop > 500 && !showBack) {
      this.setData({
        showBack: true
      })
    } else if (e.scrollTop <= 500 && showBack) {
      this.setData({
        showBack: false
      })
    }
  },
  chooseNav(e) {
    let current = e.currentTarget.dataset.id,
      that = this,
      datas = this.data.datas;
    that.setData({
      current,
      isScroll: true
    });
    var arr = ['content', 'notes'];
    wx.pageScrollTo({
      selector: "#" + arr[current],
      success: () => {
        that.setData({
          isColumn: true
        });
        setTimeout(() => {
          that.setData({
            isScroll: false
          });
        }, 1000);
      }
    });
    if (current == 1) {
      wx.reportAnalytics('equip_parameter', {
        equip_aid: datas.aid,
        equip_title: datas.title,
      });
    } else if (current == 2) {
      wx.reportAnalytics('equip_comment', {
        equip_aid: datas.aid,
        equip_title: datas.title,
      });
    }
  },
  getData() {
    let that = this;
    util.ajax({
      func: "v2/article/detail",
      data: {
        "aid": that.data.aid
      }
    }, function (res) {
      if (res.code == 0) {
        let datas = res.data;
        // datas.content = datas.content.replace(/section/g, "div");
        // datas.content = datas.content.replace(/<img/g, "<img style='max-width:100%'");
        // let str = datas.content.match(/<source src="(\S*)"/g);
        // if (str) { 
        //   let viode = [];
        //   for (let i in str) {
        //     if (i < 3) {//只显示三个视频
        //       let src = str[i].match(/<source src="(\S*)"/)[1];
        //       viode.push(src.toString())
        //     }
        //   }
        //   that.setData({ viode });
        // }
        if (datas.tags && datas.tags.length > 0) {
          let goodsGuarantee = [],
            keyTag = [];
          datas.tags.forEach(item => {
            if (item.tagKey == 'goodsGuarantee') {
              goodsGuarantee.push(item)
            }
            if (item.tagKey == 'keywords') {
              keyTag.push(item)
            }
          });
          res.data.goodsGuarantee = goodsGuarantee; //活动标签/电商卖点
          res.data.keyTag = keyTag; //电商保障
          // 分成两行
          if (res.data.keyTag && res.data.keyTag.length >= 5) {
            datas.keyTag1 = []
            datas.keyTag2 = []
            // 标签总字数
            let allNum = 0
            datas.keyTag.forEach(item => {
              allNum = allNum + item.tagValue.length
            })
            const middleIndex = Math.ceil(allNum / 2);
            // 已存入数组字数
            let nowNum = 0
            datas.keyTag.forEach(item => {
              if (nowNum >= middleIndex) {
                datas.keyTag2.push(item)
              } else {
                nowNum = nowNum + item.tagValue.length
                datas.keyTag1.push(item)
              }
            })
          } else {
            datas.keyTag1 = res.data.keyTag;
          }
        }
        that.setData({
          datas
        });
        that.getFeedbook();
        that.getContent();
        wx.reportAnalytics('enter_equipdetails', {
          equip_aid: that.data.aid,
          equip_title: datas.title,
        });
      } else {
        util.showTips(res.reason);
      }
    })
  },
  // 返回首页
  gohome() {
    wx.reLaunch({
      url: '/pages/home/index',
    })
  },
  // 获取富文本信息
  getContent() {
    let that = this;
    util.ajax({
      func: "v2/article/content",
      data: {
        "aid": that.data.aid
      },
      load: false
    }, function (res) {
      if (res.code == 0) {
        let datas = res.data;
        if (!util.isEmpty(datas.content)) {
          that.data.datas.content = datas.content.replace(/section/g, "div");
          that.data.datas.content = that.data.datas.content.replace(/<img/g, "<img style='max-width:100%;height:auto'");
          let str = datas.content.match(/<source src="(\S*)"/g);
          if (str) {
            let viode = [];
            for (let i in str) {
              if (i < 3) { //只显示三个视频
                let src = str[i].match(/<source src="(\S*)"/)[1];
                viode.push(src.toString())
              }
            }
            that.setData({
              viode
            });
          }
        }

        that.data.datas.notes = datas.notes ? datas.notes.replace(/section/g, "div") : '';

        that.data.datas.notes = that.data.datas.notes.replace(/<img/g, "<img style='max-width:100%'");
        that.data.datas.safeTrip = datas.safeTrip ? datas.safeTrip.replace(/section/g, "div") : '';
        that.data.datas.safeTrip = that.data.datas.safeTrip.replace(/<img/g, "<img style='max-width:100%'");
        that.setData({
          datas: that.data.datas
        });
      }
    })
  },
  getFeedbook() { //获取评论
    let that = this;
    util.ajax({
      func: "comments/list",
      data: {
        "aid": this.data.aid,
        "pageIndex": 1,
        "pageSize": 1,
        "sort": 1,
        "keyword": ''
      }
    }, function (res) {
      if (res.code == 0) {
        for (let i in res.data.comments) {
          res.data.comments[i].contented = res.data.comments[i].content.replace(/#([^#]+)#/g, "");
          res.data.comments[i].option = res.data.comments[i].content.match(/#([^#]+)#/g);
        }
        that.setData({
          comments: res.data,
          score: res.data.score
        });
      } else {
        util.showTips(res.reason);
      }
    })
  },
  goPay(e) {
    let datas = this.data.datas
    wx.reportAnalytics('equip_choose', {
      equip_aid: datas.aid,
      equip_title: datas.title,
    });
    this.setData({
      skuShow: true
    });
  },
  previewImage(e) {
    let index = e.currentTarget.dataset.index;
    let i = e.target.dataset.i;
    let comments = this.data.comments.comments;
    this.setData({
      onshow: false
    });
    wx.previewImage({
      current: comments[index].imageList[i], // 当前显示图片的http链接
      urls: comments[index].imageList // 需要预览的图片http链接列表
    })
  },
  toTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },
  chat() {
    this.setData({
      chatShow: true
    });
  },
  onShareAppMessage() {
    let that = this,
      datas = this.data.datas;
    wx.reportAnalytics('equip_share', {
      equip_aid: datas.aid,
      equip_title: datas.title,
    });
    return {
      title: datas.title,
      path: '/pages/product/goods/detail?aid=' + that.data.aid
    }
  }
})