// packageH/deposit_group/activity_index/activity_index.js
const app = getApp();
Page({
  data: {
    activity_id: '', // 活动id
    goods_id: '', // 活动商品id
    options_id: '', // 绑定商品规格的id
    activity_start: '', //活动开始时间
    activity_end: '', // 活动结束
    goods_count: 1,
    backgroundRGB: [], // 主题色
    actData: {
      deposit: 0
    },
    timeData: {},
    currentTime: parseInt(new Date().getTime() / 1000),
    activity_order: [],
    ladderList: [], // 梯度数组
    steps: 0,
    shareShow: false, // 弹起分享面板
    shareOptions: {},
    options: [
      { name: "分享海报", icon: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/depositGroup/poster@2x.png", description: "生成海报" },
      { name: "微信", icon: "wechat", openType: "share", description: "分享给好友"},
    ],
    cservice: {},
    posterShow: false, // 海报
    goodsPopupShow: false, // 商品详情
    showAgrPopup: false, // 协议签订
    contractId: '', // 合同id
    shareText: '',

    o2oStore: {}//门店定金团信息
  },

  onLoad: function (options) {
    if (options.scene) {
      let {id} = this.sceneDecode(options.scene);
      this.setData({
        activity_id: id
      });
    }
    if (options.id) {
      this.setData({
        activity_id: options.id
      });
    }
  },
  onShow: function () {
    this.getData();
  },

  sceneDecode(scene) {
    scene = decodeURIComponent(scene);
    let paramArr = scene.split("&");
    const senceValues = {};

    paramArr.forEach((item, index) => {
      let key = item.split("=")[0];
      let value = item.split("=")[1];
      senceValues[key] = value;
    });
    return senceValues;
  },
  getData () {
    let url = app.getNetAddresss("plugin.deposit-ladder.frontend.index.activity");
    app._getNetWork({
      url,
      data: {
        id: this.data.activity_id
      },
      success: (resdata) => {
        if (resdata.data.result === 1) {
          let res = resdata.data;
          let bgColor = this.hexStringToRGB(res.data.activity.theme_color);
          let richText = this.replaceDetail(res.data.activity.activity_explain);
          let commissionText = res.data.activity.commission ? `每成功邀请到一位好友下定，可获得${res.data.activity.commission}元奖励` : '立即分享给好友';
          try {
            wx.setStorageSync('backgroundRGB', bgColor);
          } catch (err) {
            // err
          }
          this.setData({
            activity_id: res.data.activity.id,
            goods_id: res.data.activity.goods_id,
            goods_option_id: res.data.activity.goods_option_id,
            activity_start: res.data.activity.activity_start * 1000 - new Date(),
            activity_end: res.data.activity.activity_end * 1000 - new Date(),
            actData: res.data.activity,
            cservice: res.data.cservice,
            backgroundRGB: bgColor,
            richNode: richText,
            shareOptions: res.data.activity.share,
            shareText: commissionText,
            o2oStore: res.data.activity.has_one_polymorphism||{},
          });

          // 把参与记录分段
          if (res.data.activity.activity_order.length > 4) {
            this.setData({
              recordList:  res.data.activity.activity_order.slice(0, 4),
              isMore: true
            });
          } else {
            this.setData({
              recordList: res.data.activity.activity_order,
              isMore: false
            });
          }
          this.resetSteps(res.data.activity.ladder);
        } else {
          wx.showModal({
            content: resdata.data.msg,
            showCancel: false,
            success () {
              // 确定后跳转回上一页
              let cps =  getCurrentPages();
              if (cps.length > 1) {
                wx.navigateBack({
                  delta: 1,
                });
              } else {
                wx.redirectTo({
                  url: '/packageG/index/index',
                });
              }
            }
          });
        }
      },
      fail (err) {
        console.log("失败", err);
      }
    });
  },

  // 设置 达到哪一阶段
  resetSteps (arr) {
    let steps = 0;
    arr = arr.reverse();
    let firstLadder = {...arr[0]};
    let actData = this.data.actData;
    firstLadder.deal_price = actData.bind_goods.price;
    arr.unshift(firstLadder);
    for (let index = 0; index < arr.length; index++) {
      // 第一梯队是一个区间

      if (index === 0 && ((actData.ladder_type === 1 && actData.sale_count < arr[index].sale_num) || ( actData.ladder_type === 0 && actData.order_count < arr[index].deal_num))) {
        steps = 0;
        break;
      }
      if (index > 0 && (actData.ladder_type === 1 && actData.sale_count >= arr[index].sale_num) || (actData.ladder_type === 0 && actData.order_count >= arr[index].deal_num)) {
        steps = index;
      } 
    }
    this.setData({
      steps,
      ladderList: arr
    });
  },


  //获取商品详
  getGoodDetail() {
    if (this.data.goodsInfo) {
      this.setData({
        goodsPopupShow: true
      });
      return;
    }
    let url = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url,
      data: {
        id: Number(this.data.actData.bind_goods.id),
      },
      success: (resdata) => {
        console.log(resdata);
        if (resdata.result == 0) {
          app.tips(resdata.data.msg);
          return;
        }
        this.setData({
          goodsInfo: resdata.data.data.get_goods,
          goodsPopupShow: true
        });
      }
    });
  },

  changeGoodCount (e) {
    let num = e.currentTarget.dataset.num * 1;
    this.handlerGoods(num);
  },

  // 添加商品
  goodsDetailCartAdd(event) {
    let num = event.detail * 1;
    this.handlerGoods(num);
  },


  // 修改商品数量
  handlerGoods (num) {
    let count = this.data.goods_count + num;
    if (count < 1) {
      app.tips("商品数量最低为1");
      return;
    }
    if (this.data.actData.limit !== 0 && (count > this.data.actData.limit)) {
      app.tips(`单次限购${ this.data.actData.limit}件`);
      return;
    }
    if ((count + this.data.member_order_count) > this.data.actData.limit_total) {
      app.tips(`会员限购${ this.data.actData.limit_total}件`);
      return;
    }
    this.setData({
      goods_count: count
    });
  },

  // 加载更多列表
  loadMore () {
    this.setData({
      recordList: this.data.actData.activity_order,
      isMore: false
    });
  },


  // 打开分享面板 
  openShareShow () {
    this.setData({
      shareShow: true
    });
  },
  onCloseShare () {
    this.setData({
      shareShow: false
    });
  },

  // 分享面板 选择分享方式
  onSelectShare (e) {
    if (e.detail.name == "复制链接") {
      wx.setClipboardData({
        data: e.detail.link,
        success () {
          app.tips("复制链接成功");
        },
        fail () {
          app.tips("复制链接失败");
        }
      });
    } else if (e.detail.name == "分享海报") {
      this.setData({
        posterShow: true,
      });
    } 
    
  },

  // 计时器
  onChangeTime(e) {
    this.setData({
      timeData: e.detail,
    });
  },

  // 立即下定
  buyNow () {
    if (this.data.goods_count < 1) {
      app.tips("商品数量不能为零");
      return;
    }
    // 跳转电子合同
    if (this.data.actData.agreement === 0) {
      this.getContractStatue();
    } else {
      this.showAgreementPopup();
    }
  },

  // 电子合同签订状态
  getContractStatue () {
    let url = app.getNetAddresss("plugin.deposit-ladder.frontend.yun-sign.check-yun-sign");
    app._getNetWork({
      url,
      data: {
        goods_id: this.data.goods_id,
      },
      success: (res) => {
        // console.log(res)
        if (res.data.result === 1) {
          if (res.data.data.contract_id) {
            this.setData({
              contractId: res.data.data.contract_id
            });
            this.showAgreementPopup();
          } else {
            this.toOrder();
          }
        } else {
          wx.showModal({
            content: res.data.msg
          });
        }
      }
    });
  },

  // 协议签订弹框
  showAgreementPopup () {
    this.setData({
      showAgrPopup: true
    });
  },
  // 阅读并同意协议
  agreement () {
    this.closeAgreementPopup();
    this.setData({
      agreement: true
    });
    this.toOrder();
  },
  toOrder() {
    if (this.data.goods_id) {
      let submitActionTag = "-2"; //立即购买
      let {goods_id, goods_count} = this.data;
      // 定金下单没有商品规格的 goods_option_id, activity_id
      let _url = "/packageD/buy/myOrder_v2/myOrder_v2?goodsId=" + goods_id + "&optionsId=0" + "&total=" + goods_count;
      if(this.data.o2oStore&&this.data.o2oStore.polymorphism_id){
        _url = _url + "&store_id=" + this.data.o2oStore.polymorphism_id;
        submitActionTag = "o2oDeposit"; //门店的定金团
      }
      _url = _url + '&tag=' + submitActionTag;
      wx.navigateTo({
        url: _url
      });
    }
  },
  closeAgreementPopup () {
    this.setData({
      showAgrPopup: false,
    });
  },


  // 去除富文本中图片样式
  replaceDetail (details){
    var texts='';
    while(details.indexOf('<img')!=-1){
      // 截取到<img前面的内容
      texts+=details.substring('0',details.indexOf('<img')+4);
      // <img 后面的内容
      details = details.substring(details.indexOf('<img')+4);
      if(details.indexOf('style=')!=-1 && details.indexOf('style=')<details.indexOf('>')){
        texts+=details.substring(0,details.indexOf('style="')+7)+"max-width:100%;height:auto;margin:0 auto;";
        details=details.substring(details.indexOf('style="')+7);
      }else{
        texts+=' style="max-width:100%;height:auto;margin:0 auto;" ';
      }
    }
    texts+=details;//最后拼接的内容
    return texts;
  },

  // 把十六进制颜色转换为rgb
  hexStringToRGB(hexString) {
    let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    if (!hexString) hexString = '#fec400';
    let color = hexString.toLowerCase();
    if (reg.test(color)) {
      // 如果只有三位的值，需变成六位
      if (color.length === 4) {
        let colorNew = "#";
        for (let i = 1; i < 4; i += 1) {
          colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
        }
        color = colorNew;
      }
      let colorChange = [];
      for (let j = 1; j < 7; j += 2) {
        colorChange.push(parseInt("0x" + color.slice(j, j + 2)));
      }
      return colorChange;
    }
    return [];
  },

  gotoOrder() {
    wx.navigateTo({
      url: "/packageA/member/myOrder_v2/myOrder_v2",
    });
  },

  gotoSignPage () {
    wx.navigateTo({
      url: `/packageH/signIndexPlu/signPage?id=${this.data.contractId}`,
    });
  },

  gotoRankList() {
    wx.navigateTo({
      url: `/packageH/deposit_group/rankList/rankList?id=${this.data.activity_id}`,
    });
  },

  onShareAppMessage (options) {
    let shareObj = {};
    let mid = wx.getStorageSync('yz_uid')||'';
    if (this.data.shareOptions.share_title && this.data.shareOptions.share_img) {
      shareObj = {
        path: `/packageH/deposit_group/activity_index/activity_index?id=${this.data.activity_id}&mid=${mid}`,
        title: this.data.shareOptions.share_title,
        imgUrl: this.data.shareOptions.share_img,
      };
    } else {
      shareObj = {
        path: `/packageH/deposit_group/activity_index/activity_index?id=${this.data.activity_id}&mid=${mid}`,
        title: "芸众商城",
        imgUrl: this.data.actData.goods_option&&this.data.actData.goods_option.thumb||null,
      };
    }
    return shareObj;
  },

  // 分享朋友圈
  onShareTimeline() {
    let shareObj = {};
    if (this.data.shareOptions.share_title && this.data.shareOptions.share_img) {
      shareObj = {
        query: `id=${this.data.activity_id}`,
        title: this.data.shareOptions.share_title,
        imageUrl: this.data.shareOptions.share_img,
      };
    } else {
      shareObj = {
        path: `id=${this.data.activity_id}`,
        title: "芸众商城",
      };
    }
    return shareObj;
  },
});