// packageF/goods-packge/index.js
let app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pid: 0,
    scrollArr: [],
    package_id:null,
    isScroll: false,
    order_active: 0,
    total: 0,
    title: "",
    share_title: "",
    share_thumb: "",
    share_desc: "",
    description_title: "",
    description_thumb: "",
    description_desc: "",
    order_list: [],
    checkAll: false,
    carousels: [],
    on_sale_price: 0,
    end_time:0,
    end_time_obj:{},
    time_over:false,//倒计时结束
    isDiscount:false,//是否优惠价格
    other_packages:[],
    loadingHidden:false
  },
  getTotal() {
    // 获取商品列表的高度
    let arr = this.data.carousels.length > 0 ? [260] : [60];
    arr[0] += this.data.time_over?80:0;  //倒计时是否显示，显示就加
    let query = wx.createSelectorQuery();
    let bool = false;
    query.select(".info").boundingClientRect(res => {
      if (!bool) {
        arr[0] += res.height;
        bool = true;
      }
     
    }).exec();
   
    query.selectAll(".list-item").boundingClientRect((res) => {
      res.forEach((item, i) => {
        arr[i + 1] = arr[i] + item.height + 10;
      });
    }).exec();
    this.setData({ scrollArr: arr });
  },
  count_down({detail:{days,hours,seconds,minutes}}){
    //倒计时时间'
    let end_time_obj = {
      days,
      hours:hours>=10?hours:"0" + hours,
      seconds:seconds>=10?seconds:"0" + seconds,
      minutes:minutes>=10?minutes:"0" + minutes
    }
    this.setData({end_time_obj});
  },
  finish(){
    //倒计时结束
    this.setData({time_over:false});
    this.totalPrice();//重新计算价格
  },
  onPageScroll({ scrollTop }) {
    if (!this.data.isScroll) {
      // 滚动条事件，判断是否是点击触发的滚动条事件，不是的话就执行
      this.data.scrollArr.forEach((res, i) => {
        if (scrollTop > res - 10 && scrollTop < res + 10) {
          this.setData({ order_active: i });
        } else if (scrollTop < this.data.scrollArr[i + 1] - 100 && scrollTop > res) {
          this.setData({ order_active: i });
        }
      });
    }

  },
  link({ currentTarget }) {
    // 点击轮播图跳转
    let url = currentTarget.dataset.item.carousel_link;
    wx.navigateTo({ url });
  },
  change({ detail }) {
    this.setData({ isScroll: true });
    let scrollTop = this.data.scrollArr[detail.index];
    wx.pageScrollTo({
      scrollTop,
      duration: 300
    });
    setTimeout(() => {
      this.setData({ isScroll: false });
    }, 330);
  },
  settlement() {
    let _cart_ids = [];
    let json = {goods_list:[],package_id:this.data.package_id};
    let {order_list} = this.data;
    for (let i = 0; i < order_list.length; i++) {
      let item = order_list[i];
      for (let j = 0; j < item.goods_list.length; j++) {
        let items =  item.goods_list[j];
        if (items.check) {
          let len = 0;
          items.check_spe.forEach(r=>{
            len+=r>=0?1:0;
          });
          if (len!=items.has_many_specs.length) {
            app.tips(`请选择商品规格`);
            // app.tips(`商品：${items.title}规格属性未选择`);
            return false;
          }
          _cart_ids.push(items.id);
          json.goods_list.push({
            goods_id:items.id,total:items.count,option_id:items.spe_name||''
          });
        }
      }
    }
    if (_cart_ids.length<=0) return app.tips(`请选择结算商品`);

    wx.navigateTo({
      url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=packagBuy&cart_ids='+JSON.stringify(_cart_ids)+'&packagJson='+JSON.stringify(json) 
    });
  },
  tapSpe({ target }) {
    // 点击商品规格属性
    let { i, c_index, spe_index, spe_item_index } = target.dataset;
    let { order_list } = this.data;
    let obj = order_list[i].goods_list[c_index];
    let spe = obj.has_many_options;
    obj.check_spe[spe_index] = spe_item_index;
    let str = [];
    obj.has_many_specs.forEach((r, i) => {
      let index = obj.check_spe[i];
      if (index >= 0) {
        str.push(r.specitem[index].title);
      }
    });
    str = str.join("+");
    spe.forEach(r => {
      if (r.title == str) {
        obj.price = r.product_price;
        obj.market_price = r.market_price;
        obj.spe_name = r.id;
      }
    });
    this.setData({ order_list });
    this.totalPrice();
  },
  totalPrice() {
    //计算总价格
    let total = 0;
    let order_list = this.data.order_list;
    let len = 0;
    order_list.forEach(item => {
      let isCheck = false;
      item.goods_list.forEach(items => {
        if (items.check) isCheck = true;
        total += items.check ? items.price * items.count : 0;
      });
      if(isCheck) len = len+1;
    });
    if (len==order_list.length&&this.data.time_over) {
      let num = total- Number(this.data.on_sale_price);
      total = num<0?0:num;
      
      this.setData({isDiscount:true});
    }else {
      this.setData({isDiscount:false});
    }
    total = total.toFixed(2);
    this.setData({ total });

  },
  shopChange({ target, detail }) {
    let { i, c_index, count } = target.dataset;
    let { order_list } = this.data;
    let obj = order_list[i].goods_list[c_index];
    if (!count) obj.check = !obj.check;
    else obj.count = detail;
    this.setData({ order_list });
    this.totalPrice();
  },
  gopackgoods({currentTarget:{dataset:{id}}}){
    //其他套餐
    this.setData({loadingHidden:false});
    this.getdata(id);
    wx.pageScrollTo({
      scrollTop:0,
      duration: 0
    });
  },
  getdata(package_id) {
    let url = app.getNetAddresss("plugin.goods-package.frontend.package.package.index");
    
    app._postNetWork({
      showToastIn: false,
      url,
      data: { package_id },
      success: ({ data }) => {
        console.log(data.data.other_packages);
        if (data.result) {
          let { categories, title, description_thumb, description_title, description_desc, carousels, on_sale_price ,end_time,share_title,share_desc,share_thumb,limit_time_status,other_packages} = data.data;
          let order_list = categories.map(res => {
            res.goods_list.map(item => {
              item.count = 1;
              item.check = false;
              item.check_spe = [];
              return item;
            });
            return res;
          });
          end_time = (end_time-parseInt(new Date().getTime() / 1000))*1000;
          this.setData({ title, description_thumb, order_list, description_title, description_desc, carousels, 
            on_sale_price ,end_time,package_id,share_title,share_desc,share_thumb,time_over:limit_time_status==1?true:false,other_packages,loadingHidden:true});
          this.getTotal();
        } else {
          wx.showToast({
            icon: "none",
            title: data.msg,
            duration: 1500,
          });
        }
      }
    });
  },
  todetail({ currentTarget }) {
    //商品详情
    wx.navigateTo({
      url: "/packageA/detail_v2/detail_v2?id=" + currentTarget.dataset.id
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({ pid }) {
    this.setData({
      pid: pid
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getdata(this.data.pid);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      path: "/packageF/packageGoodse/packageGoods?pid=" + this.data.package_id + "&mid=" + mid,
      title: this.data.share_title,
      imageUrl: this.data.share_thumb,
    };
  }
});