// packageA/detail_v2/detail_v2.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    prop_goods_info: {},
    producer_id: "",
    // showIn:false,
    /*商品类型*/
    goods_type: "",
    /*商品id*/
    goods_id: "",
    /*商品数据*/
    // 智能柜标示
    mark: "",
    hoet: false,
    enterAt:'',
    // start: "",
    // end: "",
    title: "",
    mark_id: "",
    fight_groups: "", // 拼团的商品id
    loginshow: false,
    groups_title: "",
    liveshow: false,
    iPnoneBottomBol: false,
    activity_id: "",
    is_open: "",
    store_id: 0,

    // 云库存
    fromStock: "",
    is_toker: false,

    // 新零售
    mode: null,
    category_option_id:'',
    // 置换亿栈债务人店铺id
    debtId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    console.log(option,"custom_params");
    if (option.mid) {
      app._setMid(option.mid);
    }
    if(option.custom_params) {
      app._setMid(JSON.parse(decodeURIComponent(option.custom_params)).mid);
    }
    wx.showLoading({
      title: "加载中...",
    });
    this._datainit();
    this.getiPnoneBottom();
    // 页面传参
    if (option.liveshow) {
      this.setData({
        liveshow: true,
      });
    }
    if (option.fromStock) {
      this.setData({
        fromStock: option.fromStock,
      });
    }
    let paramsID = null;
    //抢团69||grabGroup,新拼团：99,珍惠拼zhpGroup，starGroup
    let pluginName = new Map([
      ["group", "group_goods"],
      ["group_buy", "groupBuy"],
      ["69", "grabGroup"],
      ["99", "groupwork"]
    ]);
    if (option.scene) {
      let scene = decodeURIComponent(option.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "id") {
            //解决场景：海报带参后字符长度超出，将参数值直接与id合并，通过 / 分割，第一个需为id,其他自定义
            paramsID = chil_arr[1].split("/");
            this.setData({
              goods_id: paramsID[0],
            });
          } else if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          } else if (chil_arr[0] == "shop_id") {
            app._setshopid(Number(chil_arr[1]));
          } else if (chil_arr[0] == "name") {
            //判断是否 pluginName 包含key(即chil_arr[1])，有则取出赋值，找不到对应key则value为chil_arr[1]
            let _gtype = pluginName.has(chil_arr[1])?pluginName.get(chil_arr[1]):chil_arr[1];
            this.setData({
              goods_type: _gtype,
            });

            if (paramsID&&paramsID[1] && _gtype == "group_goods") {
              this.setData({
                store_id: paramsID[1],
              });
            }
            wx.hideLoading();
          } else if (chil_arr[0] == "activity_id") {
            this.setData({
              activity_id: chil_arr[1],
            });
          }else if (chil_arr[0] == "md") {
            //新零售商品，md：1||商品普通购买，2||代理套餐，3||进货
            this.setData({
              mode: chil_arr[1],
            });
            this.getRetailGoods();
          } else {
            // if (this.firstlogin()) {
            //   wx.hideLoading();
            // } else {
            this._getData();
            // }
          }
        }
      }
    } else {
      if (option.shop_id) {
        app._setshopid(Number(option.shop_id));
      }
      if(option.coid){
        this.setData({
          category_option_id:option.coid
        });
      }
      if (option.id) {
        paramsID = option.id.split("/");
        this.setData({
          goods_id: paramsID[0],
        });
      }
      if (option.producer_id) {
        this.setData({
          producer_id: option.producer_id,
        });
      }
      if (option.mid) {
        app._setMid(option.mid);
      }

      if (option.mark) {
        this.setData({
          mark: option.mark,
        });
      }
      if (option.mark_id) {
        this.setData({
          mark_id: option.mark_id,
        });
      }
      if (option.start) {
        this.setData({
          'enterAt.start': option.start,
        });
      }
      if (option.end) {
        this.setData({
          'enterAt.end': option.end,
        });
      }
      if (option.fight_groups) {
        this.setData({
          fight_groups: option.fight_groups,
        });
      }
      if (option.vid) {
        app._setvid(option.vid);
      }
      if (option.circle_invitation_id) {
        app._setcircleInvitationId(option.circle_invitation_id);
      }
      if (option.roomid) {
        app._setroomid(option.roomid);
      }
      if (option.activity_id) {
        this.setData({
          activity_id: option.activity_id,
        });
      }
      // 置换亿栈
      if(option.debtId){
        this.setData({
          debtId:option.debtId
        })
      }
      if (option.name) {
        //判断是否 pluginName 包含key(即option.name)，有则取出赋值，找不到对应key则value为option.name
        let _gtype = pluginName.has(option.name)?pluginName.get(option.name):option.name;
        wx.hideLoading();
        if (paramsID&&paramsID[1] && option.name == "group") {
          this.setData({
            store_id: paramsID[1],
          });
        }

        if(option.md){
          this.setData({
            mode: option.md,
          });
          wx.hideLoading();
          this.getRetailGoods();
        } else{
          this.setData({
            goods_type: _gtype,
          });
        }
      }
      // else {
      // if (this.firstlogin()) {
      // wx.hideLoading();
      // } else {
      //   this._getData();
      // }
      // }
    }
    // if (this.firstlogin()) {
    wx.hideLoading();
    // } else {
    if(!this.data.goods_type && option.name!='retailGood'){
      this._getData();
    }
    // }
    if ("kind" in option == true) {
      this.setData({
        vieText: option.kind,
      });
    }
  },
  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
    }
  },
  onParentEvent: function (event) {
    // 自定义组件触发事件时提供的detail对象，用来获取子组件传递来的数据
    this.setData({
      title: event.detail[0],
    });
  },
  touchStart(e) {
    let sy = e.touches[0].pageY;
    this.setData({
      sy: sy,
    });
  },
  touchMove(e) {
    this.setData({
      endy: e.touches[0].pageY,
    });
  },
  touchEnd() {
    if (this.data.sy - this.data.endy > 100 && this.data.showIn) {
      this.setData({
        boxHeight: "",
        xqBoxShow: true,
        showIn: false,
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (option) {
    wx.showShareMenu({
      withShareTicket: false,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    //防止小程序自动登录后无法立刻获取最新同步状态，导致提示绑定手机
    // if (wx.getStorageSync('wx_token')) {
    //   this.getpet()
    // }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function (e) {
    try {
      if (this.data.goods_type == "goods") {
        this.cGoods.reachBottom();
      } else if (this.data.goods_type == "supplierGoods") {
        this.supplierGoods.reachBottom();
      } else if (this.data.goods_type == "hotelGoods") {
        this.hotelGoods.reachBottom();
      }
    } catch (e) {
      //TODO handle the exception
    }
    this.setData({
      showIn: true,
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareTimeline() {
    var value = wx.getStorageSync("yz_uid");
    let shop_id = wx.getStorageSync("setShopId");
    let img = wx.getStorageSync("GoddsShareImg");
    var mid = "";
    if (value) {
      mid = value;
    }
    if (this.data.goods_type == "group_goods") {
      let _url = this.data.store_id && this.data.store_id != 0 ? `id=${this.data.goods_id}/${this.data.store_id}&mid=${mid}&name=group` : `id=${this.data.goods_id}&mid=${mid}&name=group`;
      return {
        title: this.data.title,
        query: _url,
        imageUrl: img ? img : "",
      };
    } else if (this.data.goods_type == "zhpGroup") {
      return {
        title: this.data.title ? this.data.title : "",
        query: "id=" + this.data.goods_id + "&mid=" + mid + "&name=" + this.data.goods_type,
        imageUrl: img ? img : "",
      };
    } else if (this.data.goods_type == "groupBuy" || this.data.goods_type == "grabGroup") {
      return {
        title: this.data.title ? this.data.title : "",
        path: "id=" + this.data.goods_id + "&mid=" + mid + "&name=" + this.data.goods_type,
      };
    }else {
      return {
        title: this.data.title,
        query: `id=${this.data.goods_id}&mid=${mid}&shop_id=${shop_id}`,
      };
    }
  },
  onShareAppMessage: function (res) {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    let shop_id = wx.getStorageSync("setShopId");
    let img = wx.getStorageSync("GoddsShareImg");

    let shareConfig = {
      title: this.data.title ? this.data.title : "",
      path: "/packageA/detail_v2/detail_v2?id=" + this.data.goods_id + "&mid=" + mid + "&shop_id=" + shop_id,
      imageUrl: img ? img : "",
    };

    if (this.data.goods_type == "group_goods") {
      let store_ids = null;
      if (this.data.store_id && this.data.store_id != 0 && this.data.store_id != "undefined") {
        store_ids = "/" + this.data.store_id;
      }
      if (this.data.goods_id != 0) {
        shareConfig.path = "/packageA/detail_v2/detail_v2?id=" + this.data.goods_id + "&mid=" + mid + "&name=group";
      } else {
        shareConfig.path = "/packageA/detail_v2/detail_v2?id=0" + store_ids + "fight_groups=" + this.data.fight_groups + "&mid=" + mid + "&name=group";
      }
    }
    let urlHasType = ['groupBuy','grabGroup','retailGood','starGroup','zhpGroup'];
    if (urlHasType.includes(this.data.goods_type)) {
      shareConfig.path = "/packageA/detail_v2/detail_v2?id=" + this.data.goods_id + "&mid=" + mid + "&name=" + this.data.goods_type;
    }

    if (this.data.goods_type == "starGroup") {
      let json = {};
      json.path = shareConfig.path;
      if (res.from == "button") {
        json.title = res.target.dataset.name;
        json.thumb = res.target.dataset.thumb;
        let id = res.target.dataset.id;
        let type = res.target.dataset.type;
        if (type && type == "startGroupDetail") {
          json.path = "/packageH/starMusic/starMusicGroupDetails/starMusicGroupDetails?mid=" + mid + "&id=" + id;
        }
      }
      return json;
    } else if (this.data.goods_type == "retailGood") {
      shareConfig.path = shareConfig.path + "&md=" + this.options.md;
    }
    return {
      title: shareConfig.title,
      path: shareConfig.path,
      imageUrl: shareConfig.imgUrl
    };
  },
  onPageScroll(e) {
    let scrollTop = e.scrollTop;
    if (scrollTop > 35) {
      if (!this.data.hoet) {
        this.setData({
          hoet: true,
        });
      }
    } else {
      if (this.data.hoet) {
        this.setData({
          hoet: false,
        });
      }
    }
    this.setData({
      datop: scrollTop,
    });
  },
  // 初始化数据
  _datainit() {
    this.setData({
      /*商品类型*/
      goods_type: "",
      /*商品id*/
      goods_id: "",
      /*商品数据*/
      goods_info: {},
      /*商品数据json字符串*/
      goods_info_str: "",
      // 智能柜标示
      mark: "",
      loginshow: false
    });
  },
  // 获取数据
  _getData: function () {
    let that = this;
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    let json = {
      id: Number(this.data.goods_id),
      mark: this.data.mark,
      mark_id: this.data.mark_id,
      url: "",
    };
    if(this.data.category_option_id){
      json.category_option_id = this.data.category_option_id;
    }
    app._postNetWork({
      showToastIn: false,
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let _data = res.data;

          if (res.data.goods_type == "cps_brand") {
            let _id = (res.data.plugin.aggregation_cps_brand_goods && res.data.plugin.aggregation_cps_brand_goods.id) || 0; //cps品牌券第三方id
            wx.redirectTo({url: '/packageH/cpsDetail/cpsDetail?id=' + _id })
            return;
          }
          this.setData({
            prop_goods_info: res.data,
            title: _data.get_goods.title,
          });
          if (_data.plugin && _data.plugin.customer_development ) {
            this.setData({
              is_toker: true,
            });
          }
          if (_data.goods_type) {
            this.setData({
              goods_type: _data.goods_type,
            });
          }
          if (this.data.goods_type == "goods") {
            this.cGoods = this.selectComponent("#cGoods");
          } else if (this.data.goods_type == "supplierGoods") {
            this.supplierGoods = this.selectComponent("#supplierGoods");
          } else if (this.data.goods_type == "hotelGoods") {
            this.hotelGoods = this.selectComponent("#hotelGoods");
          }
        } else {
          if (res.msg == "该商家已过期,去看看其他的吧") {
            this.setData({
              prop_goods_info: {},
            });
          } else {
            wx.showModal({
              title: "提示",
              content: res.msg,
              showCancel: false,
              success(resData) {
                if (resData.confirm) {
                  wx.navigateBack({
                    fail() {
                      wx.reLaunch({
                        url: "/packageG/index/index",
                      });
                    },
                  });
                }
              },
            });
          }
        }
        wx.hideLoading();
      },
      fail: function (res) {},
    });
  },
  firstlogin() {
    // 选择模板2不用登录
    let firstlogin = false;
    try {
      var is_value = wx.getStorageSync("yz_basic_info");
      if (is_value) {
        if (is_value.home.item.ViewSet.goods.code == "goods02") {
          this.setData({
            loginshow: false,
          });
          firstlogin = false;
        }
      } else {
        var value = wx.getStorageSync("wx_token");
        if (value) {
          // Do something with return value
          this.setData({
            loginshow: false,
          });
          firstlogin = false;
        } else {
          this.setData({
            loginshow: true,
          });
          firstlogin = true;
        }
      }
    } catch (err) {
      // Do something when catch error
    }
    return firstlogin;
  },
  gotologin() {
    app.seyzredirect(); // 保存当前链接
    wx.navigateTo({
      url: "/pages/login/login",
    });
  },
  goLiveBtn() {
    wx.navigateBack({
      delta: 1,
    });
  },
  // 获取数据
  getRetailGoods: function () {
    let urlStr = app.getNetAddresss("plugin.new-retail.frontend.index.goodsDetail");
    app._postNetWork({
      showToastIn: false,
      url: urlStr,
      data: {
        goods_id: this.data.goods_id,
        is_retail_goods: this.options.md
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let _data = res.data.goods;
          this.setData({
            prop_goods_info: _data,
            goods_type: "retailGood"
          });
        } else {
          if (res.msg == "该商家已过期,去看看其他的吧") {
            this.setData({
              prop_goods_info: {},
            });
          } else {
            wx.showModal({
              title: "提示",
              content: res.msg,
              showCancel: false,
              success(resData) {
                if (resData.confirm) {
                  wx.navigateBack({
                    fail() {
                      wx.reLaunch({
                        url: "/packageG/index/index",
                      });
                    },
                  });
                }
              },
            });
          }
        }
        wx.hideLoading();
      },
      fail: function (res) {},
    });
  },
});
