const app = getApp();
let self = null;
var t = function (t) {
  return t && t.__esModule ? t : {
    default: t
  };
}(require("../../../utils/LoadMore.js")),
  e = getApp(),
  os = e.globalData.setting,
  oo = e.globalData,
  r = e.request,
  rq = r,
  a = require("../../../utils/common.js"),
  s = new t.default();
var regeneratorRuntime = require('../../../utils/runtime.js');
var ut = require('../../../utils/util.js');
var t = require("../../../utils/pay.js");
var t_pay = require("../../../utils/pay2.js");



Page({
  data: {
    url: e.globalData.setting.url,
    resourceUrl: e.globalData.setting.imghost,
    iurl: e.globalData.setting.imghost,
    categories: [{
      name: "全部",
      id: 0
    }, {
      name: "待付款",
      id: 1
    }, {
      name: "待发货",
      id: 2
    }, {
      name: "待收货",
      id: 3
    }, {
      name: "待评价",
      id: 4
    }],
    tab_serviceCard: [{
      name: "全部",
      id: 0,
    }, {
      name: "待付款",
      id: 1,
    }, {
      name: "待评价",
      id: 2,
    }],
    activeCategoryId: 0,
    orderList: null,
    currentPage: 1,
    //已经读取过接口
    is_get: 0,
    conf: null,
    iscodeall: null,
    sales_rules: 1,         //默认是显示线上库存

    //会员的等级价位
    card_field: null,

    back_goods_arr: null,   //返回商品的列表
    currentIndex: 0,
    tabIndex: 0,

    startDate: '',
    endDate: '',
    list2: [],
    currentPage2: 1,
    currentDate: '',
    total: 0, //读取时段内记录数量
    is_no_data2: 0,
    is_no_more2: 0,

    cardList: [],
    // 搜索内容
    searchContent: '',

    ser_paying:0,
    have_get_nor:0,  //看一下普通订单有没有获取
  },
  onLoad: function (t) {

    self = this;
    // 设置日期选择器的结束时间为当前日期
    var now = new Date();
    var nowDate = now.getFullYear() + '-' + this.check_is_big(now.getMonth() + 1)  + '-' + this.check_is_big(now.getDate());
    var date = new Date(now.getTime() - 7 * 24 * 3600 * 1000);
    var startDate = date.getFullYear() + '-' + this.check_is_big(date.getMonth() + 1) + '-' + this.check_is_big(date.getDate());

    if (t.index) {
      if(!t.tabindex) t.tabindex=0;
      this.setData({
        currentIndex: t.index,
        tabIndex: t.tabindex,
      });
      //this.clickTab();
    };



    this.setData({
      currentDate: this.currentDate(),
      startDate: startDate,
      endDate: nowDate,
    });


    var th = this;
    if (t.type != undefined) this.setData({
      activeCategoryId: t.type
    });
    s.init(this, "", "orderList");

    //先判断有没有系统缓存的信息
    this.check_user_storage(()=>{
        if(!getApp().globalData.user_id){
          th.setData({no_user:1 })
          getApp().goto('/packageE/pages/togoin/togoin')
          return false;
        }
    })


  },


  //判断是不是大于10补0
  check_is_big(num){
    if(num<10) num='0'+num;
    return num;
  }, 

  onShow: function () {
    wx.showLoading();
    var th=this;
    th.setData({
      cardList:[],
      list2:[]
    });
    //-- 读取会员的信息先 --，再app.js中有
    this.check_user_storage(()=> {
      //在界面显示
      if(!getApp().globalData.user_id){
          wx.hideLoading();
      }else{
        th.setData({no_user:0})
      }


      ut.fy_back('', 0)
      th.setData({paying: 0});
      th.setData({ ser_paying: 0 });

      t_pay.set_fir();
      t.set_fir();

      //---查看会员的等级价---
      getApp().getConfig2(function (e) {


        th.setData({conf: e, sales_rules: e.sales_rules});
        //--- 看后台是不是有开通等级卡 ---
        if (e.switch_list) {
          var s_list = JSON.parse(e.switch_list);
          th.setData({appoint_pick_keyid: s_list.appoint_pick_keyid})

          var user = getApp().globalData.userInfo;
          var is_open_offline = s_list.is_pricing_open;
          //-- 如果后台有开启等级价的功能 --
          if (parseInt(s_list.rank_switch) == 2 && user && user['card_expiredate']) {
            var str = user['card_expiredate'].replace(/-/g, '/');
            var end = new Date(str);
            end = Date.parse(end) / 1000;
            var now = ut.gettimestamp();
            //--- 判断是等级会员，且在有效期范围内 ---
            if (user.card_field && now < end) {
              th.setData({card_field: user.card_field})
            }
          }

          //-- 判断有没有过期 --
          getApp().request.promiseGet("/store/storemoduleendtime/page?store_id=" + os.stoid + "&type=6", {}).then(res => {
            //未购买
            if (res.data.code != 0 || !res.data.data || !res.data.data.pageData || !res.data.data.pageData.length) {
              is_open_offline = 0;
            } else {
              //已经过期
              var item = res.data.data.pageData[0];
              if (item.end_time < ut.gettimestamp()) {
                is_open_offline = 0;
              }
            }

            th.data.is_open_offline = is_open_offline;
          })
        }
      }, 1)

      th.resetData();
      if(th.data.currentIndex>0){
        th.clickTab();
      }else{
        th.requestOrderList(th.data.activeCategoryId);
      }

    },1500);
  },

  onHide(){
    this.setData({no_user:0 })
  },

  //判断有没有会员缓存
  check_user_storage(func){
      var user = wx.getStorageSync("userinfo");
      if(!user){
         func();
      }else{
          setTimeout(()=>{
            func();
          },1200);
      }
  },

  changeTab: function (t) {
    if (this.data.activeCategoryId == t.currentTarget.id) return false;
    this.resetData(), this.requestOrderList(t.currentTarget.id);
  },
  resetData: function () {
    s.resetConfig(), this.data.orderList = null, this.data.currentPage = 1;
  },


  /*---------获取订单列表--------*/
  requestOrderList: function (t) {
    if(!getApp().globalData.user_id){
       return false;
    }
    var rd = Math.random() * 100;
    var e = this, th = e, r = e.data.url + "/api/weshop/order/page?rd=" + rd, a = "";
    switch (t) {
      case "1":
        r += "&wait_status=0";
        break;
      case "2":
        r += "&wait_status=1";
        break;
      case "3":
        r += "&wait_status=2";
        break;
      case "4":
        r += "&order_status=2";
        break;
    }
    r += "&isdel=0";
    if (this.data.searchContent) {
      r += "&keyWord=" + this.data.searchContent;
    }
    this.setData({ activeCategoryId: t });
    r = r + "&page=" + e.data.currentPage;
    s.request(r, function (t) {

      th.data.have_get_nor=1;

      if(t.data.data.page*t.data.data.pageSize>=t.data.data.total){
        th.setData({ iscodeall: 1 });
      }

      var data = e.data.orderList;

      //-- 如果有值的时候 --
      if(data && data.length){
         data.forEach(async function (item, ind) {
          var tt = null;
          await getApp().request.promiseGet('/api/weshop/ordergoods/list', {
            data: { order_id: item.order_id, store_id: os.stoid, pageSize: 600 },
          }).then(res => {
            tt = res;
          })
          var glist = tt.data.data.pageData;
          for (var i in glist) {
            if (glist[i].is_gift) {
              data[ind].is_prom = 1;
            }
          }

          data[ind]['ord_url'] = '/packageG/pages/user/order_detail/order_detail';
          //-- 如果是优惠活动 --
          if (glist[0].prom_type == 8) {
            await getApp().request.promiseGet('/api/weshop/order/orderPresell/get/' + os.stoid + '/' + item.order_id, {
            }).then(res => {
              if (res.data.code == 0) {
                data[ind]['presell'] = res.data.data;
                data[ind]['ord_url'] = '/packageC/pages/presell/cart/cart';
              }
            })
          }
          // 如果是幸运购活动
          if (glist[0].prom_type == 9) {
            await getApp().request.promiseGet('/api/weshop/prom/luckyOrder/list', {
              data: {
                store_id: os.stoid,
                user_id: oo.user_id,
                order_id: item.order_id,
              }
            }).then(res => {
              if (res.data.code == 0) {
                // console.log('luckyGo+++++++++>>>', res.data.data);
                // data[ind]['team_status'] = res.data.data[0]['team_status'];
                if (res.data.data[0] && res.data.data[0]['team_status']) {
                  data[ind]['team_status'] = res.data.data[0]['team_status'];
                } else {
                  data[ind]['team_status'] = 0;
                };

                // data[ind]['ord_url']='/packageC/pages/presell/cart/cart';
              }
            })
          }
          //------------对比一下有没有退款记录------------
          await getApp().request.promiseGet("/api/weshop/order/returngoods/page", {
            data: {
              order_id: item.order_id, store_id: os.stoid,
              user_id: oo.user_id, pageSize: 20
            }
          }).then(rs => {
            var ttd = rs;
            //--看一下订单的总数量--
            var gtype_num = tt.data.data.total;
            if (ttd.data.data.pageData == undefined) return false;
            var goodslist = tt.data.data.pageData;

            //----没有相关的退款记录----
            if (ttd.data.data.total == 0) {
              data[ind]['is_all_return'] = 0;
              goodslist.forEach(function (ee, ii) {
                if (data[ind]['order_status'] == 1 && data[ind]['pay_status'] == 1 && gtype_num > 1) {
                  item.goodslist = goodslist;
                  if (th.check_for_return_btn(item)) {
                    goodslist[ii]['return_btn'] = 1;
                  }
                }

              });
            } else {
              //--------整单退--------
              if (ttd.data.data.pageData[0]['goods_id_list'] != null
                  && ttd.data.data.pageData[0]['goods_id_list'] != '') {
                var eea = ttd.data.data.pageData[0];
                //1.退款正在进行中，
                //2.退款被拒绝就要显示可以退款
                //3.退款已经完成
                data[ind]['is_all_return'] = 1;
                data[ind]['is_all_return_status'] = ttd.data.data.pageData[0].status;

                if (data[ind]['order_status'] == 1 && data[ind]['pay_status'] == 1) {
                  switch (eea.status) {
                    case 0:
                    case 1:
                      data[ind]['return_btn'] = 2;
                      break;
                    case 2:
                      data[ind]['return_btn'] = 4;
                      break;
                    case 3:
                      data[ind]['return_btn'] = 3;
                      break;
                    default:
                      data[ind]['return_btn'] = 0;
                  }
                }
              } else {
                //1.退款正在进行中，
                //2.退款被拒绝就要显示可以退款
                //3.退款已经完成
                data[ind]['is_all_return'] = 0;
                var rt_ok_num = 0;
                //if(data[ind]['order_status'] == 1 && data[ind]['pay_status'] == 1) {
                goodslist.forEach(function (eeb, iii) {
                  if (data[ind]['order_status'] == 1 && data[ind]['pay_status'] == 1)
                    goodslist[iii]['return_btn'] = 1; //申请退款
                  ttd.data.data.pageData.forEach(function (eea, ii) {
                    var st = eea.status;
                    if (eea.goods_id == eeb.goods_id) {
                      switch (eea.status) {
                        case 0:
                        case 1://退款处理中
                          data[ind]['has_rt'] = 1; //有部分退
                          goodslist[iii]['return_btn'] = 2;
                          break;
                        case 2://退款完成
                          data[ind]['has_rt'] = 1; //有部分退
                          goodslist[iii]['return_btn'] = 4;
                          rt_ok_num++;
                          break;
                        case 3://已拒绝，重新退款
                          goodslist[iii]['return_btn'] = 3;
                          break;
                        default:
                          if (data[ind]['order_status'] == 1 && data[ind]['pay_status'] == 1)
                            goodslist[iii]['return_btn'] = 1; //申请退款
                      }
                      return;
                    }
                  });
                });
                //}
              }
            }

            //--如果是全部退款，也就可以删除--
            if (rt_ok_num == goodslist.length) {
              data[ind]['is_all_return_status'] = 2;
            }


            data[ind]['order_goods'] = goodslist;
            var g_num = 0;
            goodslist.forEach(function (ee, ii) {
              if (ee.return_btn != 4)
                g_num += ee.goods_num;
            });
            data[ind]['g_num'] = g_num;
          })


          data[ind].use_commission = 0;
          //-- 如果有数据的话 --
          await getApp().request.promiseGet("/api/weshop/orderMore/get/" + os.stoid + "/" + item.order_sn, {

          }).then(res => {
            if (res.data.code == 0 && res.data.data) {
              data[ind].use_commission = res.data.data.use_commission;
              data[ind].pre_cut = res.data.data.pre_cut; //是否使用预存，如果是使用预存不能单品退，只能整单退
              data[ind].pre_json = res.data.data.pre_json; //是否使用预存，如果是使用预存不能单品退，只能整单退
              data[ind].is_user_no_yhcx = res.data.data.is_user_no_yhcx;  //判断订单是不是优惠促销不参与
            }
          })


          th.setData({ orderList: data, });

          wx.hideLoading();

        });
         e.data.currentPage++, wx.stopPullDownRefresh();
      }
      else {
        //直接关闭加载中的动画
        wx.hideLoading();
      }

      th.setData({ is_get: 1 });




    }, null, { store_id: os.stoid, user_id: oo.user_id });
  },

  //滑倒底部
  onReachBottom: function () {



    if (this.data.currentIndex == 0) {
      if (s.data.goodsLoadFinishFlag) {
        this.setData({
          iscodeall: 1
        })
      }

      if(!this.data.iscodeall){
        wx.showLoading();
        s.canloadMore() && this.requestOrderList(this.data.activeCategoryId);
      }


    } else {
      if (this.data.currentIndex == 1) {
        this.request_list({
          store_id: os.stoid,
          user_id: oo.user_id,
          page: this.data.currentPage2,
          BeginDate: this.data.startDate,
          EndDate: this.data.endDate
        });
      } else { // 卡项订单
        this.request_list({
          store_id: os.stoid,
          user_id: oo.user_id,
          page: this.data.currentPage2,
        });
      }

    }
  },

  onPullDownRefresh: function (t) {
    // sty取消
    // this.resetData(), this.requestOrderList(this.data.activeCategoryId);
  },

  /*-----------取消订单-----------*/
  cancelOrder: function (t) {
    var e = this,
      a = t.currentTarget.dataset.id,
      th = this;
    var is_zsorder = parseFloat(t.currentTarget.dataset.zsorder);
    var index = t.currentTarget.dataset.orderindex;
    var order = th.data.orderList[index];
    var is_skill = 0;
    var order_goods = order.order_goods;
    //--判断是不是秒杀--
    order_goods.forEach(function (val, ind) {
      if (val.prom_type == 1) {
        is_skill = 1;
        return false;
      }
    })

    wx.showModal({
      title: "是否取消订单？",
      success: function (t) {
        //如果是秒杀和拼单的商品，取消订单要返回redis,并取消订单
        if (t.confirm) {
          //if(is_skill==1 || is_zsorder>=2){
          getApp().request.post("/api/weshop/order/cancelOrder/" + os.stoid + "/" + a + "/" + getApp().globalData.user_id, {
            data: {},
            success: function (t) {
              if (t.data.code == 0) {
                0 == e.data.activeCategoryId ?
                  (e.resetData(), e.requestOrderList(e.data.activeCategoryId)) : e.deleteOrderData2(a);
              } else {
                getApp().confirmBox(t.data.msg);
              }
            },
          })
        }
      }
    });
  },

  /*-----------确认收货-----------*/
  confirmOrder: function (t) {
    var e = this, a = t.currentTarget.dataset.id;
    var is_zsorder = t.currentTarget.dataset.zsorder;
    var th = this;

    wx.showModal({
      title: "是否确认收货?",
      success: function (t) {
        t.confirm && rq.post("/api/weshop/order/confirmOrder/" + os.stoid + "/" + a + "/" + getApp().globalData.user_id, {
          success: function (e) {
            if (e.data.code == 0) {
              th.deleteOrderData2(a);
              getApp().confirmBox("确认收货成功！");
            }
          }
        })
      }
    });
  },

  //-----删除订单-----
  deleteOrderData: function (t) {
    var th = this;
    var order_id = t.currentTarget.dataset.order_id;
    var index = t.currentTarget.dataset.index;
    var up_data = { order_id: order_id, isdel: 1 };
    var order = th.data.orderList[index];
    if (order.order_status != 6) {
      up_data.order_status = 5;
    }
    wx.showModal({
      title: "是否删除订单？",
      success: function (tt) {
        tt.confirm && rq.put("/api/weshop/order/updatebyId", {
          data: up_data,
          success: function (t) {
            for (var e = 0; e < th.data.orderList.length; e++)
              if (th.data.orderList[e].order_id == order_id) {
                th.data.orderList.splice(e, 1), th.setData({
                  orderList: th.data.orderList
                });
                break;
              }
          }
        })
      }
    });
  },

  //-----删除订单(完成和带评价的)-----
  deleteOrderData_: function (t) {
    var th = this;
    var order_id = t.currentTarget.dataset.order_id;
    var index = t.currentTarget.dataset.index;
    var up_data = { order_id: order_id, isdel: 1 };


    wx.showModal({
      title: "是否删除订单？",
      success: function (tt) {
        tt.confirm && rq.put("/api/weshop/order/updatebyId", {
          data: up_data,
          success: function (t) {
            for (var e = 0; e < th.data.orderList.length; e++)
              if (th.data.orderList[e].order_id == order_id) {
                th.data.orderList.splice(e, 1), th.setData({
                  orderList: th.data.orderList
                });
                break;
              }
          }
        })
      }
    });
  },


  //-----删除订单-----
  deleteSerOrderData: function (t) {
    var th = this;
    var order_id = t.currentTarget.dataset.orderid;
    let order_sn = t.currentTarget.dataset.ordersn;
    var index = t.currentTarget.dataset.index;
    // var up_data={order_id: order_id,isdel:1};
    // var order=th.data.orderList[index];
    // if(order.order_status!=6){
    // 	up_data.order_status=5;
    // }
    wx.showModal({
      title: "是否删除订单？",
      success: function (tt) {
        tt.confirm && rq.put("/api/weshop/recharge/update", {
          data: {
            store_id: os.stoid,
            order_id: order_id,
            order_sn: order_sn,
            order_status: 5,
          },
          success: function (t) {
            let cardList = th.data.cardList
            cardList.splice(index, 1)
            th.setData({
              cardList
            })
            // for (var e = 0; e < th.data.orderList.length; e++)
            //   if (th.data.orderList[e].order_id == order_id) {
            //     th.data.orderList.splice(e, 1), th.setData({
            //       orderList: th.data.orderList
            //     });
            //     break;
            //   }
          }
        })
      }
    });
  },

  deleteOrderData2: function (order_id) {
    var th = this;
    for (var e = 0; e < th.data.orderList.length; e++)
      if (th.data.orderList[e].order_id == order_id) {
        th.data.orderList.splice(e, 1), th.setData({
          orderList: this.data.orderList
        });
        break;
      }
  },

  //---判断是不是有退款-----
  checkReturnGoodsStatus: function (t) {
    var e = t.currentTarget.dataset.recid;
    var oid = t.currentTarget.dataset.oid;
    r.get("/api/weshop/order/returngoods/page", {
      data: {
        goods_id: e,
        order_id: oid,
        store_id: os.stoid
      },
      success: function (t) {
        if (t.data.code == 0) {
          var r = t.data.data.total;
          if (0 == r) return wx.navigateTo({
            url: "/packageF/pages/user/return_goods/return_goods?rec_id=" + e + "&order_id=" + oid,
          });
          //--如果拒绝，就重新申请退款--
          if (t.data.data.pageData[0].status == 3) {
            return wx.navigateTo({
              url: "/packageF/pages/user/return_goods/return_goods?rec_id=" + e + "&order_id=" + oid,
            });
          }

          wx.navigateTo({
            url: "/packageF/pages/user/return_goods_info/return_goods_info?id=" + r
          });
        }
      }
    });
  },

  //-- 预存款判断 --
  async vipadvancesum(keyid,pre_cut,pre_json){
    let pre=JSON.parse(pre_json)
    let listform=[]
    pre.map(item=>{
      let obj={
        advancesum: item.advancesum,
        advanceitemid: item.advanceitemid
      }
      listform.push(obj)
    })
    let res = await getApp().request.promisePost(`/api/weshop/delphiapi/saveErpApi`, {
      data: {
        accdb: getApp().globalData.config.erpid,
        ApiName: 'api.pos.shop.vipadvancesum.list',
        // usercode: "admin",
        vipid: getApp().globalData.userInfo.erpvipid,
        // oddsum: "0",
        // advancesum: cartList.order_amount,
        storageid: keyid,
        listform
      },
      is_json: 1
    })
    return res.data
  },

  /*----------跳转支付-----------*/
  async jumpToCart4(t) {

    if (this.data.paying) return false;
    // this.setData({ paying: 1 });

    var o_index = t.currentTarget.dataset.idx;
    var txt="paying["+o_index+"]";
    this.setData({[txt]:1});
    var e = this.data.orderList[o_index];
    var th = this;
    var order = e;
    var order_goods = e.order_goods;
    var user_id = getApp().globalData.userInfo.user_id;

    
    var wlist = "";
    var the_yh_map={}; //判断那种商品的prom_type为0，正在做的活动是优惠促销

    var _pick=null;
    //获取商品信息，包含线下商品ID，指定门店销售的信息
    var rh=await getApp().request.promiseGet("/api/weshop/pickup/get/"+os.stoid+"/"+order.pickup_id, {});
    if(rh && rh.data.code==0){
      _pick=rh.data.data;
    }

    for (var i in order_goods) {
      var good = order_goods[i];

      //线下取价功能已经关闭或者过期
      if (!th.data.is_open_offline && good.offline_cut > 0) {
        wx.showModal({
          title: '提示',
          content: '线下取价功能已经关闭或者过期！'
        });
        th.setData({ paying: 0 });
        return false;
      }

      //要每件每件的商品进行检查，看有么有超出库存，超出限购
      var good = order_goods[i], goodsbuynum = 0, promgoodsbuynum = 0, gg = null, presellList = null;

      //获取单品的现在的活动状态
      await getApp().request.promiseGet("/api/weshop/goods/get/" + os.stoid + "/" + good.goods_id, {}).then(res => {
        gg = res.data.data;
      })

      //-- 判断门店配送是不是匹配 --
      if(_pick && _pick.distr_type!=0 && gg.distr_type!=0 && _pick.distr_type!= gg.distr_type){
        getApp().confirmBox(gg.goods_name + "配送方式和门店不一致");
        th.setData({ paying: 0 });
        wx.hideLoading();
        return false;
      }

      //-- 要进行判断指定门店的判断优化,先做普通商品 --
      if([0,3,5,7,10].indexOf(parseInt(good.prom_type))>-1 && gg.pick_group_ids && !good.is_gift){
          var idx0=gg.pick_up_lists.findIndex(function (e){
            return e.pickup_id==order.pickup_id;
          })
          if(idx0<0){
            getApp().confirmBox(gg.goods_name + "的门店不可售");
            th.setData({ paying: 0 });
            return false;
          }
      }

      var limit = gg.viplimited;
      var store_count = gg.store_count;
      good.erpwareid = gg.erpwareid;

      //---要获得商品，该用户买了多少件,同步应用---
      await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
        data: {
          store_id: os.stoid,
          user_id: user_id,
          goods_id: good.goods_id,
          prom_type: good.prom_type,
          prom_id: good.prom_id,
          timetype:gg.viplimited_timetype
        },
      }).then(res => {
        var buy_num_data = res.data.data;
        if (buy_num_data.promgoodsbuynum) promgoodsbuynum = buy_num_data.promgoodsbuynum;
        goodsbuynum = buy_num_data.goodsbuynum;
      })

      var buyed_mum2 = goodsbuynum + good.goods_num;
      if (buyed_mum2 > limit && limit > 0  && !good.is_gift) {
        var content = gg.goods_name + '购买数量超出商品限购,请取消订单';
        th.toast(content);
        th.setData({ paying: 0 });
        return false;
      }

      //当是组合优惠的时候
      if (good.prom_type == 7) {
        //如果有组合购
        var isok = 1;
        var url = "/api/weshop/prom/zhbuy/get/" + os.stoid + "/" + good.prom_id + "/" + getApp().globalData.userInfo.user_id;
        let zh_buy_info=null
        await getApp().request.promiseGet(url, {}).then(res => {
          if (res.data.code == 0 && res.data.data) {
            zh_buy_info = res.data.data
            if (res.data.data.is_show != 1) {
              isok = 0;
            }
            //如果活动已经结束
            if (res.data.data.is_end == 1) {
              isok = 0;
            }
            //已经结束
            if (ut.gettimestamp() > res.data.data.end_time) {
              isok = 0;
            }
            //还未开始
            if (ut.gettimestamp() < res.data.data.start_time) {
              isok = 0;
            }


          } else {
            //未找到商品的活动
            isok = 0;
          }

        })
        if (!isok) {
          var content = gg.goods_name + '活动已经结束,请取消订单';
          th.toast(content);
          th.setData({ paying: 0 });
          return false;
        }

         //增加组合购次数判断
        let userbuynum = await th.getUserBuyPromNum(good.prom_id,1)
        
        if (zh_buy_info.buy_limit !=0 && zh_buy_info && userbuynum >= zh_buy_info.buy_limit) {
          var content = gg.goods_name + '超出组合购限购次数,请取消订单';
          th.toast(content);
          th.setData({ paying: 0 });
          return false;
        }
  
        var url1 = "/api/weshop/prom/zhbuyGoods/page";
        var req_data = {
          page: 1,
          pageSize: 1,
          store_id: os.stoid,
          zh_id: good.prom_id,
          goods_id: good.goods_id
        }
        await getApp().request.promiseGet(url1, {
          data: req_data
        }).then(res => {
          if (ut.ajax_ok(res)) {
            var gdlist = res.data.data.pageData[0];
            good.buyqty = gdlist.buyqty;
          }
        })

        var num = good['buyqty'];
        //---- 要计算商品的限购 -----
        if (good['buyqty'] > 0) {
          if (good.goods_num + promgoodsbuynum > good['buyqty']) {
            var content = good['goods_name'] + "超出活动限购\n";
            th.toast(content);
            th.setData({ paying: 0 });
            return false;
          }
        }
      }
      //如果是预售的时候，
      if (good.prom_type == 8) {
        await getApp().request.promiseGet("/api/weshop/order/orderPresell/countBuyGoodsSum", {
          data: { store_id: os.stoid, user_id: user_id, goods_id: good.goods_id, prom_id: good.prom_id },
        }).then(e => {
          if (e.data.code == 0) {
            promgoodsbuynum = e.data.data.sumgoodsnum;
          }
        })

        var presell_id = good.prom_id;
        var url = "/api/weshop/marketing/marketingPresellList/list"
        var rd = {
          store_id: os.stoid,
          presell_id: presell_id,
          goods_id: good.goods_id
        }
        //------获取预售从表----------
        await getApp().request.promiseGet(url, {
          data: rd
        }).then(res => {
          if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
            var arr = res.data.data[0];
            presellList = arr
          }
        })

        if(!presellList){
          var content = good.goods_name + '未找到预售活动,请取消订单';
          th.toast(content);
          th.setData({ paying: 0 });
          return false;
        }


        if (presellList) {
          if (good.goods_num > presellList.presell_sumqty - presellList.buy_goodnum) {
            var content = good.goods_name + '购买数量超出商品库存,请取消订单';
            th.toast(content);
            th.setData({ paying: 0 });
            return false;
          }
          var buyed_mum3 = promgoodsbuynum + good.goods_num;
          if (buyed_mum3 > presellList.vip_butyqty && presellList.vip_butyqty > 0) {
            var content = good.goods_name + '购买数量超出商品限购,请取消订单';
            th.toast(content);
            th.setData({ paying: 0 });
            return false;
          }

          var fres=await getApp().request.promiseGet("/api/weshop/marketing/marketingPresellForm/get/"+os.stoid+"/"+presell_id, {});
          //接口调用成功的时候
          if(fres && fres.data.code==0 && fres.data.data){

            //如果有指定门店的时候
            if(fres.data.data.pick_up_lists){
              var idx0=fres.data.data.pick_up_lists.findIndex(function (e){
                return e.pickup_id==order.pickup_id;
              })
              if(idx0<0){
                getApp().confirmBox(good.goods_name+"预售活动的门店不可售");
                th.setData({ paying: 0 });
                return false;
              }
            }

          }else{
            var content = good.goods_name  + '未找到预售活动,请取消订单';
            th.toast(content);
            th.setData({ paying: 0 });
            return false;
          }
        }
      }
      
      //如果优惠促销和搭配购的时候
      if ((good.prom_type == 3 || good.prom_type == 5 || good.prom_type == 10) && good.is_gift != 1 && good.is_collocation != 1) {
        var p_ok = 1, is_g_prom = 0;
        //只读优化促销和阶梯促销
        await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromListNew1/" + os.stoid + "/" + good.goods_id+"/0/"+user_id, {}).then(res => {
            if (res.data.code == 0) {
              var r_data = res.data.data;
              if (!r_data.collocationPromList && good.prom_type == 5) {
                 var content = good.goods_name + '未找到活动,请取消订单重新购买';
                 th.toast(content)
                 p_ok = 0;
              }

              if (!r_data.promGoodsLists && good.prom_type == 3) {
                var content = good.goods_name + '未找到活动或您无权限参与该活动,请取消订单重新购买';
                th.toast(content);
                p_ok = 0;
              }else if(r_data.promGoodsLists && good.prom_type == 3){
                var fir_act = r_data.promGoodsLists[0];
                //如果是有限购的时候
                if (fir_act.gd_limit_num>0){
                  if(promgoodsbuynum+good.goods_num > fir_act.gd_limit_num){
                    var content = good.goods_name + '超出优惠促销活动商品限购,请取消订单重新购买';
                    th.toast(content)
                    p_ok = 0;
                  }
                }

              }

              if (!r_data.ladderLists && good.prom_type == 10) {
                var content = good.goods_name + '未找到活动,请取消订单重新购买';
                th.toast(content);
                p_ok = 0;
              }



            } else {

              var content = good.goods_name + '未找到活动,请取消订单重新购买'
              th.toast(content);
              p_ok = 0;
            }
          })
        if (!p_ok) {
          th.setData({ paying: 0 });
          return false;
        }
      }

      //-- 商品的普通购买 ，不要进行判断 --
      if ((good.prom_type == 1 || good.prom_type == 2 || good.prom_type == 6 || good.prom_type == 4 || good.prom_type == 8 || good.prom_type == 9)
        && !good.is_gift && !good.is_collocation && !good.is_integral_normal && !good.is_pd_normal) {

      } else {

        //-- 如果是活动的普通购买的时候 --
        if(good.is_pd_normal || good.is_integral_normal){
          gg.prom_type=good.prom_type;
          gg.prom_id=good.prom_id;
        }else {
          //因为商品的prom_type=0,所以商品的实际活动要重新获取
          var url = '/api/weshop/activitylist/listGoodActInfo2New';
          var req_d = {
            "store_id": os.stoid,
            "goods_id": good.goods_id,
            "user_id": user_id,
          }
          await getApp().request.promiseGet(url, {
            data: req_d
          }).then(res => {
            if (res.data.code == 0 && res.data.data) {
              var arr = res.data.data;
              //-- 预热也要计算 --
              var arr2 = arr.filter(function (e) {
                return e.s_time < ut.gettimestamp() || (e.warm_uptime && e.warm_uptime < ut.gettimestamp())
              })
              if (arr2.length == 1) {
                gg.prom_type = arr2[0].prom_type;
                gg.prom_id = arr2[0].act_id;
              } else if (arr2.length > 1) {
                //如果是多活动的时候，要看good参与的活动有没有结束，是不是有效
                var fd = arr2.find(function (e) {
                  return e.prom_type == good.prom_type && e.act_id == good.prom_id
                })
                if (fd) {
                  gg.prom_type = good.prom_type;
                  gg.prom_id = good.prom_id;
                }
              }
            }
          })
        }


        //优惠促销获取取价规则
        if(gg.prom_type==3){
          var prom_pc=null;
          await getApp().request.promiseGet("/api/weshop/promgoods/get/" + os.stoid + "/" + gg.prom_id, {}).then(res => {
            if (res.data.code == 0) { prom_pc = res.data.data; }
          })

          if(prom_pc){
             gg.discount_field=prom_pc.discount_field;
          }
        }

        //阶梯促销获取取价规则
        if(gg.prom_type==10){
          var prom_ld=null;
          //-- 获取阶梯规则 --
          var url1 = "/api/weshop/prom/ladderList/list";
          var req_data = {
            store_id: os.stoid,
            form_id: gg.prom_id,
          }
          await getApp().request.promiseGet(url1, {
            data: req_data
          }).then(rs1 => {
            if (rs1.data.code == 0 && rs1.data.data && rs1.data.data.length ) {
              prom_ld = rs1.data.data[0];
            }
          })

          if(prom_ld){
             gg.discount_field=prom_ld.discount_field;
          }
        }

        if ((gg.prom_type == 1 || gg.prom_type == 2 || gg.prom_type == 4 || gg.prom_type == 6 || gg.prom_type == 8 || gg.prom_type == 9)
          && !good.is_collocation && !good.is_gift && !good.is_integral_normal && !good.is_pd_normal) {
            var prom = null;
            //---如果是活动的时候---
            var prom = null, th = this;
            if (gg.prom_type == 1) {
              await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + gg.prom_id, {}).then(res => {
                if (res.data.code == 0) {
                  prom = res.data.data;
                  prom.price = prom.user_price;
                }
              })
            }
            if (gg.prom_type == 2) {
              await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + gg.goods_id + "/" + gg.prom_id, {}).then(res => {
                if (res.data.code == 0) {
                  prom = res.data.data;
                  prom.price = prom.price;
                }
              })
            }
            if (gg.prom_type == 6) {
              await getApp().request.promiseGet("/api/weshop/teamlist/get/" + os.stoid + "/" + gg.prom_id, {}).then(res => {
                if (res.data.code == 0) {
                  prom = res.data.data;
                }
              })
            }
            if (gg.prom_type == 4) {
              await getApp().request.promiseGet("/api/weshop/integralbuy/pageIntegralBuyGoodsList?stype=1&stypeup=1&timetype=2", {
                data: { store_id: os.stoid, goods_id: gg.goods_id,user_id: getApp().globalData.user_id, }
              }).then(res => {
                if (res.data.code == 0 && res.data.data && res.data.data.pageData) {
                  prom = res.data.data.pageData[0];
                }
              })
            }
            if (prom) {
              var t_now = ut.gettimestamp();
              if (prom.is_end == 0 && prom.start_time < t_now && prom.end_time > t_now ) {
                var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
                th.toast(content);
                th.setData({ paying: 0 });
                return false;
              }
            }

            //-- 幸运购的时候 --
            if(gg.prom_type==8 || gg.prom_type==9){
              var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
              th.toast(content);
              th.setData({ paying: 0 });
              return false;
            }

        }
        else {
            var t_ok = 1;
            //-- 如果是普通购买的时候，此时计算的一定是商品的prom_type==0了,  （组合购在普通购买的时候，就不判断了，因为组合购本身就可以普通购买）---
            if(!good.is_collocation && !good.is_gift && good.is_pd_normal!=2 && gg.prom_type!=7 ){

                  var promgoodsbuynum0=0;
                  //---要获得商品，该用户买了多少件,同步应用---
                  await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
                    data: {
                      store_id: os.stoid,
                      user_id: user_id,
                      goods_id: good.goods_id,
                      prom_type: gg.prom_type,
                      prom_id: gg.prom_id
                    },
                  }).then(res => {
                    var buy_num_data = res.data.data;
                    if (buy_num_data.promgoodsbuynum) promgoodsbuynum = buy_num_data.promgoodsbuynum;
                  })


                  //商品的订单列表的活动类型，和gg参与的类型不一致
                  if(good.prom_type != gg.prom_type && good.prom_id != gg.prom_id){
                      //如果商品有单独的活动的是偶
                      switch (gg.prom_type){
                        case 10:
                            var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
                            th.toast(content);
                            t_ok = 0;
                            break;
                            //-- 优惠促销是有限购的 --
                        case 3:
                          var prom=null;
                          var yh_check=1;


                          //如果有优惠促销的普通购买的时候
                          if(order.is_user_no_yhcx && good.prom_type==0 && order.is_user_no_yhcx!='0' && order.is_user_no_yhcx!='null' ){
                               let obj=JSON.parse(order.is_user_no_yhcx);
                               //obj数组使用find函数快速查找
                               if(obj.find((item)=>{return item.prom_id==gg.prom_id && item.prom_type==3})){
                                  yh_check=0;
                               }                                       
                          } 

                          //判断优惠促销活动的限购
                          if(yh_check){
                              await getApp().request.promiseGet("/api/weshop/promgoods/get/" + os.stoid + "/" + gg.prom_id, {}).then(res => {
                                if (res.data.code == 0) { prom = res.data.data; }
                              })
                              if (prom && prom.limit_num) {
                                var limit_num = prom.limit_num;
                                var user_pre_buynum = await this.getUserBuyPromNum_pre(prom.id)
                                if (limit_num>0 && user_pre_buynum >= limit_num) {
                                  yh_check=0;
                                }
                              }
                         }

                          //--- 要判断一下优惠促销的商品的限购 ---
                          if(yh_check){
                            var pro_gd_limit_num=0;
                            var p_limit_rs= await getApp().request.promisePost('/api/weshop/promgoods/getPromGoodsLimitNum',{
                              data:{
                                store_id:os.stoid,goods_id:gg.goods_id,prom_id:gg.prom_id,prom_type:3
                              }
                            })
                            if(p_limit_rs && p_limit_rs.data.code==0){
                              pro_gd_limit_num=p_limit_rs.data.data
                            }
                            //-- 如果有商品限购的时候 --
                            if(pro_gd_limit_num>0){
                                var pro_by_num=0;
                                var lrs= {
                                    store_id: os.stoid,user_id: getApp().globalData.user_id,
                                    goods_id: gg.goods_id, prom_type: 3,
                                    prom_id: gg.prom_id, isnew:1
                                };
                                var gd_limit_rs=await getApp().promiseGet('/api/weshop/ordergoods/getUserBuyGoodsNum',{data:lrs});
                                if(gd_limit_rs && gd_limit_rs.data.code==0){
                                   pro_by_num=gd_limit_rs.data.data.promgoodsbuynum
                                }
                                if(pro_gd_limit_num<pro_by_num+good.goods_num){
                                  yh_check=0;
                                }
                            }
                          }

                          //-- 优惠促销活动没有超出限购的话 --
                          if(yh_check){
                             if(!the_yh_map[gg.prom_id]) the_yh_map[gg.prom_id]=[];
                             if(prom)  good.discount_field=prom.discount_field;
                             good.r_shop_price=gg.shop_price;
                             good.r_market_price=gg.market_price;
                             the_yh_map[gg.prom_id].push(good);
                          }

                          break
                        case 7:
                          //获取组合购活动
                          var url = "/api/weshop/prom/zhbuy/get/" + os.stoid + "/" + gg.prom_id + "/" + getApp().globalData.userInfo.user_id;
                          let zh_buy_info=null
                          await getApp().request.promiseGet(url, {}).then(res => {
                            if (res.data.code == 0 && res.data.data) {
                              zh_buy_info = res.data.data
                            }
                          })
                          //判断活动超出限购
                          var is_act_ok=1;
                          let userbuynum = await th.getUserBuyPromNum(gg.prom_id)
                          if (zh_buy_info.buy_limit !=0 && zh_buy_info && userbuynum >= zh_buy_info.buy_limit) {
                            is_act_ok=0;
                          }

                          //判断活动商品超出限购，在从表
                          var url1 = "/api/weshop/prom/zhbuyGoods/page";
                          var req_data = {
                            page: 1,
                            pageSize: 1,
                            store_id: os.stoid,
                            zh_id: gg.prom_id,
                            goods_id: gg.goods_id
                          }
                          await getApp().request.promiseGet(url1, {
                            data: req_data
                          }).then(res => {
                            if (ut.ajax_ok(res)) {
                              var gdlist = res.data.data.pageData[0];
                              gg.buyqty = gdlist.buyqty;
                            }
                          })
                          var num = gg['buyqty'];
                          //---- 要计算商品的限购 -----
                          if (gg['buyqty'] > 0) {
                            if (gg.goods_num + promgoodsbuynum0 > gg['buyqty']) {
                              is_act_ok=0;
                            }
                          }
                          if(is_act_ok){
                            var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
                            th.toast(content);
                            t_ok = 0;
                            break;
                          }
                      }
                  }
            }



            //如果有普通商品要判断能不到达到优惠促销的条件
            if(Object.keys(the_yh_map).length){
              for (let rkey in the_yh_map) {
                var all_price=0;
                var all_num=0;

                for(var ij=0;ij<the_yh_map[rkey].length;ij++){
                     var t_price=the_yh_map[rkey][ij].goods_price;
                     switch (the_yh_map[rkey][ij].discount_field){
                       case 1:
                         t_price=the_yh_map[rkey][ij].r_shop_price;
                         break;
                       case 2:
                         t_price=the_yh_map[rkey][ij].r_market_price;
                         break;
                     }

                     all_price+=t_price * the_yh_map[rkey][ij].goods_num;
                     all_num+= the_yh_map[rkey][ij].goods_num;
                }

                //-- 只有在单赠品的时候，才要进行计算 --
                var res= await getApp().request.promiseGet("/api/weshop/goods/getDiscount", {
                  data: {
                    price: parseFloat(all_price).toFixed(2),
                    prom_id: rkey,
                    goods_num: all_num,
                    user_id: getApp().globalData.user_id,
                    is_bz: prom.is_bz
                  }
                })
                if (res.data.code == 0 && res.data.data && res.data.data.condition){
                      var content = '商品的活动发生了变化,请取消订单重新购买';
                     th.toast(content);
                     t_ok = 0;
                     break;
                }
              }

            }
            //-- 判断活动是不是OK --
            if (!t_ok) {
                th.setData({ paying: 0 }); return false;
            }

            // if (!good.is_gift && good.prom_type != 3) {
            //   var t_ok = 1;
            //   await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromList/" + os.stoid + "/" + good.goods_id + "/0" + "/" + getApp().globalData.user_id, {}).then(res => {
            //     if (res.data.code == 0) {
            //       var r_data = res.data.data;
            //       //-- 参加了全局的优惠活动 --
            //       if (r_data.promGoodsLists) {
            //         var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
            //         th.toast(content);
            //         t_ok = 0;
            //       }
            //     }
            //   })
            //   if (!t_ok) {
            //     th.setData({ paying: 0 }); return false;
            //   }
            // }
            //-- 如果有参加线下取价 --
            if (good.offline_cut > 0) wlist += encodeURIComponent(gg.erpwareid) + ",";
        }
        //赠品和搭配购不判断商品金额
        var isok = 1;
        var card_field = th.data.card_field;

        //-- 如果会员是等级会员,商品有等级价,且不是活动商品，同时线下取价的要放在最后来判断 --
        if (!good.is_gift && !good.is_collocation && gg.prom_type != 9) {


          //-- 优惠促销的时候控制取价规则 --
          // gg.prom_type!=3 && gg.prom_type!=10 同时商品不是普通购买的时候，又参与优惠促销，阶梯促销
          if((gg.prom_type!=3 && gg.prom_type!=10) || gg.discount_field==undefined || gg.discount_field==0  ){

              //判断一下活动是不是有参与订单促销,并且订单促销的活动是不是实收取价,2024-2-23
              let ordprom_price_type=0;
              if(order.order_prom_id && good.prom_type==0){
                  let p_rs= await getApp().request.promiseGet("/api/weshop/promorder/get/"+os.stoid+"/"+order.order_prom_id, {});
                  if(p_rs && p_rs.data.code==0 && p_rs.data.data){
                      let ord_p=p_rs.data.data;
                      if(ord_p && ord_p.discount_field>0){
                        ordprom_price_type=ord_p.discount_field
                      }
                  }
              }
              if(ordprom_price_type>0){
                //-- 看一下订单促销的取价规则 --
                switch (ordprom_price_type){
                  case 1:
                    if (good.goods_price != gg.shop_price) isok = 0;
                    break;
                  case 2:
                    if (good.goods_price != gg.market_price) isok = 0;
                    break;
                }

              }else{
                if (card_field && gg[card_field] > 0) {
                  if (good.goods_price != gg[card_field] && good.offline_cut <= 0) isok = 0;
                  if (good.goods_price > gg[card_field] && good.offline_cut > 0) isok = 0;  //如果线下价格比较贵，则不通过

                } else {
                  if (good.goods_price != gg.shop_price && good.offline_cut <= 0) isok = 0;
                  if (good.goods_price > gg.shop_price && good.offline_cut > 0) isok = 0; //如果线下价格比较贵，则不通过
                }
              }




          }else{

            if(good.prom_type==3 || good.prom_type==10 ){
              switch (gg.discount_field){
                case 1:
                    if (good.goods_price != gg.shop_price) isok = 0;
                    break;
                case 2:
                  if (good.goods_price != gg.market_price) isok = 0;
                  break;
              }
            }
          }


          var is_h = 0;
          if (!isok) {

            var content = gg.goods_name + '商品的价格发生了变化,请取消订单重新购买1'
            th.toast(content);
            th.setData({ paying: 0 });
            return false;
          }
        }

        //--如果是线下库存的时候--
        if (th.data.conf.sales_rules >= 2 && !gg.whsle_id && !good.is_gift) {
          var ob = {};
          await th.check_down_line_next(gg, good.goods_num, order.pickup_id, function (obj) {
            ob = obj;
          })
          if (ob.code == -1) {
             var content = gg.goods_name + '门店库存不足,请取消订单';
             th.toast(content);
             th.setData({ paying: 0 });
             return false;
          }

        } else {
          if (!good.is_gift && good.goods_num > store_count) {

            var content = gg.goods_name + '商品的库存不足,请取消订单';
            th.toast(content);
            th.setData({ paying: 0 });
            return false;
          }

        }
      }

      //---如果是活动的时候---
      var prom = null, goodsinfo = good, th = this;

      goodsinfo.prom_type=parseInt(goodsinfo.prom_type+'');
      if (goodsinfo.prom_type == 1) {
        await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + goodsinfo.prom_id, {}).then(res => {
          if (res.data.code == 0) {
            prom = res.data.data;
            prom.price = prom.user_price;
          }
        })
      }
      if (goodsinfo.prom_type == 2) {
        await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + good.goods_id + "/" + goodsinfo.prom_id, {}).then(res => {
          if (res.data.code == 0) {
            prom = res.data.data;
            prom.price = prom.price;
          }
        })
      }

      if (goodsinfo.prom_type == 6 && !good.is_pd_normal) {
        await getApp().request.promiseGet("/api/weshop/teamlist/get/" + os.stoid + "/" + goodsinfo.prom_id, {}).then(res => {
          if (res.data.code == 0) {
            prom = res.data.data;
          }
        })
      }

      if (goodsinfo.prom_type == 4 && !good.is_integral_normal) {
        await getApp().request.promiseGet("/api/weshop/integralbuy/pageIntegralBuyGoodsList?stype=1&stypeup=1&timetype=2", {
          data: { store_id: os.stoid, goods_id: goodsinfo.goods_id,user_id: getApp().globalData.user_id, }
        }).then(res => {
          if (res.data.code == 0 && res.data.data && res.data.data.pageData) {
            prom = res.data.data.pageData[0];
          }
        })
      }

      if(!prom && [1,2,4,6].includes(goodsinfo.prom_type)){
        wx.showToast({ title: "未找到活动", icon: 'none', duration: 3000 });
        th.setData({ paying: 0 });
        return false;
      }

      //----------如果有活动，并且在进行中，就不计算线下库存---------------
      if (prom) {

        let c_type=parseInt(goodsinfo.prom_type+'');
        var act_type='';
        switch (c_type){
          case 1:act_type='秒杀';break;
          case 2:act_type='团购';break;
          case 6:act_type='拼团';break;
        }

        //指定门店的控制
        if ([1,2,6].indexOf(c_type)>-1 && prom.pick_up_lists) {
          var idx0=prom.pick_up_lists.findIndex(function (e){
            return e.pickup_id==order.pickup_id;
          })
          if(idx0<0){
            getApp().confirmBox(goodsinfo.goods_name +act_type+ "活动的门店不可售");
            th.setData({ paying: 0 });
            return false;
          }
        }

        var now = ut.gettimestamp();
        if (prom.is_end == 1 || prom.end_time < now) {
          var content = goodsinfo.goods_name + '商品的活动已经结束,请取消订单'
          th.toast(content);
          th.setData({ paying: 0 });
          return false;
        }

        if(prom.is_show==0){
          wx.showToast({ title: "活动未启用", icon: 'none', duration: 3000 });
          th.setData({ paying: 0 });
          return false
        }


        buyed_mum2 = promgoodsbuynum + good.goods_num;
        if (buyed_mum2 > prom.buy_limit && prom.buy_limit > 0) {

          var content = goodsinfo.goods_name + '购买数量超出商品活动限购,请取消订单'
          th.toast(content);
          th.setData({ paying: 0 });
          return false;
        }

        // --看一下会员的秒杀价格是不是发生了变化，因为会员的身份发生了变化
        if (goodsinfo.prom_type == 1 && goodsinfo.goods_price != prom.price) {
          var content = goodsinfo.goods_name + '秒杀活动的价格发生了变化';
          th.toast(content);
          th.setData({ paying: 0 });
          return false;
        }

        // --看一下会员的团购价格是不是发生了变化
        if (goodsinfo.prom_type == 2 && goodsinfo.goods_price != prom.price) {
          var content = goodsinfo.goods_name + '秒杀活动的价格发生了变化';
          th.toast(content);
          th.setData({ paying: 0 });
          return false;
        }

        if (goodsinfo.prom_type == 4) {
          if (good.goods_num > prom.limitqty - prom.buy_num) {

            var content = goodsinfo.goods_name + '购买数量超出商品活动库存,请取消订单'
            th.toast(content);
            th.setData({ paying: 0 });
            return false;
          }
        } else if (goodsinfo.prom_type == 1 || goodsinfo.prom_type == 2 || goodsinfo.prom_type == 6) {
          if (order.add_time + 5 * 60 < ut.gettimestamp()) {
            var content = gg.goods_name + '该订单已经超时无法支付,请取消订单';
            th.toast(content);
            th.setData({ paying: 0 });
            return false;
          }
        }

      }

      //-- 预售和幸运购要单独计算 --
      if (goodsinfo.prom_type == 8) {
        var presell_id= goodsinfo.prom_id;
        //------获取预售主表,判断预售活动是不是到期不可以使用了----------
        var res= await getApp().request.promiseGet(`/api/weshop/marketing/marketingPresellForm/get/${os.stoid}/${presell_id}`, {})
        if (res.data.code == 0 && res.data.data) {
          var act_data = res.data.data;
          if (act_data.is_end) {
            wx.showToast({ title: "活动已经结束", icon: 'none', duration: 3000 });
            return false;
          }
          if (act_data.isuse == 0) {
            wx.showToast({ title: "活动未启用", icon: 'none', duration: 3000 });
            return false;
          }

          var err_txt = "活动定金时间已经结束";
          var end_time = act_data.end_time;
          if (act_data.presell_type == 1) {
            err_txt = "活动时间已经结束";
          }
          if (end_time < ut.gettimestamp()) {
            wx.showToast({ title: err_txt, icon: 'none', duration: 3000 });
            return false;
          }

          if (act_data.presell_type == 0) {
            end_time = act_data.pay_enddate;
            err_txt = "活动尾款时间已经结束";
          }
          if (end_time < ut.gettimestamp()) {
            wx.showToast({ title: err_txt, icon: 'none', duration: 3000 });
            return false;
          }
        }

        var all_pre_goods=null;
        var userInfo = getApp().globalData.userInfo;
        var pre_data = { store_id: os.stoid, is_end: 0, timetype: 1, isuse: 1, goods_id: goodsinfo.goods_id };
        if (userInfo) {
          pre_data.user_id = userInfo.user_id;
        }
        var rs_pre= await getApp().request.promiseGet("/api/weshop/marketing/marketingPresellList/page", {
          data: pre_data,
        })
        if (rs_pre.data.code == 0 && rs_pre.data.data.pageData && rs_pre.data.data.pageData.length > 0) {
            all_pre_goods = rs_pre.data.data.pageData;
        }

        if(!all_pre_goods){
          wx.showToast({ title: "未找到活动商品", icon: 'none', duration: 3000 });
          return false;
        }
        var idx = all_pre_goods.findIndex(function (ele) {
          return ele.goods_id == goodsinfo.goods_id;
        })

        if(idx==-1){
           wx.showToast({ title: "未找到活动商品", icon: 'none', duration: 3000 });
           return false;
        }
        var pre_arr = all_pre_goods[idx];
        var prom_buy_limit = pre_arr.vip_butyqty;

        if (goodsinfo.goods_num > pre_arr.presell_sumqty - pre_arr.buy_goodnum) {
           wx.showToast({ title: "超出活动商品库存", icon: 'none', duration: 3000 });
           return false;
        }
        //--判断商品是否超出活动限购--
        if (promgoodsbuynum0 && prom_buy_limit > 0) {
            wx.showToast({ title: "超出活动商品库存", icon: 'none', duration: 3000 });
            return false;
        }

      }
      //幸运购的时候
      if (goodsinfo.prom_type == 9 && !good.is_pt_normal) {

        var lk_act=null;
        //获取单个活动成团信息
        var lk_rs= await getApp().request.promiseGet('/api/weshop/prom/luckyActivity/page', {
            data: {
              store_id: os.stoid,
              is_end: 0,
              timetype: 1,
              id: goodsinfo.prom_id,
              user_id:getApp().globalData.user_id?getApp().globalData.user_id:0
            }
        });

        if(lk_rs && ut.ajax_ok(lk_rs)){
          lk_act= lk_rs.data.data.pageData[0];
        }
        if(!lk_act){
           wx.showToast({ title: "未找到活动，或者活动已结束", icon: 'none', duration: 3000 });
           th.setData({ paying: 0 });
           return false;
        }
        // 检查幸运购活动商品库存
        var lk_redis=await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/9/" + goodsinfo.prom_id,{});
        if(!lk_redis || lk_redis<goodsinfo.goods_num ){
          wx.showToast({ title: "活动商品库存不足", icon: 'none', duration: 3000 });
          th.setData({ paying: 0 });
          return false;
        }
      }

    }

    //-- 要判断一下线下取价价格是不是发生改变 --
    if (wlist != "" && th.data.is_open_offline && th.data.is_open_offline > 0) {
      wlist = ut.sub_last(wlist);
      var keyid = order.pickup_id;
      var user_info = getApp().globalData.userInfo;
      if (!keyid) {
        th.setData({ paying: 0 }); return false;
      }
      var offarr = null;
      await getApp().request.promiseGet("/api/weshop/goods/listWarePrice", {
        data: {
          VIPId: encodeURIComponent(user_info.erpvipid),
          store_id: os.stoid,
          PickupId: keyid,
          WareIds: wlist
        },
      },
      ).then(res => {
        if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
          offarr = res.data.data;
        }
      })
      if (!offarr && offarr.length <= 0) {
        th.toast('获取线下取价失败');
      }
      var newarr = ut.convert_arr_key(offarr, 'WareId');
      //-- 循环判断线下的价格 --
      for (var k in order_goods) {
        var good = order_goods[k];
        //判断线下取价是不是一样
        if (newarr[good.erpwareid] &&
          parseFloat(newarr[good.erpwareid].WarePrice) != parseFloat(good.goods_price)) {

          var content = good.goods_name + '商品的价格发生了变化,请取消订单重新购买';
          th.toast(content);
          th.setData({ paying: 0 });
          return false;
        }
      }
    }

    th.pay_next(e, o_index);
  },


  pay_next(e, o_index) {
    var th = this;
    if (e.order_amount == 0) {
      var dd = {
        parent_sn: e.order_sn,
        store_id: e.store_id,
        type: 1,
      };
      getApp().request.post("/api/weshop/order/pay/createOrder", {
        data: dd,
        success: function (t) {
          th.setData({ paying: 0 });
          if (t.data.code == 0) {
            //th.data.orderList.splice(o_index, 1);
            //th.setData({ orderList: th.data.orderList });
            th.onShow();
          } else {
            getApp().confirmBox(t.data.msg + "请您取消该订单");
          }
        }
      })

      return false;
    }

    /*---
    a.jumpToCart4({
      order_sn: e.order_sn,
      order_amount: e.order_amount,
      type: 1 //正常单
    });--*/

    t.pay(e.order_sn, function () {
      th.setData({ paying: 0 });
      wx.showToast({ title: '支付成功' })
      //th.data.orderList.splice(o_index, 1);
      //th.setData({ orderList: th.data.orderList });

      //商家团支付成功后，要让他的团能够建立或者参与
      if(e.is_zsorder==2){
        //--如果商家团的时候---
        getApp().request.promisePost("/api/weshop/order/pay/vipAutoTuan", {
          data: {orderSn:e.order_sn,storeId:os.stoid }
        })
      }

      setTimeout(()=>{
        th.setData({is_get:0})
        th.onShow();
      },500)


    }, function () {
      th.setData({ paying: 0 });
    }, os.stoid, 1);


  },

  //---检验线下库存的数量的子函数---
  async check_down_line_next(gg, num, pick_id, func) {

    //如果默认是商品
    if(getApp().is_virtual(gg)){
      return func(100000);
    }

    var lock = 0, pick_no, plist;
    var log_rq = { store_id: os.stoid, wareId: gg.goods_id, storageId: pick_id };
    if (this.data.sales_rules == 3) {
      log_rq.appoint_pick_keyid = this.data.appoint_pick_keyid;
      delete log_rq.storageId
    }
    //先读取门店的lock
    await getApp().request.promiseGet("/api/weshop/order/ware/lock/page", {
      data: log_rq
    }).then(res => {
      if (res.data.code == 0 && res.data.data.total > 0) {
        for (var i in res.data.data.pageData)
          lock += res.data.data.pageData[i].outQty;
      }
    })

    if (this.data.sales_rules == 2) {
      //先获取门店的编号
      await getApp().request.promiseGet("/api/weshop/pickup/get/" + os.stoid + "/" + pick_id, {
        data: { storeId: os.stoid, goodsId: gg.goods_id, pickupId: pick_id }
      }).then(res => {
        if (res.data.code == 0) {
          pick_no = res.data.data.pickup_no;
        }
      })
    }

    var sto_rq = { storageNos: pick_no, wareIds: encodeURIComponent(gg.erpwareid), storeId: os.stoid };
    if (this.data.sales_rules == 3) {
      sto_rq.storageIds = this.data.appoint_pick_keyid;
      delete sto_rq.storageNos
    }

    //读取线下的门店库存 
    await getApp().request.promiseGet("/api/weshop/goods/getWareStorages", {
      data: sto_rq
    }).then(res => {
      if (res.data.code == 0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length > 0) {
        plist = res.data.data.pageData[0];
      }
    })

    var ob = {}; ob.code = 1;
    if (!plist) {
      ob.code = -1; ob.CanOutQty = 0;
      func(ob); return false;
    }

    if (num > plist.CanOutQty - lock) {
      ob.code = -1;
      ob.CanOutQty = plist.CanOutQty - lock
      if (ob.CanOutQty < 0) ob.CanOutQty = 0;
    }
    func(ob)
  },


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

  //--------跳转到退款详情-----------
  gotoreturn: function (t) {
    var e = t.currentTarget.dataset.recid;
    var oid = t.currentTarget.dataset.oid;
    var wh = "";
    if (e != undefined && e != null && e != "") {
      wh = "&goods_id=" + e;
    }
    wx.navigateTo({
      url: "/packageF/pages/user/return_goods_info/return_goods_info?order_id=" + oid + wh,
    });
  },

  //-----支付尾款------
  pay_wk: function (ee) {
    console.log("pay_wk");
    var order_id = ee.currentTarget.dataset.order_id;
    wx.navigateTo({
      url: "/packageE/pages/cart/cart_wk/cart_wk?order_id=" + order_id,
    });

  },

  //--判断是不是可以单个商品退--
  check_for_return_btn: function (item) {
    if (item.coupon_no) return false; //有用优惠券
    if (item.order_prom_id) return false; //有订单优惠
    if (item.order_status >= 2) return false; //订单状态>2
    var istrue = true;
    //----判断是不是有优惠活动和赠送商品----
    for (var g in item.goodslist) {
      var g_item = item.goodslist[g];
      if ((g_item.prom_type == 3 && g_item.discount_amount > 0) ||
        (g_item.prom_type == 3 && g_item.goods_price <= 0)
      ) {
        istrue = false;
        break
      }
      if (g_item.prom_type == 5) {
        istrue = false;
        break
      }
    }
    if (!istrue) return false;
    var conf = this.data.conf;
    //判断是不是原路退回
    if (conf.refund_type == 1) return true;
    else {
      if (item.order_amount == 0 || item.user_money == 0) return true;
    }
    return false;
  },
  //跳到首页
  goto: function (e) {
    wx.navigateTo({
      url: '/pages/index/index/index',
    })
  },

  //显示核销码
  code_show: function (e) {
    var th = this;
    //--获取成功的时候--
    var no = e.currentTarget.dataset.order_sn;
    var qc_com = th.selectComponent("#qc_com"); //组件的id
    var obj = {
      val: no,
      content: "请将二维码展示给核销员，收货更快捷"
    };
    qc_com.open(obj)
  },

  //再来一单的功能的实现
  moreOrder: function (e) {

    if (this.data.moring) return false;
    this.data.moring = 1;

    var th = this;
    var index = e.currentTarget.dataset.index;
    var item = th.data.orderList[index];
    th.check_more_order(item);
  },


  check_more_order: async function (item) {
    var pickup = null, th = this;
    var user_id = getApp().globalData.user_id;
    wx.showLoading();
    //--------获取门店-----------
    await getApp().request.promiseGet("/api/weshop/pickup/get/" + os.stoid + "/" + item.pickup_id, {

    }).then(res => {
      if (res.data.code == 0) {
        pickup = res.data.data;
      }
    })
    if (!pickup) {
      wx.hideLoading();
      getApp().confirmBox("找不到门店");
      this.data.moring = 0;
      return false;
    }

    if (pickup.isstop) {
      wx.hideLoading();
      getApp().confirmBox("门店已停用");
      this.data.moring = 0;
      return false;
    }


    if (!pickup.is_pos) {
      wx.hideLoading();
      getApp().confirmBox("门店不允许销售");
      this.data.moring = 0;
      return false;
    }
    //--------获取商品----------
    var goods_list = item.order_goods;
    //--- 返回的内容 ---
    var back_goods_arr = [];
    var err_text = "";
    for (var i in goods_list) {
      var g_item = goods_list[i];
      var b_item = {};
      //--如果是赠品，不加入购物车--
      if (g_item['is_gift']) continue;
      if (g_item['prom_type'] == 4) {
        err_text += g_item['goods_name'] + "积分购商品不加入购物车\n";
        continue;
      }
      if (g_item['prom_type'] == 5) {
        err_text += g_item['goods_name'] + "搭配购商品不加入购物车\n";
        continue;
      }
      if (g_item['prom_type'] == 6) {
        err_text += g_item['goods_name'] + "拼团商品不加入购物车\n";
        continue;
      }

      //--获取商品--
      var good = null;
      await getApp().request.promiseGet("/api/weshop/goods/get/" + os.stoid + "/" + g_item.goods_id, {

      }).then(res => {
        good = res.data.data;
      })

      //调用接口判断订单优惠，
      // const res = await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromList/" + os.stoid + "/" + g_item.goods_id + "/0", {})
      // if (res.data.code == 0 && res.data.data) {
      //     var r_data = res.data.data;
      //     if (r_data.ladderLists) {
      //         var act_id = r_data.ladderLists[0].form_id;
      //         //-- 判断会员能不能参与阶梯促销 --
      //         const data = await getApp().request.promiseGet("/api/weshop/prom/ladderForm/getNew/" + os.stoid + "/" + user_id + "/" + act_id, {})
      //         if (data.data.code == 0 && data.data.data && data.data.data.isuse && data.data.data.is_end == 0) {
      //             b_item.prom_type = 10;
      //             b_item.prom_id = data.data.data.id;
      //         }
      //     }
      // }
      if (!good) {
        err_text += g_item['goods_name'] + "未找到商品\n";
        continue;
      }
      if (good.is_on_sale != 1) {
        err_text += g_item['goods_name'] + "已经下架\n";
        continue;
      }

      var timestamp = ut.gettimestamp();
      if (good.on_time > timestamp) {
        err_text += g_item['goods_name'] + "还未上架\n";
        continue;
      }
      if (good.down_time > 0) {
        if (good.down_time < timestamp) {
          err_text += g_item['goods_name'] + "已经下架\n";
          continue;
        }
      }

      //如果商品的配送方式和门店不匹配
      if (good['distr_type'] > 0 && pickup['distr_type'] > 0 && good['distr_type'] != pickup['distr_type']) {
        err_text += good['goods_name'] + "配送方式不一致\n";
        continue;
      }

      var prom = null;

      b_item.goods_id = g_item.goods_id;
      b_item.goods_name = g_item.goods_name;
      b_item.goods_num = g_item.goods_num;
      b_item.guide_id = g_item.guide_id;
      b_item.guide_type = g_item.guide_type;
      b_item.pickup_id = item.pickup_id;
      b_item.price = good.shop_price;
      b_item.goods_sn = good.goods_sn;
      b_item.sku = good.sku;
      b_item.is_integral_normal = g_item.is_integral_normal;

      //-- 如果会员是等级卡的时候,同时商品也有设置相应的卡价格 --
      var card_field = th.data.card_field;
      if (card_field && good[card_field] > 0) {
        b_item.price = good[card_field];
      }

      var url = "/api/weshop/activitylist/listGoodActInfo2New";
      var req_data = {
        store_id: g_item.store_id, goods_id: g_item.goods_id, user_id: user_id
      };
      await getApp().request.promiseGet(url, { data: req_data }).then(res => {
        if (res.data.code == 0) {

          var arr = res.data.data;
          //-- 预热也要计算 --
          var arr2 = arr.filter(function (e) {
            return e.s_time < ut.gettimestamp();
          })

          if (arr2.length == 1) {
             good.prom_type = arr2[0].prom_type;
             good.prom_id = arr2[0].act_id;
          }
          else if (arr2.length > 1) {
            good.prom_type = g_item.prom_type; good.prom_id = g_item.prom_id;
          }


          var arr3 = arr.filter(function (e) {
            return e.s_time < ut.gettimestamp() && e.prom_type == 7;
          })

          if (arr3 && arr3.length > 0) {
            b_item.zh_prom_id= arr3[0].act_id;
          }

        }
      })


       //--判断商品当前的活动情况--
      switch (good.prom_type) {
          case 1:
            var flash = null;
            await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + os.stoid + "/" + getApp().globalData.user_id + "/" + good.prom_id, {}).then(res => {
              if (res.data.code == 0) {
                flash = res.data.data;
              }
            })
            //----没有结束-----
            if (flash && flash.is_end == 0) {

              if (flash.end_time > timestamp && flash.start_time < timestamp) {
                prom = flash;
                prom.price = prom.user_price;
                b_item.price = prom.user_price;
              } else {
                if (g_item.prom_type == 0 && !flash.is_shop_buy) {
                  err_text += g_item['goods_name'] + "秒杀活动不允许普通价\n";
                  continue;
                }
              }

            }
            break;

          case 2:
            var group = null;
            await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getNewActInfo/" + os.stoid + "/" + good.goods_id + "/" + good.prom_id+"/"+ getApp().globalData.user_id, {}).then(res => {
              if (res.data.code == 0) {
                group = res.data.data;
              }
            })
            //----已经结束-----
            if (group && group.is_end == 0 && group.end_time > timestamp && group.start_time < timestamp) {
              prom = group;
              prom.price = prom.price;
              b_item.price = prom.price;
            }
            break;

          case 6:
            b_item.is_pd_normal = 1;
            break;
          case 7:
            //如果有组合购
            var url = "/api/weshop/prom/zhbuy/get/" + os.stoid + "/" + good.prom_id + "/" + getApp().globalData.userInfo.user_id;
            await getApp().request.promiseGet(url, {}).then(res => {
              if (res.data.code == 0 && res.data.data) {
                var t_act=res.data.data;
                if(!t_act.zh_num || t_act.zh_num>t_act.zh_buy_num) {
                    if (res.data.data.is_show == 1 && res.data.data.is_end == 0
                        && ut.gettimestamp() < res.data.data.end_time
                        && ut.gettimestamp() > res.data.data.start_time
                    ) {
                      b_item.prom_type = 7;
                      b_item.prom_id = res.data.data.id;

                    }
                }
              }
            })
            break;
          case 10:
            let user_id = getApp().globalData.userInfo.user_id;
            var url = `/api/weshop/prom/ladderForm/getNew/${os.stoid}/${user_id}/${good.prom_id}`;
            await getApp().request.promiseGet(url, {}).then(res => {
              if (res.data.code == 0 && res.data.data && res.data.data.isuse && res.data.data.is_end == 0) {
                b_item.prom_type = 10;
                b_item.prom_id = res.data.data.id;
              }
            })
            break;
        }


      //如果有优惠促销的时候,要看下商品的优惠活动有没有过期
      if ((g_item.prom_type == 3 || good.prom_type == 3) && good.whsle_id <= 0) {
        var is_g_prom = 0;
        //因为有全场优惠活动，商品参加的活动还未开始
        var url = "/api/weshop/activitylist/getGoodActInfo";
        var req_data = {
          store_id: os.stoid, goodsidlist: good.goods_id, is_detail: 1, user_id: user_id
        };
        await getApp().request.promiseGet(url, { data: req_data }).then(async function (res) {
          if (res.data.code == 0 && res.data.data && res.data.data.length) {
            for (let i in res.data.data) {
              let item = res.data.data[i];
              if (item.prom_type == 3) {
                is_g_prom = 1; break;
              }
            }
          }
        })
        if (is_g_prom) {
          await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromList/" + os.stoid + "/" + good.goods_id + "/1" + "/" + getApp().globalData.user_id, {}).then(res => {
            if (res.data.code == 0) {
              var r_data = res.data.data;
              if (r_data.promGoodsLists) {
                b_item.prom_type = 3;
                b_item.prom_id = r_data.promGoodsLists[0].prom_id;
              }
            }
          })
        } else {
          await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromNormal/" + os.stoid + "/" + good.goods_id, {}).then(res => {
            if (res.data.code == 0) {
              var r_data = res.data.data;
              if (r_data.promGoodsLists) {
                b_item.prom_type = 3;
                b_item.prom_id = r_data.promGoodsLists[0].prom_id;
              }
            }
          })
        }

      }


      //判断是不是线下库存的购买，  是不是秒杀活动
      if (!getApp().is_virtual(good) && th.data.sales_rules >= 2 && !prom && !good.whsle_id) {

        //-- 看一下购物车上有多少商品 --
        var cart_num = 0;
        // await getApp().request.promiseGet("/api/weshop/cart/page", {
        //   data: {
        //     store_id: os.stoid,
        //     user_id: getApp().globalData.user_id,
        //     state: 0, is_gift: 0,
        //     goods_id: good.goods_id,
        //     pick_id: b_item.pickup_id
        //   }
        // }).then(res => {
        //   var num = 0;
        //   if (res.data.code == 0 && res.data.data && res.data.data.pageData) {
        //     for (var i = 0; i < res.data.data.pageData.length; i++) {
        //       num += res.data.data.pageData[i].goods_num;
        //     }
        //   }
        //   cart_num = num;
        // })

        var lock = 0, plist = null;

        if (b_item.prom_type != 7) {

          var lock_rq = { store_id: os.stoid, wareId: good.goods_id, storageId: b_item.pickup_id, pageSize: 1000 };
          if (th.data.sales_rules == 3) {
            lock_rq.appoint_pick_keyid = th.data.appoint_pick_keyid;
            delete lock_rq.storageId;
          }
          //先读取门店的lock,
          await getApp().request.promiseGet("/api/weshop/order/ware/lock/page", {
            data: lock_rq
          }).then(res => {
            if (res.data.code == 0 && res.data.data.total > 0) {
              for (var i in res.data.data.pageData)
                lock += res.data.data.pageData[i].outQty
            }
          })

          var sto_rq = { storageNos: pickup.pickup_no, wareIds: encodeURIComponent(good.erpwareid), storeId: os.stoid }
          if (th.data.sales_rules == 3) {
            sto_rq.storageIds = th.data.appoint_pick_keyid;
            delete sto_rq.storageNos;
          }
          //---通过接口获取门店的线下库存信息--
          await getApp().request.promiseGet("/api/weshop/goods/getWareStorages", {
            data: sto_rq
          }).then(res => {
            if (res.data.code == 0 && res.data.data.total > 0) {
              plist = res.data.data.pageData[0];
            }
          })

          if (!plist) {
            err_text += good['goods_name'] + "库存不足\n";
            continue;
          }
          if (plist.CanOutQty - lock <= 0) {
            err_text += good['goods_name'] + "库存不足\n";
            continue;
          }
          if (b_item.goods_num > (plist.CanOutQty - lock)) {
            b_item.goods_num = plist.CanOutQty - lock;
          }
        }
        var req_data = {
          store_id: os.stoid,
          user_id: getApp().globalData.user_id,
          goods_id: good.goods_id,
          timetype:good.viplimited_timetype,
          isnew:1,

        };
        if (b_item.prom_type == 7) {
          req_data.prom_type = 7;
          req_data.prom_id = b_item.prom_id;
        }

        var buynum = 0;
        var promnum = 0;
        //---要获得商品，该用户买了多少件,同步应用---
        await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
          data: req_data,
        }).then(res => {
          if (res.data.code == 0) {
            var buy_num_data = res.data.data;
            buynum = buy_num_data.goodsbuynum;
            if (buy_num_data.promgoodsbuynum) {
              promnum = buy_num_data.promgoodsbuynum;
            }
          }
        })

        //---- 要计算商品的限购 -----
        if (good['viplimited'] > 0) {
          if (cart_num + buynum > good['viplimited']) {
            err_text += good['goods_name'] + "超出限购\n";
            continue;
          }
          good['viplimited'] -= (cart_num + buynum);
          if (b_item.goods_num > good['viplimited']) {
            b_item.goods_num = good['viplimited'];
          }
        }
        //不需要计算组合购的限购

        back_goods_arr.push(b_item);  //返回商品元素

      } else {

        //-- 看一下购物车上有多少商品 --
        var cart_num = 0;
        // await getApp().request.promiseGet("/api/weshop/cart/page", {
        //   data: {
        //     store_id: os.stoid,
        //     user_id: getApp().globalData.user_id,
        //     state: 0, is_gift: 0,
        //     goods_id: good.goods_id
        //   }
        // }).then(res => {
        //   var num = 0;
        //   if (res.data.code == 0 && res.data.data && res.data.data.pageData) {
        //     for (var i = 0; i < res.data.data.pageData.length; i++) {
        //       num += res.data.data.pageData[i].goods_num;
        //     }
        //   }
        //   cart_num = num;
        // })


        if (good.store_count <= 0) {
          err_text += good['goods_name'] + "库存不足\n";
          continue;
        }
        if (b_item.goods_num > good.store_count)
          b_item.goods_num = good.store_count;

        var buynum = 0;             //商品已经购买多少件
        var promgoodsbuynum = 0;	//活动已经购买多少件
        var redis_num = 0;        //redis库存

        var req_data = {
          store_id: os.stoid,
          user_id: getApp().globalData.user_id,
          goods_id: good.goods_id,
          timetype:good.viplimited_timetype,
          isnew:1,
        };

        if (prom) {
          req_data.prom_type = good.prom_type;
          req_data.prom_id = good.prom_id;
          b_item.prom_type = good.prom_type;
          b_item.prom_id = good.prom_id;

          //------判断活动是否抢光-----
          await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" +
            os.stoid + "/" + good.prom_type + "/" + good.prom_id, {
            1: 1
          }).then(res => {
            redis_num = res.data.data;
          });
          if (redis_num <= 0) {
            //不允许商品普通价格修改
            if (!prom.is_shop_buy && prom.is_shop_buy != undefined) {
              err_text += good['goods_name'] + "活动不足\n";
              continue;
            }
          }

        }

        //---要获得商品，该用户买了多少件,同步应用---
        await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
          data: req_data,
        }).then(res => {
          if (res.data.code == 0) {
            var buy_num_data = res.data.data;
            if (buy_num_data.promgoodsbuynum) promgoodsbuynum = buy_num_data.promgoodsbuynum;
            buynum = buy_num_data.goodsbuynum;
          }
        })

        //---- 要计算商品的限购 -----
        if (good['viplimited'] > 0) {
          if (cart_num + buynum >= good['viplimited']) {
            err_text += good['goods_name'] + "超出限购\n";
            continue;
          }
          good['viplimited'] -= (cart_num + buynum);
          if (b_item.goods_num > good['viplimited']) {
            b_item.goods_num = good['viplimited'];
          }

        }

        //-- 判断活动的库存 --
        if (prom) {
          if (prom['goods_num'] <= prom['buy_num']) {
            err_text += good['goods_name'] + "超出活动库存\n";
            continue;
          }

          if (b_item.goods_num > prom['goods_num'] - prom['buy_num']) {
            b_item['goods_num'] = b_item['goods_num'] - b_item['buy_num'];
          }

          if (b_item.goods_num > redis_num) {
            b_item.goods_num = redis_num;
          }

          if (prom['buy_limit'] > 0) {
            if (cart_num + promgoodsbuynum >= prom['buy_limit']) {
              err_text += good['goods_name'] + "超出活动限购\n";
              continue;
            }
            prom['buy_limit'] -= (cart_num + promgoodsbuynum);
            if (b_item.goods_num > prom['buy_limit']) {
              b_item.goods_num = prom['buy_limit'];
            }
          }
        }


        back_goods_arr.push(b_item);  //返回商品元素
      }
    }

    //有重新购买的数据是时候，就要重新生成订单
    if (back_goods_arr.length > 0) {
      th.setData({ back_goods_arr: back_goods_arr });
      if (!err_text) {
        th.more_add_cart();
      } else {
        wx.hideLoading();
        // 如果没有获取用户信息
        wx.showModal({
          title: '确定',
          content: err_text + ',确定要买其他商品码？',
          success(res) {
            if (res.confirm) {
              //跳转到登录页
              th.more_add_cart();
            } else {
              th.data.moring = 0;
              wx.hideLoading();
            }
          }, fail() {
            th.data.moring = 0;
            wx.hideLoading();
          }
        });

      }
    } else {
      th.data.moring = 0;
      wx.hideLoading();
      getApp().confirmBox(err_text);
    }
  },

  more_add_cart: async function () {
    var th=this;
    var back_goods_arr = this.data.back_goods_arr;
    var err_text = "";
    var ok_num = 0;
    var zh_prom_id_err=[];
    var zh_prom_id_err_goods=[];

    for (var i in back_goods_arr) {
      //商品ID
      var g_item = back_goods_arr[i];
      var newd = {
        goods_id: g_item.goods_id,
        goods_num: g_item.goods_num,
        pick_id: g_item.pickup_id,
        user_id: oo.user_id,
        store_id: os.stoid,
        goods_price: g_item.price,
        member_goods_price: g_item.price,
        goods_name: g_item.goods_name,
        goods_sn: g_item.goods_sn,
        sku: g_item.sku,
      };

      if (g_item.guide_id) {
        newd['guide_id'] = g_item.guide_id;
        newd['guide_type'] = g_item.guide_type;
      }

      if (g_item.is_integral_normal) {
        newd['is_integral_normal'] = g_item.is_integral_normal;
      }
      if (g_item.is_pd_normal) {
        newd['is_pd_normal'] = g_item.is_pd_normal;
      }

      if (g_item.prom_type) {
        //3，5，7，10加入购物车，统一prom_type为0
        if([3,5,7,10].indexOf(g_item.prom_type)>-1){
          g_item.prom_type=0;
          g_item.prom_id=0;
        }
        newd['prom_type'] = g_item.prom_type;
        newd['prom_id'] = g_item.prom_id;
      }

      newd['zh_prom_id']=0;

      if(g_item.zh_prom_id){
        newd['zh_prom_id'] = g_item.zh_prom_id;
      }


      var b_cart_goods = null;
      await getApp().request.promiseGet("/api/weshop/cart/page", {
        data: {
          store_id: os.stoid,
          user_id: oo.user_id,
          goods_id: g_item.goods_id,
          pick_id: g_item.pickup_id,
          state: 0,
        },
      }).then(res => {
        //-------如果购物车中有相关的数据-------
        if (res.data.data.total > 0) {
          b_cart_goods = res.data.data.pageData;
        }
      })

      //-- 判断购物车是不是有重复 --
      var is_has=null;
      if(b_cart_goods) {

        for (let jr = 0; jr < b_cart_goods.length; jr++) {
          var b_cart_item = b_cart_goods[jr];

          if (!g_item.prom_type || g_item.prom_type == 0 || ([0, 3, 5, 7, 10].includes(parseInt(g_item.prom_type+''))) ) {
            if ([0, 3, 5, 7, 10].indexOf(b_cart_item.prom_type) > -1 && g_item.is_gift!=0) {
              is_has = b_cart_item;
              break
            }
          } else {
            if (b_cart_item.prom_type == g_item.prom_type && b_cart_item.prom_id == g_item.prom_id) {
              is_has = b_cart_item;
              break
            }
          }
        }
      }

      //-- 如果就加入过购物车 --
      if (is_has) {
        var updata = {
          id: is_has.id,
          goods_num: newd.goods_num + is_has.goods_num,
          goods_price: newd.goods_price,
          member_goods_price: newd.goods_price,
          store_id: os.stoid,
        };
        if (newd.guide_id) {
          updata.guide_id = newd.guide_id;
          updata.guide_type = newd.guide_type;
        }
        if (newd.prom_type) {
          updata.prom_type = newd.prom_type;
          updata.prom_id = newd.prom_id;
        }

        if(newd['zh_prom_id']){
          updata.zh_prom_id=newd['zh_prom_id'];
        }


        //如果购物车中商品zh_prom_id不一致的话，要进行提示
        if(is_has.zh_prom_id>0 && is_has.zh_prom_id!= newd['zh_prom_id'] ){
          zh_prom_id_err.push(newd.goods_name+ '已在购物车\n');
          zh_prom_id_err_goods.push(updata);
          continue;
        }
        
        await getApp().request.promisePut("/api/weshop/cart/update", {
          data: updata
        }).then(res => {
          if (res.data.code == 0) {
            ok_num++;
          } else {
            err_text += newd.goods_name + "加入购物车失败\n";
          }
        })

      } else {
        await getApp().request.promisePost("/api/weshop/cart/save", {
          data: newd
        }).then(res => {
          if (res.data.code == 0) {
            ok_num++;
          } else {
            err_text += newd.goods_name + "加入购物车失败\n";
          }
        })
      }
    }
    wx.hideLoading();
    this.data.moring = 0;

    if(zh_prom_id_err_goods && zh_prom_id_err_goods.length){
      if(err_text){
        err_text+="同时有以下商品：\n";
      }
      err_text+=zh_prom_id_err.join('');
      err_text+="是否替换参与该活动？"

      // 如果没有获取用户信息
      wx.showModal({
        title: '提示',
        content: err_text,
        success(res) {
          if (res.confirm) {
            //进行对有zh_prom_id 不一样的商品进行替换
            th.zhbuy_add_cart(zh_prom_id_err_goods)
          }
        }
      });


    }else{

        if (ok_num == 0) {
        //-- 如果没有获取用户信息 --
        wx.showModal({
          title: '提示',
          content: err_text,
          success(res) { }
        });
      } else {


            if (err_text == "") {
              getApp().goto("/pages/cart/cart/cart");
            } else {
              // 如果没有获取用户信息
              wx.showModal({
                title: '提示',
                content: err_text,
                success(res) {
                  if (res.confirm) {
                    //跳转到登录页
                    getApp().goto("/pages/cart/cart/cart");
                  }
                }
              });
            }
        }
    }
  },

  //-- 组合购的商品重新购买 --
  zhbuy_add_cart: async function (zh_prom_id_err_goods) {
      var err_text = "";
      for (var i in zh_prom_id_err_goods) {
        var updata=zh_prom_id_err_goods[i];
        await getApp().request.promisePut("/api/weshop/cart/update", {
          data: updata
        }).then(res => {
          if (res.data.code != 0) {
            err_text += newd.goods_name + "加入购物车失败\n";
          }
        })
      }

     if (err_text == "") {
       getApp().goto("/pages/cart/cart/cart");
     }else{
       // 如果没有获取用户信息
       wx.showModal({
         title: '提示',
         content: err_text,
         success(res) {
           if (res.confirm) {
             //跳转到登录页
             getApp().goto("/pages/cart/cart/cart");
           }
         }
       });
     }
  },


  //获取用户参与组合购的次数
  async getUserBuyPromNum(prom_id,is_buy){
    var userInfo = getApp().globalData.userInfo;

    var url = `/api/weshop/ordergoods/getUserBuyPromNum?is_all=1&store_id=${os.stoid}&user_id=${userInfo.user_id}&prom_type=7&prom_id=${prom_id}`;
    if(is_buy){
      url = `/api/weshop/ordergoods/getUserBuyPromNum?store_id=${os.stoid}&user_id=${userInfo.user_id}&prom_type=7&prom_id=${prom_id}`;
    }

    let res = await getApp().request.promiseGet(url, {
      data:{}
    });
    let userbuynum=0
    if(res.data.code==0 && res.data.data){
      userbuynum=res.data.data.userbuynum
    }
    return userbuynum
  },


  request_list: function (data, callback) {
    // console.log('进入request_list');

    var th = this;
    if (this.data.is_load2) return false;    //-- 正在加载
    if (this.data.is_no_data2) return false; //-- 没有数据
    if (this.data.is_no_more2) return false; //-- 没有更多

    // 开启加载状态
    this.data.is_load2 = 1;

    // var req_data = {
    // 	page:th.data.currentPage2
    // }
    let currentIndex = this.data.currentIndex;
    let url = '';
    if (currentIndex == 1) {
      url = '/api/weshop/order/pagePosOrder';
    };
    if (currentIndex == 2) {
      url = '/api/weshop/recharge/user/page';
    };

    wx.showLoading({
      title: '',
    })

    app.request.promiseGet(url, {
      data: data
    }).then(async res => {
      wx.hideLoading();
      // 关闭加载状态
      th.data.is_load2 = 0;
   
      // 请求成功
      if (res.data.code == 0 && res.data.data && res.data.data.pageData) {

        if (res.data.data.pageData.length > 0) {
          th.data.currentPage2++;
          var data = res.data.data.pageData;
          // 判断有无更多数据可以加载，如果大于则没有更多数据，反之则有
          if (res.data.data.page * res.data.data.pageSize >= res.data.data.total) { th.setData({ is_no_more2: 1 }); }
          
          
          let list = th.data.list2;
          if(!list) list=[];

          if (currentIndex == 1) {
            //list = th.data.list2;
            var new_data= data.map((item,index)=>{
                 var all_qty=0;  //总数量
                 var all_yh=0;   //总是优惠金额
                 if(item.list && item.list.length){
                   for (let iv = 0; iv < item.list.length; iv++) {
                       var tt_ite=item.list[iv];
                       all_qty+=tt_ite.Qty;
                       all_yh+=tt_ite.LetSum;
                   }
                   item.all_qty=all_qty;
                   item.all_yh=all_yh;
                 }
                 if(item.CashRepNo){
                     var q_arr=item.CashRepNo.split(',');
                     var n_arr=[];
                     for (let ix = 0; ix <q_arr.length; ix++) {
                         if(!q_arr[ix]) continue;
                         n_arr.push(q_arr[ix]);
                     }
                     item.quan_arr=n_arr;
                 }
                 return item;
            })

            list = list.concat(new_data);
            th.setData({ list2: list });
          };

          if (currentIndex == 2) { // 卡项订单
            list = th.data.cardList;
            // var new_data= data.map((item,index)=>{
            //      if(item.list && item.list.length){
            //        item.pt_status=item.list[0].pt_status;
            //        item.pt_tail_money=item.list[0].pt_tail_money;
            //        item.prom_id=item.list[0].prom_id;
            //        item.prom_type=item.list[0].prom_type;
            //      }
            //      return item;
            // })

            var new_data=[];
            for (let ir = 0; ir <data.length ; ir++) {
                   var item=data[ir];
                   if(item.list && item.list.length){
                     item.pt_status=item.list[0].pt_status;
                     item.pt_tail_money=item.list[0].pt_tail_money;
                     item.prom_id=item.list[0].prom_id;
                     item.prom_type=item.list[0].prom_type;
                   }

                   if(item.prom_type==8){
                     await getApp().request.promiseGet('/api/weshop/recharge/rechargePresell/get/' + os.stoid + '/' + item.order_id, {
                     }).then(rr => {
                       if (rr.data.code == 0) {
                         item['presell'] = rr.data.data;
                         item['ord_url'] = '/packageC/pages/presell/cart/cart';
                       }
                     })
                   }

                   new_data.push(item);
            }

            list = list.concat(new_data);
            th.setData({ cardList: list });
            console.log('currentCard', list);
          };

        } else {
          if (th.data.currentPage2 == 1) {
            th.setData({ is_no_data2: 1 });
          } else {
            th.setData({ is_no_more2: 1 });
          }
        }

        if (callback) callback(res);
      } else {
        // wx.showToast({
        //   title: res.data.msg,
        //   icon: 'none',
        //   duration: 2000
        // })
      }

      th.setData({is_get:1})

    })
  },


  onClickTab(e) {
    let currentIndex = parseInt(e.target.dataset.index || 0);
    this.setData({
      currentIndex: currentIndex,
      is_get:0
    });

    this.setData({
      is_no_data2: 0,
      is_no_more2: 0,
      currentPage2: 1,
    });
    if (currentIndex == 0 && !this.data.have_get_nor) {
      console.log('线上订单');
      /*---
      this.setData({
        startDate: '选择开始时间',
        endDate: '选择结束时间',
      });--*/
      wx.showLoading({
        title: '',
      })
      this.requestOrderList(this.data.activeCategoryId);

    };

    
    if (currentIndex == 1) {
      console.log('线下订单');
      this.request_list({
        store_id: os.stoid,
        user_id: oo.user_id,
        page: 1,
        BeginDate: this.data.startDate,
        EndDate: this.data.endDate
      });
    };
    if (currentIndex == 2) {
      console.log('卡项订单');
      // this.setData({
      // 	orderList: null,
      // });
      // 默认请求全部卡项订单
      this.request_list({
        store_id: os.stoid,
        user_id: oo.user_id,
      });
      // let url = '/api/weshop/recharge/user/page';
      // let data = {
      // 	store_id: os.stoid,
      // 	user_id: oo.user_id,
      // };
      // app.promiseGet(url, {
      // 	data: data,
      // }).then(res => {
      // 	if(res.data.code == 0) {
      // 		console.log('卡项订单请求成功', res);
      // 		this.setData({
      // 			orderList: res.data.data.pageData,
      // 		});
      // 	} else {
      // 		throw(res);
      // 	};
      // }).catch(err => {
      // 	console.log('卡项订单请求失败', err);
      // 	this.setData({
      // 		orderList: null,
      // 	});
      // 	wx.showToast({
      // 		title: err.data.data,
      // 		icon: 'error',
      // 	});
      // });
    };
  },

  bindDateChange1: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      startDate: e.detail.value
    })
  },

  bindDateChange2: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endDate: e.detail.value
    })
  },

  bindInput(e) {
    this.data.searchContent = e.detail.value;
  },

  searchOnline() {
    let currentIndex = this.data.currentIndex;
    // console.log('online',this.data.searchContent, currentIndex);
    if (this.data.searchContent) {
      console.log(this.data.searchContent);
      if (currentIndex == 0) {
        this.resetData(), this.requestOrderList(this.data.activeCategoryId);
      };
      if (currentIndex == 2) { // 卡项订单
        let url = '/api/weshop/recharge/user/page';
        let data = {
          store_id: os.stoid,
          user_id: oo.user_id,
          keyWord: this.data.searchContent,
        };
        this.setData({
          tabIndex: 0,
        });
        // 请求数据
        app.promiseGet(url, {
          data: data,
        }).then(res => {
          if (res.data.code == 0) {
            // console.log('卡项订单请求成功', res);
            this.setData({
              cardList: res.data.data.pageData,
            });
          } else {
            throw (res);
          };
        }).catch(err => {
          // console.log('卡项订单请求失败', err);
          this.setData({
            cardList: [],
            is_no_data2: 0,
            is_no_more2: 0,
          });
          // wx.showToast({
          // 	title: '搜索失败',
          // 	icon: 'none',
          // });
        });
      };
    } else {
      wx.showToast({
        title: '您还没有输入搜索内容~',
        icon: 'none',
      })
    };
  },

  searchOffline() {
    console.log('执行查询');
    let th = this;
    let startDate = this.data.startDate;
    let endDate = this.data.endDate;

    // this.data.is_no_data2 = 0;
    if (startDate == '选择开始时间' || endDate == '选择结束时间') {
      wx.showToast({
        title: '请选择完整的查询时间~',
        icon: 'none',
      })
    };

    if (new Date(startDate) > new Date(endDate)) {
      wx.showToast({
        title: '不对噢！开始时间不能晚于结束时间~',
        icon: 'none',
      })
      return;
    };

    this.setData({
      currentPage2: 1,
      list2: [],
      is_no_data2: 0,
      is_no_more2:0,
      is_get:0
    });


    wx.showLoading({
      title: '',
    })


    this.request_list({
      store_id: os.stoid,
      user_id: oo.user_id,
      page: 1,
      BeginDate: this.data.startDate,
      EndDate: this.data.endDate
    }, function (res) {
      if (res.data.data.total == 0) {
        wx.showToast({
          title: '没有找到相关订单',
          icon: 'none',
          duration: 2000
        })
      } else {
        th.setData({
          total: res.data.data.total
        });
      }
    });
  },

  currentDate() {
    var now = new Date();
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var clock = year + "-";

    if (month < 10) month += "0";
    clock += month + "-";

    if (day < 10) day += "0";
    clock += day;

    // if(hh < 10)
    // 		clock += "0";

    // clock += hh + ":";
    // if (mm < 10) clock += '0'; 
    // clock += mm + ":"; 

    // if (ss < 10) clock += '0'; 
    // clock += ss; 
    return clock;
  },

  toast(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 3000
    })
  },

  go_url(e) {
    var url = e.currentTarget.dataset.url;
    getApp().goto(url);
  },

  // 点击卡项订单二级tabbar
  clickTab(e) {
    // console.log('服务卡项index', e.target.dataset.index);
    let currentIndex = 0;
    if (e) {
      currentIndex = e.target.dataset.index;
    } else {
      currentIndex = this.data.tabIndex
    };

    // let || this.data.tabIndex;

    let url = '/api/weshop/recharge/user/page';
    let data = {
      store_id: os.stoid,
      user_id: oo.user_id,
    };
    this.setData({
      tabIndex: currentIndex,
      is_no_data2: 0,
      is_no_more2: 0,
      cardList: [],
    });


    switch (parseInt(currentIndex+'')) {
      case 0: { // 全部
        delete data.order_status;
        delete data.pay_status;
        break;
      };
      case 1: { // 待支付
        data.order_status = 0;
        delete data.pay_status;

        data.page=1;
        data.BeginDate=this.data.startDate,
        data.EndDate=this.data.endDate

        break;
      };
      case 2: { // 待评价
        data.pay_status = 1;
        data.order_status=1;
        break;
      };
    };
    // 请求数据
    this.request_list(data);

    // app.promiseGet(url, {
    // 	data: data,
    // }).then(res => {
    // 	if(res.data.code == 0) {
    // 		console.log('卡项订单请求成功', res);
    // 		this.setData({
    // 			orderList: res.data.data.pageData,
    // 		});
    // 	} else {
    // 		throw(res);
    // 	};
    // }).catch(err => {
    // 	console.log('卡项订单请求失败', err);
    // 	this.setData({
    // 		orderList: null,
    // 	});
    // 	wx.showToast({
    // 		title: err.data.data,
    // 		icon: 'error',
    // 	});
    // });
  },

  // 卡项订单 - 查看详情
  viewDetails() {
    let url = '/packageA/pages/details_serviceCard/details_serviceCard';
    app.goto(url);
  },

  // 卡项订单 - 立即支付
  pay: async function (e) {
    let th=this;

    if(th.data.ser_paying) return false;
    //th.data.ser_paying=1;
    let index = e.currentTarget.dataset.index;

    //避免重复点击
    var txt="ser_paying["+index+"]";
    this.setData({[txt]:1});

    let item = this.data.cardList[index];
    let order_sn = item.order_sn;
    let order_id = item.order_id;
    let store_id = app.globalData.setting.stoid;
    let user_id = oo.user_id;
    let flag = true;
    // 如果是普通购买或单独购买，不用判断
    // 如果是秒杀购买：1、判断活动是否变化；2、是否超出限购
    let list = item.list;
    var pt_act=null;  //-- 拼团活动的优化 --

    for (const it of list) {

      var card=null;
      await getApp().request.promiseGet("/api/weshop/serviceCard/get/" + store_id + "/" + it.card_id, {}).then(res => {
        if(res.data.code==0 && res.data.data){
          card = res.data.data;
        }
      })

      if(card && card.storageId){
        let the_c_key=it.pickup_keyid;
        if (card.storageId.indexOf(the_c_key)==-1) {
          getApp().confirmBox(it.service_name + "的门店不可售");
          th.setData({ ser_paying: 0 });
          flag = false;
          return false;
        }
      }

      //秒杀
      if ([1,2].includes(it.prom_type)) {
        let act_details = null;
        let redis_num = 0;
        let promcardbuynum = 0;
        let qty = it.qty;

        if(it.prom_type==1)
            await getApp().request.promiseGet('/api/ms/flash_sale/getNew/' + store_id + '/' + user_id + '/' + it.prom_id, {}).then(res => {

          if (res.data.code == 0) {
            act_details = res.data.data;
            if (act_details.is_end == 1) {
              wx.showModal({
                title: '提示',
                content: '活动已结束,无法支付,请取消订单！',
                showCancel: false,
              });
              flag = false;
              return false;
            };
            if (act_details.id != it.prom_id) {
              wx.showModal({
                title: '提示',
                content: '活动发生了变化,无法支付,请取消订单,重新购买！',
                showCancel: false,
              });
              flag = false;
              return false;
            };


            var t_now = ut.gettimestamp();
            if (act_details.is_end == 1 || act_details.start_time > t_now || act_details.end_time < t_now) {
              wx.showModal({
                title: '提示',
                content: '活动发生了变化,无法支付,请取消订单,重新购买！',
                showCancel: false,
              });
              flag = false;
              return false;
            }


            //指定门店的控制
            if (act_details.pick_up_lists) {
              var idx0=act_details.pick_up_lists.findIndex(function (e){
                return e.pickup_id==it.pickup_id;
              })
              if(idx0<0){
                getApp().confirmBox(it.service_name + "秒杀活动的门店不可售");
                th.setData({ ser_paying: 0 });
                flag = false;
                return false;
              }
            }

          }
        });
        if(it.prom_type==2)
          await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + it.card_id + "/" + it.prom_id, {}).then(res => {
            if (res.data.code == 0) {
              console.log('当前的t团购活动信息：', res.data.data);
              act_details = res.data.data;
              if (act_details.is_end == 1) {
                wx.showModal({
                  title: '提示',
                  content: '活动已结束,无法支付,请取消订单！',
                  showCancel: false,
                });
                flag = false;
                return false;
              };
              var t_now = ut.gettimestamp();
              if (act_details.is_end == 1 || act_details.start_time > t_now || act_details.end_time < t_now) {
                wx.showModal({
                  title: '提示',
                  content: '活动发生了变化,无法支付,请取消订单,重新购买！',
                  showCancel: false,
                });
                flag = false;
                return false;
              }

              //指定门店的控制
              if (act_details.pick_up_lists) {
                var idx0=act_details.pick_up_lists.findIndex(function (e){
                  return e.pickup_id==it.pickup_id;
                })
                if(idx0<0){
                  getApp().confirmBox(it.service_name + "秒杀活动的门店不可售");
                  th.setData({ ser_paying: 0 });
                  flag = false;
                  return false;
                }
              }

            };
          });

        if(act_details && act_details.buy_limit>0 && flag){
            await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum", {
              data: {
                store_id: store_id,
                user_id: user_id,
                card_id: it.card_id,
                prom_type: it.prom_type,
                prom_id: it.prom_id,
                ispay:1
              }
            }).then(res => {
              if (res.data.code == 0) {
                  promcardbuynum = res.data.data.promcardbuynum;
                  let canBuyNum = act_details.buy_limit - promcardbuynum; // 自己还可购买的数量c

                  if (canBuyNum < qty) {
                    wx.showModal({
                      title: '提示',
                      content: '您已超出活动限购数量,无法支付,请取消订单！',
                      showCancel: false,
                    });
                    flag = false;
                  }
              }
            })
        }

      };
      //-- 拼团 --
      if (it.prom_type == 6 ) {
        let act_details = null;
        let redis_num = 0;
        let promcardbuynum = 0;
        let qty = it.qty;

        await getApp().request.promiseGet("/api/weshop/teamlist/get/" + store_id + "/" + it.prom_id, {}).then(res => {

          if (res.data.code == 0) {

            act_details = res.data.data;

            if (act_details.is_end == 1) {
              wx.showModal({
                title: '提示',
                content: '活动已结束,无法支付,请取消订单！',
                showCancel: false,
              });
              flag = false;
              return false;
            }

            if (act_details.id != it.prom_id) {
              wx.showModal({
                title: '提示',
                content: '活动发生了变化,无法支付,请取消订单,重新购买！',
                showCancel: false,
              });
              flag = false;
              return false;
            }

            var t_now = ut.gettimestamp();
            if (act_details.is_end == 1 || act_details.start_time > t_now || act_details.end_time < t_now) {
              wx.showModal({
                title: '提示',
                content: '活动发生了变化,无法支付,请取消订单,重新购买！',
                showCancel: false,
              });
              flag = false;
              return false;
            }

            //指定门店的控制
            if (act_details.pick_up_lists) {
              var idx0=act_details.pick_up_lists.findIndex(function (e){
                return e.pickup_id==it.pickup_id;
              })
              if(idx0<0){
                getApp().confirmBox(it.service_name + "拼团活动的门店不可售");
                th.setData({ paying: 0 });
                flag = false;
                return false;
              }
            }

          }
        });

        if(act_details.buy_limit>0 && flag){
          await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum", {
            data: {
              store_id: store_id,
              user_id: user_id,
              card_id: it.card_id,
              prom_type: it.prom_type,
              prom_id: it.prom_id,
              ispay:1
            }
          }).then(res => {
            if (res.data.code == 0) {
              console.log('已经购买的数量：', res.data.data);
              promcardbuynum = res.data.data.promcardbuynum;
            }
          })
          let limited = act_details.buy_limit; // 限购数量a
          let canBuyNum = limited - promcardbuynum; // 自己还可购买的数量c

          if (canBuyNum < qty ) {
            wx.showModal({
              title: '提示',
              content: '您已超出活动限购数量,无法支付,请取消订单！',
              showCancel: false,
            });
            flag = false;
          }
        }
        pt_act=act_details;

      }
      //-- 预售 --
      if (it.prom_type == 8 ) {

        let act_details = null;
        let promcardbuynum = 0;
        let qty = it.qty;
        let presell_id=0;

        var url = "/api/weshop/marketing/marketingPresellList/list"
        var rd = {
          store_id: os.stoid,
          presell_id: it.prom_id,
          goods_id: it.card_id
        }
        console.log('获取预售从表')
        //------获取预售从表----------
        await getApp().request.promiseGet(url, {
          data: rd
        }).then(res => {
          if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
            act_details = res.data.data[0];
            presell_id = act_details.presell_id;
          }
        })

        //------获取预售主表----------
        await getApp().request.promiseGet(`/api/weshop/marketing/marketingPresellForm/get/${os.stoid}/${presell_id}`, {}).then(res => {
          if (res.data.code == 0 && res.data.data) {
            var act_data = res.data.data;
            if (act_data.is_end) {
              wx.showToast({ title: "活动已经结束", icon: 'none', duration: 3000 });
              flag = 0;
              return false;
            }
            if (act_data.isuse == 0) {
              wx.showToast({ title: "活动未启用", icon: 'none', duration: 3000 });
              flag = 0;
              return false;
            }

            var err_txt = "活动定金时间已经结束";
            var end_time = act_data.end_time;
            if (act_data.presell_type == 1) {
              err_txt = "活动时间已经结束";
            }
            if (end_time < ut.gettimestamp()) {
              wx.showToast({ title: err_txt, icon: 'none', duration: 3000 });
              flag = 0;
              return false;
            }

            if (act_data.presell_type == 0) {
              end_time = act_data.pay_enddate;
              err_txt = "活动尾款时间已经结束";
            }
            if (end_time < ut.gettimestamp()) {
              wx.showToast({ title: err_txt, icon: 'none', duration: 3000 });
              flag = 0;
              return false;
            }
          }
        })

        if(!flag) {
          th.setData({ ser_paying: 0 });
          return false;
        }

        //-- 判断一下限购的计算 --
        if(act_details.vip_butyqty>0){
          await getApp().request.promiseGet("/api/weshop/recharge/rechargePresell/countBuyGoodsSum", {
            data: {
              store_id: store_id,
              user_id: user_id,
              goods_id: it.card_id,
              prom_id: it.prom_id,
            }
          }).then(res => {
            if (res.data.code == 0) {
               console.log('已经购买的数量：', res.data.data);
               promcardbuynum = res.data.data.sumgoodsnum;
            }
          })
          let limited = act_details.buy_limit; // 限购数量a
          let canBuyNum = limited - promcardbuynum; // 自己还可购买的数量c

          if (canBuyNum < qty ) {
            wx.showModal({
              title: '提示',
              content: '您已超出活动限购数量,无法支付,请取消订单！',
              showCancel: false,
            });
            flag = false;
          }
        }
      }

    }

    if (flag) {

      t_pay.set_pay_url("/api/weshop/order/pay/createRechargeOrder");
      t_pay.pay({
        parentSn: order_sn,
        store_id: store_id
      }, function () {
          th.data.ser_paying=0;
          wx.showToast({
            title: '支付成功',
            icon:'success',
            duration: 2000
          });

          if(pt_act && pt_act.kttype==1){

            //--如果商家团的时候,这个要改,要用服务卡的接口---
            getApp().request.promisePost("/api/weshop/rechargeServicelist/vipAutoTuan", {
              data: {orderSn:order_sn,storeId:os.stoid }
            })
          }

          setTimeout(()=>{
            th.setData({is_get:0})
            th.onShow();
          },500)



      }, function (e) {
        th.setData({ ser_paying: 0 });
        wx.showToast({
          title: e,
          icon: 'none',
          duration: 2000
        });
      })

      // await app.request.promisePost('/api/weshop/order/pay/createRechargeOrder', {
      //   data: {
      //     parentSn: order_sn,
      //     store_id: store_id,
      //   },
      // }).then(res => {
      //   // success: function(res) {
      //   var n = res.data.data;
      //   self.weixinPay(n, function () {
      //     app.showWarning('支付成功');
      //
      //   }, function () {
      //     app.showWarning('支付失败');
      //     // setTimeout(function() {
      //     // 	wx.reLaunch({
      //     // 		url: '/packageA/pages/cardList/cardList',
      //     // 	})
      //     // }, 1000)
      //   });
      //   // }
      // });
    }else {
      th.setData({ ser_paying: 0 });
    }

  },

  //------调起支付框--------
  weixinPay: function (n, success, fail) {
    if (!n) return false;
    // let order_id = item.order_id;

        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("支付成功！");
        "function" == typeof success && success();
        wx.redirectTo({
          url: "/packageG/pages/payment/pay_success/pay_success?card=1&order_id=" + order_id,
        });
      },
      fail: function (n) {
        console.log(n), "requestPayment:fail" == n.errMsg ? getApp().showWarning("支付失败") :
          "requestPayment:fail cancel" == n.errMsg ? getApp().showWarning("您已取消支付") : getApp().showWarning("支付失败：" + n
            .errMsg.substr("requestPayment:fail ".length)),
          "function" == typeof fail && fail();
      }
    });
  },

  // 卡项订单 - 取消订单
  // api/weshop/recharge/update?store_id=&order_id=&order_status=3
  cancle(e) {
    wx.showModal({
      title: '提示',
      content: '确定取消订单吗？',
      success(res) {
        if (res.confirm) {
          console.log('取消订单~');
          let order_id = e.currentTarget.dataset.orderid;
          let order_sn = e.currentTarget.dataset.ordersn;
          app.request.put('/api/weshop/recharge/update', {
            data: {
              store_id: os.stoid,
              order_id: order_id,
              order_sn: order_sn,
              order_status: 3,
            },
            success: function (res) {
              wx.showToast({
                title: '取消成功',
                success: function () {

                  // 这里还可以优化不刷新，后面有时间再优化
                  self.setData({
                    is_no_data2: 0,
                    is_no_more2: 0,
                  });

                  // 这里还可以优化不刷新，后面有时间再优化
                  self.clickTab(e);
                },
              });



              //self.request_list(self.data.currentRequestData);
            },
          })
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  },


  // 卡项订单 - 再来一单
  addCart: function (t) {
    var th = this;
    var ind = t.currentTarget.dataset.openSpecModal_ind;
    var action = t.currentTarget.dataset.action;
    if (!ind) ind = t.currentTarget.dataset.openspecmodal_ind;

    th.setData({
      open_ind_store: ind
    });

    if (!th.data.sto_sele_name) {
      getApp().my_warnning('请选择门店', 1, th, 450);
      return false;
    }


    if (action == "buy") {
      //-------------- 此时操作的数据 ------------
      var newd = {
        id: th.data.data.id,
        goods_num: th.data.goodsInputNum,
        pick_id: th.data.sto_sele_id,
        keyid: th.data.sto_sele_keyid,
      };
      newd['pick_name'] = th.data.sto_sele_name;
      newd['guide_id'] = getApp().globalData.guide_id;
      newd['guide_type'] = 0;
      th.buyNow(newd);
    } else {

      var newd = {
        service_id: th.data.data.id,
        service_sn: th.data.data.service_sn,
        service_name: th.data.data.goods_name,
        goods_num: th.data.goodsInputNum,
        pick_id: th.data.sto_sele_id,
        user_id: oo.user_id,
        store_id: os.stoid,
        money: th.data.data.shop_price
      };
      if (getApp().globalData.guide_id) {
        newd['guide_id'] = getApp().globalData.guide_id;
        newd['guide_type'] = 0;
      }

      //----先看会员在购物车中是否加入了该商品-----
      getApp().request.get("/api/weshop/cartService/page", {
        data: {
          store_id: os.stoid,
          user_id: oo.user_id,
          service_id: th.data.data.id,
          pick_id: th.data.sto_sele_id,
        },
        success: function (re) {

          //-------如果购物车中有相关的数据---------
          if (re.data.data.total > 0) {
            var item = re.data.data.pageData[0];
            var updata = {
              id: item.id,
              goods_num: th.data.goodsInputNum + item.goods_num,
              money: th.data.data.shop_price,
              store_id: os.stoid,
            };

            if (getApp().globalData.guide_id) {
              updata['guide_id'] = getApp().globalData.guide_id;
              updata['guide_type'] = 1;
            }
            getApp().request.put("/api/weshop/cartService/update", {
              data: updata,
              success: function (t) {
                getApp().my_warnning('加入购物车成功', 1, th, 450);
                var c_num = th.data.cartGoodsNum + th.data.goodsInputNum;
                th.setData({
                  cartGoodsNum: c_num
                });
                th.closeSpecModal();
              }
            });
          } else {

            getApp().request.post("/api/weshop/cartService/save", {
              data: newd,
              success: function (t) {
                getApp().my_warnning('加入购物车成功', 1, th, 450);
                var c_num = th.data.cartGoodsNum + th.data.goodsInputNum;
                th.setData({
                  cartGoodsNum: c_num
                });
                th.closeSpecModal();
              }
            });
          }
        }
      });

    }
  },


  //-- 查看物流 --
  go_wuliu:function (e) {
      getApp().go_wuliu(e);
  },

  //优惠促销用户参与次数,is_buy=1，表示只获取支付了的
  async getUserBuyPromNum_pre(prom_id,is_buy) {
    var userInfo = getApp().globalData.userInfo;
    var url = `/api/weshop/ordergoods/getUserBuyPromNum?is_all=1&store_id=${os.stoid}&user_id=${userInfo.user_id}&prom_type=3&prom_id=${prom_id}`;
    if(is_buy){
      url = `/api/weshop/ordergoods/getUserBuyPromNum?store_id=${os.stoid}&user_id=${userInfo.user_id}&prom_type=3&prom_id=${prom_id}`;
    }
    let res = await getApp().request.promiseGet(url, {
      data: {}
    });
    let user_pre_buynum = 0
    if (res.data.code == 0 && res.data.data) {
      user_pre_buynum = res.data.data.userbuynum
    }
    return user_pre_buynum
  },


});