var app = getApp();
var WxParse = require('../../../wxParse/wxParse.js');
let siftTop='';
let foshowTop='';

var share_tag = '-1'; // 顶部导航返回上一级按钮 标志
// 商品详情

Component({
  properties: {
    // 属性值可以在组件使用时指定
    goodType: {
      type: String
    },
    goodsId: {
      type: Number
    },
    goodsType: {
      type: String
    },

    hoet: {
      type: null
    },

    boxHeight: {
      type: Number
    },
    xqBoxShow: {
      type: null
    },
    datop: {
      type: null
    },
    ipnonexbol: {
      type: null
    },
    activityid: {
      type: null
    },
  },
  data: {
    language: '',
    // 图片域名
    imagUrl: 'https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/',
    current: 1,

    datop: 1,
    groupStock: 1, // 当前拼团商品的库存

    // 判断显示限时还是结束
    istime: false,
    // 是否有更多评论
    noMoreComment: false,
    // 初始评论页数
    commentPage: 1,
    posterShow: false, // 商品分享二维码显示
    hoet: false,

    popStock: 0, // 库存


    gooddatas: {}, // 总商品数据
    goodsInfo: {}, // 商品详情信息
    activityId: '', // 活动id
    goodsId: '',



    team: [], //成团信息
    show1: false,

    // 商品详情
    first_content: '',
    second_content: '',
    third_content: [],
    activeName: 'first',
    end_time: '', // 截止结束时间
    start_time: '', // 截止开始时间
    // 轮播高度自适应
    aheight: 750,

    btnData: { // 侧边按钮定位
      over_top: 500,
      icon_url: "https://www.yunzmall.com//min_img/icon-fontclass-zhiding.png"
    },

    heightDome: '', // 高度
    nowTime: '', // 现在的时间
    iPnoneBottomBol: false,
    isCheckActivity: true, //下单前检查客户今天是否超出限制
    showGoodslist: false,
    //活动是否结束
    isTimeEnd: false,
    begTimeStr: '',
    //限时购据开始时间倒计时
    beginDownObj: {
      day: '00',
      hou: '00',
      min: '00',
      sec: '00'
    },

    getMarketPrice: '',
    goodType: null, //商品类型： 拼购商品 groupBuy ||抢团商品 grabGroup

  },
  lifetimes: {
    attached(e) {
      this.getiPnoneBottom();
      let language = wx.getStorageSync('langIndex');
      this.setData({
        'language': language.en
      });
      this.setData({
        activityId: this.properties.activityid || 0,
        goodsId: this.properties.goodsId,
        goodsInfo: {},
        goodType: this.properties.goodType
      });
      this.getData();

      this.getCommentData();
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
    ready() {
      let that = this;
      this.createSelectorQuery().select('.sift').boundingClientRect(function (rect) {
        that.setData({
          pjtop: rect.top - 80
        });
      }).exec();
      this.createSelectorQuery().select('.pullBox').boundingClientRect(function (rect) {
        console.log(rect.top);
        that.setData({
          xqtop: rect.top - 80
        });
      }).exec();
      try {
        wx.getStorage({
          key: 'yz_basic_info',
          success: function (res) {
            that.setData({
              getMarketPrice: res.data.lang.goods.market_price
            });
          },
        });
      } catch (e) {
        console.log(e);
      }
    }
  },
  observers:{
    'datop':function(obs){
      let that = this;
      if(that.data.getTapNoObsever){
        return;
      }
      this.createSelectorQuery()
        .select(".sift")
        .boundingClientRect(function (rect) {
          siftTop = rect.top -50;
        })
        .exec();
      this.createSelectorQuery()
        .select(".foShowBox")
        .boundingClientRect(function (rect) {
          foshowTop = rect.top - 150;
        })
        .exec();
      console.log(foshowTop,siftTop);
      if(foshowTop < 0 && siftTop < 0){
        that.setData({
          current:3
        });
      }else if(siftTop <=0 && foshowTop>0){
        that.setData({
          current:2
        });
      }else if(foshowTop >0 && siftTop > 0){
        that.setData({
          current:1
        });
      }
    }
  },
  methods: {
    getiPnoneBottom() {
      let that = this;
      try {
        var value = wx.getStorageSync('iPhoneBottom');
        if (value) {
          that.setData({
            iPnoneBottomBol: true
          });
          // Do something with return value
        }
      } catch (e) {
        // Do something when catch error
      }
    },
    showGoodslistM() {
      this.setData({
        showGoodslist: true
      });
    },
    clicktapshow() {
      this.setData({
        showGoodslist: false
      });
    },
    closeCs() {
      this.setData({
        showCs: false
      });
    },
    showCan() {
      console.log('开启参数弹窗');
      this.setData({
        showCs: true,
        second_content: this.data.goodsInfo.has_many_params
      });
    },
    gotoShopGoods(e) {
      let _id = e.target.dataset.id || e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/packageA/detail_v2/detail_v2?id=' + _id
      });
    },
    // 隐藏评论按钮
    streetClose() {
      this.setData({
        streetShow: false
      });
    },
    // 查看全部评论
    goKb() {
      console.log('打开全部口碑');
      this.setData({
        streetShow: true
      });
      this.getCommentData();
    },
    // 顶部导航
    getTap(e) {
      console.log(e.currentTarget.id);
      let pid = e.currentTarget.id;
      this.setData({
        current: pid,
        getTapNoObsever:true
      });
      if (pid == 1) {
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300,
          success:(res)=>{
            setTimeout(() => {
              this.setData({
                getTapNoObsever:false
              });
            }, 300);
          }
        });
      } else if (pid == 2) {
        wx.pageScrollTo({
          scrollTop: this.data.pjtop + 50,
          duration: 300,
          success:(res)=>{
            setTimeout(() => {
              this.setData({
                getTapNoObsever:false
              });
            }, 300);
          }
        });
      } else if (pid == 3) {
        this.setData({
          xqBoxShow: true
        });
        wx.pageScrollTo({
          scrollTop: this.data.xqtop +100,
          duration: 300,
          success:(res)=>{
            setTimeout(() => {
              this.setData({
                getTapNoObsever:false
              });
            }, 300);
          }
        });
      }
    },
    imageLoad(res) {
      if (res.target.dataset.index == 1) {
        this.setData({
          heightDome: res.detail.height
        });
      }
    },

    showGroupMore() {
      if (this.data.team.length == 0) {
        wx.showToast({
          icon: 'none',
          title: '抱歉，暂无更多可参与的团!',
          duration: 1500
        });
        return;
      }

    },
    // 点击蒙层触发
    tapOverlay() {
      this.setData({

        posterShow: false
      });
    },
    showPop() {
      this.setData({
        show1: true
      });
    },
    // 获取数据
    getData() {
      let urlStr = null;
      urlStr = app.getNetAddresss('plugin.star-spell.frontend.index.goodsDetail');
      urlStr += '&goods_id=' + this.data.goodsId;

      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            console.log("team", res.data.team);
            let thumb = [];
            thumb.push(res.data.goods.thumb);
            this.setData({
              gooddatas: res.data.goods,
              popStock: res.data.goods.stock,
              team: res.data.team,
              third_content: res.data.comment.data,
              end_time: res.data.goods.end_time,
              'gooddatas.thumb': thumb,
              'gooddatas.status': res.data.activity_state,
              first_content: res.data.goods.content
            });
            console.log("team", this.data.team, res.data.team);

            // 分享的自定义图片
            wx.setStorageSync('GoddsShareImg', thumb[0]);
            this.triggerEvent('parentEvent', [this.data.gooddatas.title]);
            let start_time = new Date().getTime() / 1000;
            this.setData({
              nowTime: start_time
            });


            let _team = this.data.team;
            for (let i = _team.length - 1; i >= 0; i--) {
              if (_team[i].end_time <= start_time) {
                _team.splice(i, 1); //删除下标为i的元素
              }
            }
            this.setData({
              team: _team.splice(0, 3)
            });

            this._timeCompare(res.data.goods.start_time);

            let article = this.data.first_content;
            try {
              if (article.indexOf('&#') <= -1) {
                WxParse.wxParse('article', 'html', article, this);
              }
            } catch (e) {
              //TODO handle the exception
            }
            // WxParse.wxParse('article', 'html', article, this)
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        }
      });
    },
    gotoStarMusicListGroup() {
      if (this.data.team.length == 0) return app.tips("暂无更多可参团");
      wx.navigateTo({
        url: '/packageH/starMusic/starMusicListGroup/starMusicListGroup?id=' + this.data.gooddatas.activity_id
      });
    },
    gotoStarMusicGroupDetails(evt) {
      let id = evt.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/packageH/starMusic/starMusicGroupDetails/starMusicGroupDetails?id=' + id
      });
      //this.$router.push(this.fun.getUrl("starMusicGroupDetails",{id}));
    },

    // 获取评论数据
    getCommentData() {
      let that = this;
      let json = {
        goods_id: this.properties.goodsId,
        page: this.data.commentPage
      };
      let urlStr = app.getNetAddresss('goods.comment.get-comment');
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.data.length < 20) {
              that.setData({
                noMoreComment: true
              });
            }
            that.setData({
              commentPage: that.data.commentPage + 1
            });
            if (!that.data.third_content) {
              that.setData({
                third_content: []
              });
            }
            that.setData({
              third_content: [...that.data.third_content, ...res.data.data]
            });
            console.log(that.data.third_content);
            if (app._isTextEmpty(that.data.third_content)) {
              console.log('空没评论');
              that.setData({
                thirKong: false
              });
            } else {
              console.log("不空");
              that.setData({
                thirKong: true
              });
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        }
      });
    },


    //查看大图
    seePicture(evt) {
      let pics = evt.currentTarget.dataset.pics;
      let index = evt.currentTarget.dataset.index;
      wx.previewImage({
        current: pics[index], // 当前显示图片的http链接
        urls: pics // 需要预览的图片http链接列表
      });
    },

    // 跳转评论详情
    toContentInfo(e) {
      let data = e.target.dataset.item || e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/packageD/member/CommentDetails/CommentDetails?order_id' + data.order_id + '&goods_id=' + data.goods_id +
          '&uid=' + data.uid + '&comment_id=' + data.id
      });
    },
    // 顶部返回按钮
    goto() {
      if (share_tag == '-1') {
        wx.navigateBack({
          delta: 1
        });
      } else {
        wx.reLaunch({
          url: '/packageG/index/index',
        });
      }
    },
    // 跳转主页
    gotoHome() {
      wx.reLaunch({
        url: '/packageG/index/index',
      });
    },
    // 跳转个人中心
    gotoMember() {
      wx.reLaunch({
        url: '/packageG/member_v2/member_v2'
      });
    },
    postShow() {

      let that = this;
      if (that.data.posterImg) {
        this.setData({
          posterShow: true
        });
      } else {
        wx.showLoading({
          title: '海报生成中',
        });
        let urlStr = app.getNetAddresss('plugin.star-spell.frontend.goods-poster.generateGoodsPoster');

        urlStr += '&id=' + this.data.goodsId;

        app._getNetWork({
          url: urlStr,
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              this.setData({
                posterShow: true,
                posterImg: res.data.image_url
              });
            } else {
              wx.showToast({
                icon: 'none',
                title: res.msg,
                duration: 1500
              });
              this.setData({
                posterShow: false
              });
            }
            wx.hideLoading();
          }
        });
        setTimeout(function () {
          wx.hideLoading();
        }, 5000);
      }
    },


    // 隐藏二维码
    tapposterShow() {
      this.setData({
        posterShow: false
      });
    },
    // 长按保存
    saveImg() {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {}
            });
          }
        }
      });
      var imgSrc = this.data.posterImg;
      wx.downloadFile({
        url: imgSrc,
        success: function (res) {
          // 图片保存到本地
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (data) {
              wx.showToast({
                title: '保存成功',
                icon: 'none',
                duration: 2000
              });
            },
            fail: function (err) {
              if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
                wx.openSetting({
                  success(settingdata) {
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      wx.showToast({
                        icon: 'none',
                        title: '获取权限成功,再次长按保存图片',
                        duration: 1500
                      });
                    } else {
                      wx.showToast({
                        icon: 'none',
                        title: '获取权限失败,保存图片需要用户授权',
                        duration: 1500
                      });
                    }
                  }
                });
              }
            },
            complete(res) {
              console.log(res);
            }
          });
        }
      });
    },
    //获取时间-限时购
    _timeCompare(begin) {
      let beginTime = new Date(parseInt(begin) * 1000);
      let now = new Date();
      if (now >= beginTime) {
        this.setData({
          isTime: true
        });
        //开启倒计时
        this._countDown();
      } else {
        this.setData({
          isTime: false,
          isTimeEnd: false,
          begTimeStr: begin * 1000
        });
        //开启距离开始倒计时
        this.beginDown();
      }
    },
    //倒计时
    _countDown: function () {
      let newTime = new Date().getTime();
      let endTime = this.data.end_time * 1000;
      let obj = null;
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this._timeFormat(day),
          hou: this._timeFormat(hou),
          min: this._timeFormat(min),
          sec: this._timeFormat(sec)
        };
      } else { //活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        };
      }
      this.setData({
        countDownObj: obj
      });
      // console.log('gggggggggggggggg',endTime ,newTime )
      if (endTime - newTime < 0) {
        this.setData({
          countDownObj: {
            day: '00',
            hou: '00',
            min: '00',
            sec: '00'
          },
          isTimeEnd: true
        });
      } else {
        setTimeout(this._countDown.bind(this), 1000);
      }

    },
    //倒计时
    beginDown: function () {
      let newTime = new Date().getTime();
      let endTime = this.data.begTimeStr;
      let obj = null;
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this._timeFormat(day),
          hou: this._timeFormat(hou),
          min: this._timeFormat(min),
          sec: this._timeFormat(sec)
        };
      } else { //活动已结束，全部设置为'00'
        this.setData({
          isTime: true,
          isTimeEnd: true
        });
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        };
      }
      this.setData({
        beginDownObj: obj
      });
      if (endTime - newTime < 0) {
        this.setData({
          isTime: true,
          isTimeEnd: true
        });
        this.setData({
          beginDownObj: {
            day: '00',
            hou: '00',
            min: '00',
            sec: '00'
          }
        });
      } else {
        setTimeout(this.beginDown.bind(this), 1000);
      }
    },
    //小于10的格式化函数
    _timeFormat(param) { //小于10的格式化函数
      return param < 10 ? '0' + param : param;
    },


  },
  pageLifetimes: {
    show() {
      // 页面被展示
    },
    hide() {
      // 页面被隐藏
    },
    resize(size) {
      // 页面尺寸变化
    }
  }

});