// pages/cart/cart_wk/cart_wk.js
var t = getApp(),
  oo = t.globalData.setting,
  os=oo;
var ut=require("../../../../utils/util.js");
var util_pay=require("../../../../utils/pay.js");
var regeneratorRuntime = require('../../../../utils/runtime.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: t.globalData.setting.imghost,
    order_id: 0, //订单ID
    order: null, //订单所有字段
    user_addr: null, //会员地址
    pickup: null,    //门店
    goods: null,      //商品
    /*------------------------*/
    userinfo: null, //获取会员
    /*----------物流选择--------*/
    wu_arr: null,
    index: 0,
    is_express: 0,
    //申请提现的金额
    txmon: 0,
    yuer: 0,
    //判断页面是返回回来的还是 首次进入的
    isclose: 1,

    //配送方式 0=用户自选 1=自提 2=物流
    distr_type: 0,
    //实际配送方式 0物流  1自提
    exp_type: 1,
    //------物流费用------
    exp_price: 0,
    enterAddressPage: 0,  //进入地址页面
    is_no_by: {},
    allpice: 0,
    show_pay_type: 0,

    teamgroup: null,
    submit:1, //默认按钮是灰色
    show_submit:0, //不线上

      dis_config: null,
      bn_use_commission: 0, //是不是使用佣金

      bn_is_order_yh:1,  //是不是订单优惠
      bn_is_post_temp:1, //是不是进行计算包邮模板

    paying:0,  //支付中
    same_ok:1  //同城配送的控制

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //定义第一次进入
    this.data.fir_in=1;

    //清空is_pick_up
    getApp().request.put("/api/weshop/useraddress/updatePickUp", {
      data: { user_id: getApp().globalData.user_id, is_pickup: 0 },
      success: function (s) {
      }
    });

    var th = this;
    this.data.order_id = options.order_id;
    //--初始化--
    getApp().getConfig2(function (e) {
      var json_d = JSON.parse(e.switch_list);

      //测试强行写死，后面一定要删除
      //json_d.pickupway=2;


      th.data.json_d = json_d;
      var is_default_logistics = json_d.is_default_logistics;
      var is_same_city = json_d.is_same_city;
      th.setData({ is_default_logistics: is_default_logistics,is_same_city:is_same_city });

      th.get_wuliu(th.get_info(th.show_page));
    }, 1)

    //判断是不是佣金抵扣
    getApp().is_distribut(this);

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.data.paying=0;

    var th = this;
    //判断是不是第一次进入
    if(this.data.fir_in){
      this.data.fir_in=0;
    }else{
        ut.fy_back('',0);
        util_pay.set_fir();


      var back_url="/packageG/pages/payment/pay_success/pay_success?order_id=" + th.data.order.order_id + "&type=1&card=1";
      //-- 通联的第三方支付的返回优化 --
      ut.is_pay_ok(th.data.wk_pyed,back_url,"/pages/user/order_list/order_list?index=2&tabindex=1",function (){
        if(!th.data.wk_pyed) return false;

        getApp().request.promiseGet("/api/weshop/rechargeServicelist/page",{
          data: { store_id: os.stoid, order_id: th.data.order.order_id}
        }).then(res=>{
          if(ut.ajax_ok(res)){
            var item=res.data.data.pageData[0];
            if(item.pt_status==4 || item.pt_status==5){
              //支付支付，返回首页
              ut.m_toast('支付成功');
              setTimeout(()=>{
                getApp().re_to(back_url);
              },1000)

            }else{
              //支付支付，返回首页
              ut.m_toast('支付失败');
              setTimeout(()=>{
                getApp().re_to("/pages/user/order_list/order_list?index=2&tabindex=1");
              },1000)
            }
          }
        })
      });

    }



    getApp().check_can_share();
    if (th.data.isclose == 0) {
      wx.navigateTo({
        url: "/pages/index/index/index"
      })
    }
    th.getuser_addr(function (addr) {
      if (addr == null || addr == undefined || addr.length == 0) {
        th.setData({ user_addr: null, enterAddressPage: 1,same_ok:1  });
      } else {
        th.setData({
          user_addr: addr, enterAddressPage: 0,same_ok:1
        });
      }
    })

    //--更新默认地址--,看一下是不是跳到地址页面
    // if (!getApp().globalData.is_cart_old) {
    //   this.update_code();
    // } else {
    //   getApp().globalData.is_cart_old = 0;
    // }

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {  getApp().globalData.no_clear=1 },
  //---------------获取物流---------------
  get_wuliu(func) {
    var th = this,
      to = getApp();
    to.getwuliu(function (e) {
      //如果第一个不是开启默认，说明要让用户自己选
      if (!e[0].is_default) {
        th.setData({ is_default_logistics: 0 });
      }

      th.setData({ wu_arr: e })
      typeof func == "function" && func();
    })
  },
  //------获取会员信息-----先获取用户信息，在进行下一步---
  get_info: function (func) {
    var user_id = t.globalData.user_id,
      to = getApp();
    to.auth.get_u(func);
  },

  //------获取会员收货地址-----
  getuser_addr: function (func) {
    var to = getApp(),
      a = to.request;

    a.get("/api/weshop/useraddress/page", {
      data: {
        user_id: to.globalData.user_id,
        store_id: oo.stoid,
        pageSize: 600
      },
      success: function (su) {
        var user_addr = su.data.data.pageData;
        var item = null;
        var def_item = null;
        for (var i = 0; i < user_addr.length; i++) {
          if (user_addr[i]['is_default'] == 1) { def_item = user_addr[i]; }
          if (user_addr[i]['is_pickup'] == 1) { item = user_addr[i]; }
        }

        if (item == null) item = def_item;
        if (item == null) item = user_addr[0];
        if (item == undefined) item = null;
        func(item);
      }
    });

  },

  //----------------展示页面,是再获取用户信息之后--------------
  show_page: function () {
    var th = this,
      to = getApp();
    th.setData({
      userinfo: to.globalData.userInfo,
    });
    //选获取地址
    th.getuser_addr(function (addr) {

      if (addr == null || addr == undefined || addr.length == 0) {
        th.setData({
          enterAddressPage: 1,
        });

      } else {
        th.setData({
          user_addr: addr, enterAddressPage: 0,
        });
      }
      //获取立即购买的商品信息
      th.get_buy_goods(th.data.order_id);
    });
    //获取提现金额
    getApp().request.get("/api/weshop/withdrawals/summoney", {
      data: {
        user_id: to.globalData.user_id,
        store_id: oo.stoid,
        status: 0
      },
      success: function (su) {
        console.log("withdrawals");
        if (su.data.code == 0) {
          var yuer = parseFloat(th.data.userinfo.user_money -
            th.data.userinfo.frozen_money - su.data.data.summoney).toFixed(2);
          th.setData({
            txmon: su.data.data.summoney,
            yuer: yuer
          });
        }
      }
    });
  },

  //-----获取商品------
  async get_buy_goods(ord) {
    var order = null,
      order_goods = null,
      goods = null,
      pickup = null,
      distr_type = 0,
      exp_type = 0,
      teamgroup = null,
      teamlist=null,
      th = this;

    //---获取订单---
    await getApp().request.promiseGet("/api/weshop/recharge/list", {
      data:{store_id:oo.stoid,order_id: ord }
    }).then(res => {
       if(res.data.code==0 && res.data.data.length){
         order = res.data.data[0];
       }else{
         wx.showToast({
           title: "订单未找到",
           icon: 'none',
           duration: 2000
         })
       }
    });

    if(!order) return  false;

    //---获取订单从表---
    await getApp().request.promiseGet("/api/weshop/rechargeServicelist/page", {
      data: {
        store_id: oo.stoid,
        order_id: ord
      }
    }).then(res => {
       if(ut.ajax_ok(res)){
         order_goods = res.data.data.pageData[0];
       }
    });

    order.pt_listno=order_goods.pt_listno;
    order.pt_status=order_goods.pt_status;
    order.pt_prom_id=order_goods.prom_id;
    order.pt_tail_money=order_goods.pt_tail_money;
    order.tail_pay_type=order_goods.tail_pay_type;
    order.pickup_id=order_goods.pickup_id;
    order.order_amount=order.account;
    order_goods.goods_num=order_goods.qty;

    //---获取商品---
    await getApp().request.promiseGet("/api/weshop/serviceCard/get/" + oo.stoid + "/" + order_goods.card_id, {}).then(res => {
      goods = res.data.data;
      order.show_img = oo.imghost + goods.img_url;
    });
    //---获取门店---
    await getApp().request.promiseGet("/api/weshop/pickup/get/" + oo.stoid + "/" + order.pickup_id, {}).then(res => {
      pickup = res.data.data;
    });

    //---获取尾款价格---
    await getApp().request.promiseGet("/api/weshop/teamgroup/page", {
      data: { store_id: oo.stoid, team_id: order.pt_prom_id, listno: order.pt_listno }
    }).then(res => {
      teamgroup = res.data.data.pageData[0];
    });

    await getApp().request.promiseGet("/api/weshop/teamlist/get/" + os.stoid + "/" + order.pt_prom_id, {
          data: { }
      }).then(res => {
          if(res.data.code==0) teamlist=res.data.data;
      });


    var act_set=null;
    var url = '/api/weshop/activitylist/getActInfo1/'+os.stoid+'/6/'+order.pt_prom_id;
    await getApp().promiseGet(url, {}).then(res => {
          if(res.data.code==0){
              act_set=res.data.data;
          }
      })


      // if(act_set.is_order_yh){
      //     th.data.bn_is_order_yh=1;
      // }else{
      //     th.data.bn_is_order_yh=0;
      // }
      th.data.bn_is_order_yh=0;
      th.data.bn_is_post_temp=0;

      // if(act_set.is_post_temp){
      //     th.data.bn_is_post_temp=1;
      // }else{
      //     th.data.bn_is_post_temp=0;
      // }

      
    var jsarr = JSON.parse(teamgroup.jt_json);
    var count = teamgroup.jt_ct_num;
    if(teamgroup.is_xuni_ct) count=teamlist.ct_num;

    //要计算尾款的价钱
    var price = 0;
    jsarr.forEach(function (value, index) {
      if (count >= value['rynum']) price = value['price'];
    })
    var tail_money = (price * order_goods.goods_num - order['order_amount']).toFixed(2);

    tail_money = parseFloat(tail_money);
    order.tail_money = tail_money;

    if (!goods) return false;

      if(goods.is_minishop==1 && getApp().is_sp_hao()){

          if(goods.distr_type==1 || pickup.distr_type==1) {
              wx.showToast({
                  title: "视频号仅支持物流",
                  icon: 'none',
                  duration: 2000
              })

              setTimeout(function(){
                  wx.navigateBack({delta: 1})
              },1000)

              return false
          }

          goods.distr_type=2;
          th.setData({show_same_city:0})

      }

      //--判断物流--
      if (goods.distr_type)
        distr_type = goods.distr_type;
      else
        distr_type = pickup.distr_type;


      //-- 如果商品有同城配送的参数的时候,一件代发商品不能显示同城配送按钮 --
      if(goods.is_same_city && th.data.is_same_city && goods.whsle_id<=0){
         await getApp().request.promiseGet("/api/weshop/pickup/get/"+os.stoid+"/"+order.pickup_id, {}).then(res=>{
              if(res.data.code==0){
                  var pk=res.data.data;
                  if(pk && pk.is_same_city){
                      th.setData({show_same_city:1})
                  }
              }
          })
      }

      exp_type = 1;
      order.order_goods = order_goods;

      //-- 计算获得佣金的金额 --
      if (getApp().globalData.userInfo.is_distribut
          && th.data.dis_config && th.data.dis_config.is_yongjin_dk) {
          var fir_num = 0;
          var sec_num = 0;
          var thi_num = 0;
          if (th.data.dis_config.pattern == 1) {
              fir_num = (teamlist.fir_rate || 0) * order_goods.goods_num;
              sec_num = (teamlist.sec_rate || 0) * order_goods.goods_num;
              thi_num = (teamlist.thi_rate || 0) * order_goods.goods_num;
          } else {
              fir_num = parseFloat((teamlist.commission || 0) * order_goods.goods_num * (th.data.dis_config.firstRate || 0) / 100).toFixed(2);
              sec_num = parseFloat((teamlist.commission || 0) * order_goods.goods_num * (th.data.dis_config.secondRate || 0) / 100).toFixed(2);
              thi_num = parseFloat((teamlist.commission || 0) * order_goods.goods_num * (th.data.dis_config.thirdRate || 0) / 100).toFixed(2);
          }
          var c_num = getApp().get_commission(fir_num, sec_num, thi_num, th);
          goods.use_commission = parseFloat(c_num.toFixed(2));

      }

    this.setData({
      order: order,
      distr_type: distr_type,
      pickup: pickup,
      exp_type: exp_type,
      goods: goods,
      teamgroup: teamgroup,
      teamlist: teamlist,
    });

    //--计算价格--
    th.calculatePrice2();
  },


  calculatePrice2: async function () {
    wx.showLoading();
    var th = this;
    th.setData({submit: 1})

    var allpice = th.data.order.order_amount + th.data.order.user_money + th.data.order.tail_money;
    var o_condition = allpice;
    var ord_prom=null;
    var order_prom_amount=0;

    if (th.data.bn_is_order_yh) {
      await getApp().request.promiseGet("/api/weshop/promorder/getOrderPromotion", {
        data: {store_id: os.stoid, orderAmount: o_condition, user_id: getApp().globalData.user_id}
      }).then(res => {
        if (res.data.code == 0) {
          ord_prom = res.data.data;
        }
      })
    }

    th.data.ord_prom=ord_prom;

    //--计算物流--
    if (th.data.exp_type == 0) {
      th.calculate_wuliu();
      return false;
    }else if(th.data.exp_type == 2){
      th.calculate_same_city();
      return false;
    } else {

      var order_prom_id=0;
      if (ord_prom) {
        order_prom_id = ord_prom['id'];
        switch (ord_prom['type']) {
          case 0:
            allpice = Math.round(o_condition * ord_prom['expression']) / 100;//满额打折
            order_prom_amount = (o_condition - order_m).toFixed(2);
            break;
          case 1:
            //-- 如果有优惠促销倍减的时候 --
            var bs = 1;
            if (ord_prom.is_bz) {
              bs = Math.floor(o_condition / ord_prom.money);
            }
            allpice = o_condition - bs * ord_prom['expression'];//满额优惠金额
            order_prom_amount = ord_prom['expression'];
            break;
        }
      }


      //--订单优惠的显示--
      var order_prom_txt1 = "formData.order_prom_id";
      var order_prom_txt2 = "formData.order_prom_amount";
      if (order_prom_id > 0) {
        th.setData({[order_prom_txt1]: order_prom_id, [order_prom_txt2]: order_prom_amount})
      } else {
        th.setData({[order_prom_txt1]: 0, [order_prom_txt2]: 0})
      }

      if (th.data.bn_use_commission) {
        allpice -= th.data.goods.use_commission;
      }


      allpice = allpice.toFixed(2);

      th.setData({exp_price: 0, allpice: allpice, submit: 0, show_submit: 1})
      wx.hideLoading();
    }
  },

  //--图片失败，默认图片--
  bind_bnerr: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errObj = {};
    _errObj[_errImg] = this.data.imgUrl + "/miniapp/images/del/logo.jpg";
    this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;
  },

  //-------------------获取物流---------------
  get_wuliu(func) {
    var th = this, to = getApp();
    to.getwuliu(function (e) {
      th.setData({
        wu_arr: e
      })
      typeof func == "function" && func();
    })
  },

  //--------点击选择----------
  set_wuliu: function (e) {
    var type = e.currentTarget.dataset.type, th = this;
    this.setData({
      exp_type: type,same_ok:1
    });
    //--计算物流的值--
    if (type == 0) {
      th.calculate_wuliu();
    } else if(type==1){
      var allpice = parseFloat(th.data.order.order_amount)
        + parseFloat(th.data.order.user_money)
        + parseFloat(th.data.order.tail_money);
      allpice = allpice.toFixed(2);
      this.setData({
        allpice: allpice, exp_price: 0,show_submit:1,submit:0
      });
    }else{
        th.calculate_same_city();
    }
  },

  //关闭支付
  close_show_pay: function () {
    this.setData({ show_pay_type: 0 });
  },

  //--弹起支付框--
  to_pay() {
    //如果有再计算价格的过程中，不能提交订单
    if(this.data.submit){ return false}
    if(!this.data.same_ok){ return false}
    this.set_pay_type(1);
  },

  //选择支付方式,服务卡项固定微信支付
  set_pay_type: function (e) {
    if(this.data.paying) return false;
    this.data.paying=1;
    this.to_pay_type(0);
  },

  //--立即支付--
  to_pay_type: function (ind) {
    var th = this;


    th.data.exp_type=parseInt(th.data.exp_type+'');
    //---支付参数--
    var dd = {
      order_sn: th.data.order.order_sn,
      order_id: th.data.order.order_id,
      store_id: oo.stoid,
      exp_type: th.data.exp_type,
      user_id: t.globalData.user_id,
      listno: th.data.order.pt_listno,
      prom_id: th.data.order.pt_prom_id,
      tail_pay_type: ind,//0微信支付 1余额支付
    };

    if(getApp().globalData.scene){
      dd.scene=getApp().globalData.scene;
    }

    if(th.data.bn_use_commission){
        dd.use_commission=th.data.goods.use_commission;
    }

    if(th.data.bn_use_commission){
      dd.use_commission=th.data.goods.use_commission;
    }

    //--判断有没有优惠活动--
    if (th.data.formData.order_prom_amount > 0) {
      var order_prom_list = {};
      order_prom_list.order_prom_id = th.data.formData.order_prom_id;
      order_prom_list.order_prom_amount = th.data.formData.order_prom_amount;
      dd.order_prom_list = order_prom_list;
    }

    var arr = [];
    arr.push(dd);
    //console.log(JSON.stringify(arr));

    getApp().request.promisePost("/api/weshop/order/pay/payTuanWkCard", {
      data: arr,is_json:1,is_normal:1
    }).then(t => {

        //---用微信支付---
        if (dd.tail_pay_type == 0) {

          if (t.data.code != 0) {
              getApp().my_warnning(t.data.msg, 1, th);
              th.data.paying=0;
              return false;
          }

          th.data.wk_pyed=1;
          util_pay.pay_data(t,function (){
                var allmoney = th.data.allpice;
                th.jumpPaymentPage(th.data.order.order_id, allmoney);
          },function (){
                th.data.paying=0;
                //getApp().my_warnning("支付失败", 0, th);
          })

        } else {
          if (t.data.code == 0) {
            //---用余额支付---
            // getApp().my_warnning("支付成功", 1, th);
						wx.showToast({
						  title: '支付成功',
						  icon: 'success',
						  duration: 2000
						});
            setTimeout(function () {
              th.setData({ isclose: 0 });
              th.data.paying=0;
              wx.redirectTo({
                url: "/pages/user/order_list/order_list?index=1"
              })
            }, 1000)
          } else {

             th.data.paying=0;
             getApp().my_warnning(t.data.msg, 1, th);
          }
        }

    }).catch(function(err) {
      th.data.paying=0;
      wx.hideLoading();
    })

  },

  //检查区域是不是包邮
  check_area: function (arr) {
    var user_addr = this.data.user_addr;
    if (!user_addr) return 0;
    for (var i in arr) {
      var item = arr[i];
      if (user_addr.twon == item || user_addr.district == item
        || user_addr.city == item || user_addr.province == item) {
        return 0;
      }
    }
    return 1;
  },

  //检查立即购买的商品是不是不包邮
  check_good: function (arr, goods_id) {
    if (!goods_id) goods_id = this.data.goods.goods_id;
    for (var i in arr) {
      var item = arr[i];
      if (goods_id == item) return 0;
    }
    return 1;
  },
  check_by_area: function (region_list) {
    var arr = region_list.split(",");
    var check = this.check_area(arr);
    return !check;
  },
  check_by_goods: function (goods_list, goods_id) {
    var arr = goods_list.split(",");
    var check = this.check_good(arr, goods_id);
    return !check;
  },

  //------------循环获取config-----------
  get_wuliu_config: function (region_id, code, rs) {
    var item = null, rslist = rs.pageData;
    for (var i = 0; i < rslist.length; i++) {
      if (rslist[i].code == code && rslist[i].region_id == region_id) { item = rslist[i]; }
    }
    return item;
  },
  //-------循环获取config,code default-------
  get_wuliu_default: function (code, rs) {
    var item = null, rslist = rs.pageData;
    for (var i = 0; i < rslist.length; i++) {
      if (rslist[i].shipping_code == code && rslist[i].is_default == 1) { item = rslist[i]; }
    }
    return item;
  },


  //------支付成功页面--------
  jumpPaymentPage: function (order_id, order_amount) {
    wx.setStorageSync("order:order_list:update", !0), wx.redirectTo({
      url: "/packageG/pages/payment/pay_success/pay_success?order_id=" + order_id + "&type=1&card=1",
    });
  },

  //------调起支付框--------
  weixinPay: function (n, success, fail) {
    if (!n) return false;
    var th = this;

      getApp().globalData.no_clear=1;

    wx.requestPayment({
      timeStamp: String(n.timeStamp),
      nonceStr: n.nonceStr,
      package: n.packageValue,
      signType: n.signType,
      paySign: n.paySign,
      success: function (n) {
        // console.log(n), getApp().showSuccess("支付成功！");
				wx.showToast({
				  title: '支付成功',
				  icon: 'success',
				  duration: 2000
				});
        "function" == typeof success && success();
      },
      fail: function (n) {
        console.log(n), "requestPayment:fail" == n.errMsg ? getApp().my_warnning("支付失败", 0, th) : "requestPayment:fail cancel" == n.errMsg ? getApp().my_warnning("您已取消支付", 0, th) : getApp().my_warnning("支付失败：" + n.errMsg.substr("requestPayment:fail ".length), 0, th),
          "function" == typeof fail && fail();
      }
    });
  },


  //使用
  set_bn_commission:function(){
      var th = this;
      th.setData({bn_use_commission: !th.data.bn_use_commission});
      th.calculatePrice2();
  }

})