// pages/prod/prod.js
const app = getApp()
var http = require('../../utils/http.js');
var config = require('../../utils/config.js');
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopId: 1,
    shopName: '',
    picDomain: config.picDomain,
    indicatorDots: true,
    indicatorColor: '#f2f2f2',
    indicatorActiveColor: '#04358D',
    isAuthInfo: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    prodNum: 1,
    totalCartNum: 0,
    groupActivityId: 0,
    pic: "",
    imgs: '',
    prodName: '',
    price: 0,
    actPrice: 0,
    content: '',
    prodId: 0,
    brief: '',
    skuId: 0,
    popupShow: false,
    // 是否获取过用户领取过的优惠券id
    loadCouponIds: false,
    skuShow: false,
    skuGroupShow: false,
    commentShow: false,
    couponList: [],
    skuList: [],
    skuGroup: {},
    findSku: true,
    defaultSku: undefined,
    detaultGroupSku: undefined,
    selectedProp: [],
    selectedPropObj: {},
    selectedProperties: "",
    propKeys: [],
    allProperties: [],
    prodCommData: {},
    prodCommPage: {
      current: 0,
      pages: 0,
      records: []
    },
    littleCommPage: [],
    evaluate: -1,
    isCollection: false,
    shareShow: false,
    isDist: false, //是否分销员
    isDistProd: false, //是否分销商品
    distributionCardNo: "", //分销员卡号

    wxCodeShow: false, //是否显示二维码弹层
    shareWxCode: "", //分享二维码图片路径
    groupActivity: {}, // 团购活动
    endOfGroupTime: {}, // 距离团购活动结束还剩多久
    joinGroupList: [], // 可加入的团列表
    skuShowType: 0, // sku的显示类型 0普通sku 1拼团sku
    totalStocks: 0, // 活动剩余库存
    hasMaxNum: false, // 是否限购
    maxNum: 0, // 限购数量

    joinGroupListTimer: '',
    endOfGroupTimer: '',
    scene: '',
    prodDiscountList: [], // 商品促销活动列表

    phoneNumber: '', //客服电话
    showBacktop: false, //回到顶部显隐
    showDiscountPopup: false, //促销弹窗显隐
    videoContext: '', // 视频组件
    isPlaying: false, // 视频是否播放中
    currentSwiper: 0, // 当前轮播index
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    //根据Ticket获取保存的内容(pc团购扫码 || 分销)
    if (options.scene) {
      this.setData({
        scene: options.scene,
      })
      this.getContent() //根据Ticket获取保存的内容
    }
    // 加载商品信息
    if (options.prodid) {
      this.setData({
        prodId: options.prodid,
      });
      this.executionFunction() //所有需要加载的函数
    }
    if (options.cardno && options.type == 2) {
      // this.bindDistUser(options.cardno)
      this.setData({
        distributionCardNo: options.cardno,
      })
    }
    this.getCartCount() //请求购物车数量
  },

  /**
   * 执行函数
   */
  executionFunction: function () {

    // 加载评论数据
    this.getProdCommData();
    // 加载评论项
    this.getLittleProdComm();
    // 获取商品是否被收藏信息
    this.getCollection();
    // 查询分销开关是否开启
    this.getDistInfo();
    //加载商品数据
    this.getProdInfo();
    // 获取商品所有促销活动
    this.getPordDiscountList()

  },


  /**
   * 根据Ticket获取保存的内容
   */
  getContent: function () {
    http.request({
      url: "/qrcodeTicket/getContent",
      method: "GET",
      data: {
        ticket: this.data.scene
      },
      callBack: (res) => {
        console.log(res)

        var content = JSON.parse(res.content);
        var ids = JSON.parse(content.content)
        if (res.type == 1) { //pc团购二维码跳转
          this.setData({
            prodId: ids.prodId,
            groupActivityId: ids.groupActivityId
          })
          this.executionFunction() //所有需要加载的函数
        } else if (res.type == 2) { //分销员二维码跳转
          this.setData({
            prodId: ids.shareProdId,
            distributionCardNo: ids.cardNo
          })
          this.executionFunction() //所有需要加载的函数
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.endOfGroupTimer)
  },

  /**
   * 分销绑定用户
   */
  // bindDistUser(cardno) {
  //   var params = {
  //     url: "/p/distribution/bindUser",
  //     method: "post",
  //     data: cardno,
  //     callBack:res=>{
  //       console.log('绑定分销员',res)
  //     }
  //   }
  //   http.request(params)
  // },

  /**
   * 查询分销相关信息
   */
  getDistInfo() {
    //查询分销开关是否开启
    http.request({
      url: "/p/distribution/distributionBasicSet/canDistribution",
      method: "GET",
      dontTrunLogin: true,
      // data: {
      //   shopId: this.data.shopId,
      // },
      callBack: (res) => {
        if (res == 1) {
          this.getIsDistInfo();
        }
      }
    })
  },

  /**
   * 查询用户 是否为分销员
   */
  getIsDistInfo() {
    http.request({
      url: "/p/distribution/user/distributionUserInfo",
      method: "GET",
      callBack: (res) => {
        console.log('是否分销员', res)
        if (res && res.state == 1) {
          this.setData({
            isDist: true
          });
          this.getIsDistProd();
          wx.setStorageSync("distCardNo", res.cardNo);
        }
      }
    })
  },

  /**
   * 查询是否为分销商品
   */
  getIsDistProd() {
    http.request({
      url: "/p/distribution/prod/isDistributionProd",
      method: "GET",
      data: {
        prodId: this.data.prodId,
      },
      callBack: (res) => {
        console.log('是否分销商品', res)
        if (res) {
          this.setData({
            isDistProd: true
          });
        }
      }
    })
  },

  /**
   * 获取商品是否被收藏信息
   */
  getCollection() {
    wx.showLoading();
    var params = {
      url: "/p/user/collection/isCollection",
      method: "GET",
      dontTrunLogin: true,
      data: {
        prodId: this.data.prodId
      },
      callBack: (res) => {
        this.setData({
          isCollection: res
        })
        wx.hideLoading();
      }
    };
    http.request(params);
  },

  /**
   * 添加或者取消收藏商品
   */

  addOrCannelCollection() {
    util.checkAuthInfo(() => {
      var params = {
        url: "/p/user/collection/addOrCancel",
        method: "POST",
        data: this.data.prodId,
        callBack: (res) => {
          this.setData({
            isCollection: !this.data.isCollection
          })
          wx.showToast({
            title: res ? '已添加收藏' : '已取消收藏',
            duration: 3000,
            icon: 'none',
          })
          setTimeout(() => {
            wx.hideToast()
          }, 3000)
        }
      };
      http.request(params);
    })
  },


  // 获取商品信息
  getProdInfo() {
    wx.showLoading();
    var params = {
      url: "/prod/prodInfo",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        // userType: 0
      },
      callBack: (res) => {
        let pic = ''
        var imgStrs = res.imgs;
        var imgs = imgStrs.split(",");
        var content = util.formatHtml(res.content);
        pic = res.pic.split(',')
        res.pic = pic[0]
        this.setData({
          imgs: imgs,
          content: content,
          price: res.price,
          prodName: res.prodName,
          prodId: res.prodId,
          brief: res.brief,
          totalStocks: res.totalStocks,
          // skuId: res.skuId
          skuList: res.skuList,
          pic: res.pic,
          shopId: res.shopId,
          video: res.video,
          prodType: res.prodType
        });
        if (res.video) {
          this.getVideoInfo()
        }
        // 团购商品
        if (res.prodType === 1) {
          this.setData({
            groupActivityId: res.activityId
          });
          this.getGroupActivity();
          this.getJoinGroupList();
        }
        // 获取优惠券
        this.getCouponList();
        // 组装sku
        this.groupSkuProp(res.skuList);

        this.getShopInfo();

        wx.hideLoading();
      },
      errCallBack: (err) => {
        console.log(err)
        if (err.statusCode == 400) {
          wx.showModal({
            title: '提示',
            content: err.data,
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        }
      }
    };
    http.request(params);
  },


  /**
   * 获取店铺信息
   */
  getShopInfo() {
    http.request({
      url: "/shop/headInfo",
      method: "GET",
      data: {
        shopId: this.data.shopId,
      },
      callBack: (res) => {
        this.setData({
          shopName: res.shopName,
          shopLogo: res.shopLogo,
          phoneNumber: res.tel
        })
      }
    })
  },
  getProdCommData() {
    http.request({
      url: "/prod/prodCommData",
      method: "GET",
      data: {
        prodId: this.data.prodId,
      },
      callBack: (res) => {
        this.setData({
          prodCommData: res
        })
      }
    })
  },
  // 获取部分评论
  getLittleProdComm() {
    if (this.data.prodCommPage.records.length) {
      return;
    }
    this.getProdCommPage();
  },
  getMoreCommPage(e) {
    this.getProdCommPage();
  },
  // 获取分页获取评论
  getProdCommPage(e) {
    if (e) {
      if (e.currentTarget.dataset.evaluate === this.data.evaluate) {
        return;
      }
      this.setData({
        prodCommPage: {
          current: 0,
          pages: 0,
          records: []
        },
        evaluate: e.currentTarget.dataset.evaluate
      })
    }
    http.request({
      url: "/prod/prodCommPageByProd",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        size: 10,
        current: this.data.prodCommPage.current + 1,
        evaluate: this.data.evaluate
      },
      callBack: (res) => {
        res.records.forEach(item => {
          if (item.pics) {
            item.pics = item.pics.split(',')
          }
        })
        let records = this.data.prodCommPage.records
        records = records.concat(res.records)
        this.setData({
          prodCommPage: {
            current: res.current,
            pages: res.pages,
            records: records
          }
        })
        // 如果商品详情中没有评论的数据，截取两条到商品详情页商品详情
        if (!this.data.littleCommPage.length) {
          this.setData({
            littleCommPage: records.slice(0, 2)
          })
        }
      }
    })
  },

  /**
   * 评论小图点击事件(点击图片显示大图)
   */
  clickImg: function (e) {
    const current = e.currentTarget.dataset.index //获取当前点击的 图片 url
    const pics = e.currentTarget.dataset.pics
    wx.previewImage({
      current: pics[current],
      urls: pics
    })
  },


  getCouponList() {
    http.request({
      url: "/coupon/listByProdId",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        shopId: this.data.shopId,
      },
      callBack: (res) => {
        this.setData({
          couponList: res
        })
      }
    })
  },

  /**
   * 团购商品详情信息
   */
  getGroupActivity() {
    http.request({
      url: "/groupProd/info",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        groupActivityId: this.data.groupActivityId,
      },
      callBack: (res) => {
        if (res.success) {
          this.setData({
            groupActivity: res.obj,
            maxNum: res.obj.maxNum,
            hasMaxNum: res.obj.hasMaxNum
          })
          this.setDefaultGroupSku();
          this.groupActivityCountdown(res.obj)
        } else {
          this.setData({
            groupActivityId: null
          });
        }
      }
    })
  },
  // 团购倒计时
  groupActivityCountdown(groupActivity) {
    let endOfGroupTime;
    // activityStatus 1 未开始
    if (groupActivity.activityStatus === 1) {
      endOfGroupTime = util.endOfStartTime(util.dateToTimestamp(groupActivity.startTime), new Date().getTime())
    } else {
      endOfGroupTime = util.endOfStartTime(new Date().getTime(), util.dateToTimestamp(groupActivity.endTime))
    }
    this.setData({
      endOfGroupTime: endOfGroupTime,
      endOfGroupTimer: setTimeout(() => this.groupActivityCountdown(groupActivity), 1000)
    })
  },
  // 可加入的拼团列表
  getJoinGroupList() {
    http.request({
      url: "/groupProd/joinGroupList",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        groupActivityId: this.data.groupActivityId,
        showSize: 3
      },
      callBack: (res) => {
        this.setData({
          joinGroupList: res
        })
        this.joinGroupListCountdown(res)
      }
    })
  },
  joinGroupListCountdown(joinGroupList) {
    joinGroupList.forEach(item => {
      item.endOfGroupTime = util.endOfStartTime(new Date().getTime(), util.dateToTimestamp(item.endTime))
    })

    this.setData({
      joinGroupList: joinGroupList,
      joinGroupListTimer: setTimeout(() => this.joinGroupListCountdown(joinGroupList), 1000)
    })

  },
  //根据sku的属性 分组
  groupSkuProp: function (skuList) {
    // var skuList = this.data.skuList;
    if (skuList.length == 1 && skuList[0].properties == "") {
      this.setData({
        defaultSku: skuList[0]
      });
      this.setDefaultGroupSku();
      return;
    }
    var skuGroup = {};
    var allProperties = [];
    var propKeys = [];
    this.setData({
      selectedPropObj: {}
    });
    for (var i = 0; i < skuList.length; i++) {
      var defaultSku = this.data.defaultSku;
      var isDefault = false;
      if (!defaultSku && skuList[i].price == this.data.price) { //找到和商品价格一样的那个SKU，作为默认选中的SKU
        defaultSku = skuList[i];
        isDefault = true;
        this.setData({
          defaultSku: defaultSku
        });
      }
      var properties = skuList[i].properties; //版本:公开版;颜色:金色;内存:64GB
      allProperties.push(properties);
      var propList = properties.split(";"); // ["版本:公开版","颜色:金色","内存:64GB"]

      var selectedPropObj = this.data.selectedPropObj;
      for (var j = 0; j < propList.length; j++) {

        var propval = propList[j].split(":"); //["版本","公开版"]
        var props = skuGroup[propval[0]]; //先取出 版本对应的值数组

        //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
        if (isDefault) {
          propKeys.push(propval[0]);
          selectedPropObj[propval[0]] = propval[1];
        }

        if (props == undefined) {
          props = []; //假设还没有版本，新建个新的空数组
          props.push(propval[1]); //把 "公开版" 放进空数组
        } else {
          if (!this.array_contain(props, propval[1])) { //如果数组里面没有"公开版"
            props.push(propval[1]); //把 "公开版" 放进数组
          }
        }
        skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
      }
      this.setData({
        selectedPropObj: selectedPropObj,
        propKeys: propKeys
      });
    }
    this.parseSelectedObjToVals();
    this.setData({
      skuGroup: skuGroup,
      allProperties: allProperties
    });
    this.setDefaultGroupSku();
  },

  //将已选的 {key:val,key2:val2}转换成 [val,val2]
  parseSelectedObjToVals: function () {
    var selectedPropObj = this.data.selectedPropObj;
    var selectedProperties = "";
    var selectedProp = [];
    for (var key in selectedPropObj) {
      selectedProp.push(selectedPropObj[key]);
      selectedProperties += key + ":" + selectedPropObj[key] + ";";
    }
    selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1);
    this.setData({
      selectedProp: selectedProp,
      selectedProperties: selectedProperties
    });
    var findSku = false;
    for (var i = 0; i < this.data.skuList.length; i++) {
      if (this.data.skuList[i].properties == selectedProperties) {
        findSku = true;
        this.setData({
          defaultSku: this.data.skuList[i]
        });
        break;
      }
    }
    this.setData({
      findSku: findSku
    });
    this.setDefaultGroupSku();
  },

  //点击选择规格
  toChooseItem: function (e) {
    var ok = e.currentTarget.dataset.ok;
    if (ok == 0) {
      return;
    }
    var val = e.currentTarget.dataset.val;
    var key = e.currentTarget.dataset.key;
    var selectedPropObj = this.data.selectedPropObj;
    selectedPropObj[key] = val;
    this.setData({
      selectedPropObj: selectedPropObj
    });
    this.parseSelectedObjToVals();
  },

  //判断数组是否包含某对象
  array_contain: function (array, obj) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == obj) //如果要求数据类型也一致，这里可使用恒等号===
        return true;
    }
    return false;
  },

  /**
   * 设置选中的拼团sku
   */
  setDefaultGroupSku() {
    if (this.data.groupActivityId) {
      var groupSkuList = this.data.groupActivity.groupSkuList;
      if (groupSkuList) {
        for (var i = 0; i < groupSkuList.length; i++) {
          if (groupSkuList[i].properties == this.data.selectedProperties) {
            this.setData({
              detaultGroupSku: groupSkuList[i]
            });
            break;
          }
        }
      }
    }
  },


  /**
   * 去凑团
   */
  toSpellGroupDetail(e) {
    const groupTeamId = e.currentTarget.dataset.groupteamid
    util.checkAuthInfo(() => {
      wx.navigateTo({
        url: '/pages/spellGroupDetails/spellGroupDetails?groupTeamId=' + groupTeamId,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCartCount()
    if (this.data.prodType == 1) {
      this.getJoinGroupList()
    }
  },

  getCartCount: function () {
    var params = {
      url: "/p/shopCart/prodCount",
      method: "GET",
      dontTrunLogin: true,
      data: {},
      callBack: (res) => {
        if (res > 0) {
          // wx.setTabBarBadge({
          //   index: 2,
          //   text: res + "",
          // })
          var app = getApp();
          app.globalData.totalCartCount = res;
        } else {
          // wx.removeTabBarBadge({
          //   index: 2
          // })
          var app = getApp();
          app.globalData.totalCartCount = 0;
        }
        this.setData({
          totalCartNum: res
        })
      }
    };
    http.request(params);
  },

  /**
   * 阻止滚动
   */
  preventScorll() {

  },

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

  },

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

  },

  /**
   * 跳转到首页
   */
  toHomePage: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  /**
   * 跳转到购物车
   */
  toCartPage: function () {
    wx.switchTab({
      url: '/pages/basket/basket',
    })
  },
  handleContact: function (e) {
    console.log(e.detail, '----路径')
    console.log(e.detail.query, '----参数')
    // this.get_register()
  },
  /**
   * 创建商户
   * @param {*} event 
   */
  // get_register: function () {
  //   let url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc032a09413289004&secret=453c5047ae43288f1d015d48df32a5c0'
  //   wx.request({
  //     url:url,
  //     method: 'GET',
  //     data: {},
  //     header: {
  //       'content-type': 'application/json' // 默认值
  //     },
  //     success(res) {
  //       // console.log(res.data.access_token)
  //       wx.request({
  //         url: 'https://api.weixin.qq.com/cgi-bin/business/register?access_token='+res.data.access_token,
  //         method: 'POST',
  //         data: {
  //           account_name: "test_shopname",
  //           nickname: "苹果",
  //           icon_media_id: "png",
  //           transfer_to_commkf: true
  //         },
  //         header: {
  //           'content-type': 'application/json' // 默认值
  //         },
  //         success(res) {
  //           console.log(res.data)
  //         }
  //       })
  //     }
  //   })
  // },
  /**
   * 加入购物车
   */
  addToCart: function (event) {
    let skuList = this.data.skuList[0]
    if (skuList.weight > 20000) {
      wx.showToast({
        title: "商品超过20kg，太重咯~",
        icon: "none"
      })
      return;
    }
    if(this.data.totalStocks<0){
      wx.showToast({
        title: "该商品暂无库存~",
        icon: "none"
      })
      return;
    }
    if (this.data.isPlaying) {
      this._stopPlay()
    }
    if (!this.data.skuShow) {
      this.setData({
        skuShow: true
      })
      return
    }
    wx.showLoading({
      mask: true
    });
    // 查看是否授权
    util.checkAuthInfo(this.callChangeItem)
  },

  callChangeItem() {
    wx.showLoading({
      mask: true
    });
    http.request({
      url: "/p/shopCart/changeItem",
      method: "POST",
      data: {
        basketId: 0,
        count: this.data.prodNum,
        prodId: this.data.prodId,
        shopId: this.data.shopId,
        shopName: this.data.shopName,
        skuId: this.data.defaultSku.skuId,
        distributionCardNo: this.data.distributionCardNo
      },
      callBack: (res) => {
        this.setData({
          totalCartNum: this.data.totalCartNum + this.data.prodNum,
          skuShow: false,
        });
        wx.hideLoading();
        wx.showToast({
          title: "加入购物车成功",
          icon: "none"
        })
      }
    });
  },


  /**
   * 立即购买
   */
  buyNow: function () {
    let skuList = this.data.skuList[0]
    if (skuList.weight > 20000) {
      wx.showToast({
        title: "商品超过20kg，太重咯~",
        icon: "none"
      })
      return;
    }
    if(this.data.totalStocks<0){
      wx.showToast({
        title: "该商品暂无库存~",
        icon: "none"
      })
      return;
    }
    if (this.data.isPlaying) {
      this._stopPlay()
    }
    if (!this.data.skuShow) {
      this.setData({
        skuShow: true
      })
      return
    }

    wx.showLoading({
      mask: true
    });
    // 查看是否授权
    util.checkAuthInfo(this._buyNowData)
  },

  /**
   * 立即购买参数配置
   */
  _buyNowData() {
    wx.setStorageSync("orderItem", JSON.stringify({
      prodId: this.data.prodId,
      skuId: this.data.defaultSku.skuId,
      prodCount: this.data.prodNum,
      shopId: this.data.shopId,
      distributionCardNo: this.data.distributionCardNo
    }));
    wx.navigateTo({
      url: '/pages/submit-order/submit-order?orderEntry=1',
    })
  },


  /**
   * 减数量
   */
  onCountMinus: function () {
    var prodNum = this.data.prodNum;
    if (prodNum > 1) {
      this.setData({
        prodNum: prodNum - 1
      });
    }
  },

  /**
   * 加数量
   */
  onCountPlus: function () {
    var prodNum = this.data.prodNum;
    // 判断是否限购
    if (this.data.hasMaxNum) {
      if (prodNum < this.data.totalStocks && prodNum < this.data.maxNum) {
        this.setData({
          prodNum: prodNum + 1
        });
      } else {
        wx.showToast({
          title: '限购' + this.data.maxNum + '件',
          icon: 'none',
        })
      }
    } else {
      if (prodNum < this.data.totalStocks) {
        this.setData({
          prodNum: prodNum + 1
        });
      } else {
        wx.showToast({
          title: '库存不足!',
          icon: 'none'
        })
      }
    }
  },

  /**
   * 用户点击转发
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      var cardno = wx.getStorageSync("distCardNo");
      return {
        title: this.data.prodName,
        path: '/pages/prod/prod?prodid=' + this.data.prodId + '&cardno=' + cardno + '&type=' + this.data.shareType,
        imageUrl: this.data.pic,
      }
    } else {
      return {
        title: this.data.prodName,
        path: '/pages/prod/prod?prodid=' + this.data.prodId
      }
    }
  },

  /**
   * 优惠券
   */
  showPopup: function () {
    if (this.data.loadCouponIds) {
      this.setData({
        popupShow: true
      });
      return;
    }
    http.request({
      url: "/p/myCoupon/listCouponIds",
      method: "GET",
      data: {},
      callBack: (couponIds) => {
        var couponList = this.data.couponList;
        couponList.forEach(coupon => {
          if (couponIds && couponIds.length) {
            // 领取该优惠券数量
            var couponLimit = 0;
            couponIds.forEach(couponId => {
              if (couponId == coupon.couponId) {
                couponLimit++;
              }
            });
            // 小于用户领取优惠券上限，可以领取优惠券
            if (couponLimit < coupon.limitNum) {
              coupon.canReceive = true;
            } else {
              coupon.canReceive = false;
            }
          } else {
            coupon.canReceive = true;
          }
        });
        this.setData({
          couponList: couponList,
          popupShow: true,
          loadCouponIds: true
        })
      }
    })
  },

  showSku: function (e) {
    if (e.currentTarget.dataset.alonebuy == 1) {
      this.setData({
        skuShow: true,
        skuShowType: 0
      });
    } else {
      if (this.data.groupActivityId) {
        this.setData({
          skuShow: true,
          skuShowType: 1
        });
      } else {
        this.setData({
          skuShow: true,
          skuShowType: 0
        });
      }
    }

  },

  showGroupSku: function () {
    if (this.data.isPlaying) {
      this._stopPlay()
    }
    this.setData({
      skuShow: true,
      skuShowType: 1
    });

  },

  showComment: function () {
    this.setData({
      commentShow: true
    });
  },

  closePopup: function () {
    this.setData({
      popupShow: false,
      skuShow: false,
      commentShow: false
    });
  },

  /**
   * 赚字浮层
   */
  onShowShare: function (e) {
    if (this.data.isPlaying) {
      this._stopPlay()
    }
    this.setData({
      shareShow: true,
      shareType: e.currentTarget.dataset.type,
    });

  },
  /**
   * 回到顶部
   */
  backToTop: function () {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  /**
   * 监听页面滚动
   */
  onPageScroll: function (e) {
    if (e.scrollTop > 80) {
      this.setData({
        showBacktop: true
      })
    } else if (e.scrollTop < 80) {
      this.setData({
        showBacktop: false
      })
    }
  },

  closeEarn: function () {
    this.setData({
      shareShow: false

    })
  },

  toDistCenterPage: function () {
    wx.navigateTo({
      url: '/pages/dis-center/dis-center',
    })
  },

  /**
   * 生成小程序二维码
   */
  genWeixinCode() {
    wx.showLoading({
      mask: true
    })
    var cardNo = wx.getStorageSync("distCardNo");
    var content = JSON.stringify({
      shareProdId: this.data.prodId,
      cardNo: cardNo,
    })
    http.request({
      url: "/qrcodeTicket/miniQrCode",
      method: "GET",
      responseType: 'arraybuffer',
      data: {
        content: content,
        type: 2
      },
      callBack: (res) => {
        this.setData({
          wxCodeShow: true,
          shareShow: false,
          shareWxCode: "data:image/jpg;base64," + wx.arrayBufferToBase64(res)
        });
        wx.hideLoading();
      }
    })
    console.log('分销员id:' + cardNo)
  },

  /**
   * 关闭二维码弹窗
   */
  closeCodePopup() {
    this.setData({
      wxCodeShow: false
    });
  },

  /**
   * 保存图片至相册
   */
  downloadImg() {
    var ths = this
    var imgSrc = this.data.shareWxCode.slice(22); //base64编码
    var save = wx.getFileSystemManager();
    save.writeFile({
      filePath: wx.env.USER_DATA_PATH + '/分享商品-' + this.data.prodName + '.png',
      data: imgSrc,
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/分享商品-' + this.data.prodName + '.png',
          success: function (res) {
            wx.showToast({
              title: '保存成功',
            })
            ths.setData({
              wxCodeShow: false
            })
          },
          fail: function (err) {
            wx.showModal({
              title: '提示',
              content: '保存图片需要授予存储权限',
              success: modalRes => {
                if (modalRes.confirm) {
                  wx.openSetting({
                    success(settingdata) {
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        console.log('用户权限成功')
                      } else {
                        console.log('用户取消权限')
                      }
                    }
                  })
                }
              }
            })
          }
        })
        // console.log(res)
      },
      fail: err => {
        // console.log(err)
      }
    })
  },

  /**
   * 获取用户信息
   */
  onGotUserInfo: function (e) {
    if (e.detail.errMsg != "getUserInfo:fail auth deny") {
      this.setData({
        isAuthInfo: true
      });
      http.updateUserInfo();
    }
  },

  /**
   * 确认开团
   */
  groupConfirmOrder: function (e) {
    if (!this.data.findSku) {
      return;
    }
    wx.showLoading({
      mask: true
    });
    this.setData({
      teamId: e.currentTarget.dataset.teamid
    })
    // 查看是否授权
    util.checkAuthInfo(this._groupConfirmParams)
  },
  // 拼团确认订单参数
  _groupConfirmParams() {
    wx.setStorageSync("groupOrderItem", JSON.stringify({
      groupSkuId: this.data.detaultGroupSku.groupSkuId, // this.data.groupSkuId,
      prodCount: this.data.prodNum, // this.data.prodNum,
      groupTeamId: this.data.teamId // this.data.groupTeamId
    }));
    wx.navigateTo({
      url: '/pages/groupConfirmOrder/groupConfirmOrder',
    })
  },

  /**
   * 跳转到店铺页
   */
  toShopPage: function () {
    wx.navigateTo({
      url: '/pages/shopPage/shopPage?shopId=' + this.data.shopId,
    })
  },

  /**
   * 通过商品id获取商品所有促销活动
   */
  getPordDiscountList() {
    http.request({
      url: "/marking/discount/getDiscountByProdId",
      method: "GET",
      data: {
        prodId: this.data.prodId
      },
      callBack: res => {
        this.setData({
          prodDiscountList: res
        })
      }
    })
  },
  /**
   * 促销活动弹窗
   */
  clickDiscount: function () {
    var showDiscountPopup = !this.data.showDiscountPopup
    this.setData({
      showDiscountPopup
    })
  },

  /**
   * 页面从前台变为后台时执行
   */
  onHide: function () {
    this.setData({
      isCollection: false,
      skuShow: false,
    })
    clearTimeout(this.data.joinGroupListTimer)
  },

  /**
   * 视频信息
   */
  getVideoInfo() {
    wx.showLoading()
    wx.request({
      url: this.data.video + '?avinfo',
      success: res => {
        wx.hideLoading()
        let time = Number(res.data.format.duration).toFixed(0)
        this.setData({
          videoDuration: time < 60 ? '00′' + time + '″' : ((parseInt(time / 60) < 10 ? '0' + parseInt(time / 60) : parseInt(time / 60)) + '′' + (time % 60 < 10 ? '0' + time % 60 : time % 60) + '″')
        })
      }
    })
  },

  /**
   * 视频播放/停止按钮
   */
  videoOper() {
    if (this.data.isPlaying) {
      this._stopPlay()
    } else {
      this._startPlay()
    }
  },

  /**
   * 视频播放结束时
   */
  playEnd() {
    this._stopPlay()
  },

  _startPlay() {
    this.setData({
      isPlaying: true,
    })
    this.videoContext.play()
    this.videoContext.seek(0)
  },
  _stopPlay() {
    this.setData({
      isPlaying: false
    })
    this.videoContext.stop()
    this.videoContext.seek(0)
  },

})