// pages/buy/myOrder_v2/myOrder_v2.js
import Toast from "../../../dist/toast/toast";
import util from "../../../utils/util.js";
var location = require("../../../mybehaviors/location/location");

var app = getApp();
// var WxParse = require('../../../wxParse/wxParse.js');
// var qqmapsdk;

Page({
  behaviors: [location],

  /**
   * 页面的初始数据
   */
  data: {
    plugin_id: "", // 应用市场用来判断请求的接口
    isDomain: false,
    clicktag: 0, // 方式提交订单多次点击
    language: "",
    //不同购买方式
    pre_order_url: "", // 预下单的请求url
    order_url: "", // 提交订单的请求url
    order_other_json: {}, // 每种类型下单的格外的请求数据
    isCartsOrder: false, // 判断是不是购物车下单类型
    options: {}, //路由参数购买方式
    _root_tag: "",
    TAG_ACTION_BUY: "-2", //直接购买
    TAG_ACTION_CART: "-1", //-1购物车结算
    _goodsId: "",
    _optionsId: "",
    _total: 1,
    _cart_ids: [],
    currentAddId: "",
    currentAddress: {},
    //O2O部分
    store_id: 0,
    storeCarts: [],
    store_info: {},
    linkinfo: {
      mobile: "",
      name: "",
    },
    selectedMode: 0,
    selected: 0,
    dispatch: [],

    //优惠券标识
    cup_notice: true,
    isShowCoupon: false, //是否显示优惠券
    defaultAddress: {},
    realname: "", //收件人
    mobile: "",
    address: "",
    order_data: "",
    dispatch_price: 0,
    goods_price: 0,
    price: 0,
    discount_price: 0,
    deduction_price: 0,
    goodsInfo: {},
    //优惠券
    popupCouponSpecs: false,
    checkCouponList: [],
    coupon_size: 0,
    use_coupon_size: 0,
    coupons: [],
    //积分抵扣 其他抵扣
    checkDeductionList: [],
    //个人信息和修改
    myRealname: "",
    myIdcard: "",
    showMyinfo: false,
    showFrom: false,

    currentIndex: "999",
    //是否开启会员权益开关
    isOpenRight: false,
    //是否选择权益商品
    isRightChoose: false,
    //租赁商品标识
    isRent: false,
    //租期
    rentTime: [],
    //可以免租的件数
    rentFree: "",
    //免押件数
    rent_deposit_free: 0,
    //租赁协议
    agreeCon: {},
    //免租件数
    rent_free: 0,
    rentShow: false,
    tenancy: "",
    //留言
    note: {},
    //跨境
    isTaxGoods: false,
    // explain_title: "",
    // explain_content: "",
    //同意租赁协议
    agreement: false,
    agreementShow: false,
    submit_active: true,
    //是否显示支付协议
    AgreementPay: "",
    //同意支付协议
    agreementPay: false,
    //支付协议
    agreementPayShow: false,
    _show_address: false,
    // 发票
    isShowInvoice: true, //71182
    invoiceData: {
      papery_status: "",
      electron_status: "",
    },
    invoice_list: {},

    total_items: [],
    discount_amount_items: [],
    service_fee_items: [],
    //服务费
    service: {},
    isCash: "",
    goodsId: "",
    show1: false,
    isOpenTeam: false, //是否为一键开团
    isJoinTeam: false, //是否为去参团

    point: {
      lat: "",
      lng: "",
    },
    city: "",
    defaultSelfCarry: {},
    diyShow: false,
    orders_goods: {},
    diyform: {
      form_id: "",
      diyform_data_id: "",
      pre_id: "",
    },
    // 门店配送  start +++++++++++++++++++++++++++++++++++
    markers_2: [{
      // 获取返回结果，放到mks数组中
      latitude: "",
      longitude: "",
      iconPath: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", //图标路径
      width: 20,
      height: 25,
      callout: {
        padding: "10rpx",
        borderRadius: "5rpx",
      },
    },],
    polygons_2: [{
      points: [],
      fillColor: "#FF88887F",
      strokeColor: "#FFF",
      strokeWidth: 2,
      zIndex: 1,
    },],
    deliveryScopeShow: false,
    default_member_address: "",
    delivery: {
      longitude: "113.324520",
      latitude: "23.099994",
    },
    delivery_note: "", //门店配送说明
    delivery_area: [
      [116.403322, 39.920255]
    ], // 配送范围经纬度
    locations: [116.403322, 39.920255], //门店经纬度
    // 门店配送  end-------------------------
    integral: "",
    is_region: 0,
    activity_id: "",
    TemplateArray: [],

    orderLocationObj: {
      positioning_success: 0,
      province: "",
      city: ""
    },

    isCueCoupon: false,
    openCueCoupon: false,

    getParams_status: false, //是否已请求接口
    fromStock: "", // 是否是云库存商品

    // 话费慢充
    show_recharge_mobile: "",
    recharge_tips: "",
    recharge_mobile: "",

    // 自定义表单
    hasGoodOpenDF: false,
    // 聚合cps
    iscps: false,
    cpstype: 2,
    cpsTxt: "",
    // end
    storeSearchBtn: {}, //门店搜索插件自定义下单页按钮

    service_fee: [], //服务费、运费说明

    //上门安装 插件名：live-install
    minDate: new Date().getTime(),
    installDateShow: false,
    installDate: null, //预约时间(10位时间戳)
    installDateText: "",
    install_comment: "", //安装备注，不要超过120个字符
    location: {}, //定位信息
    showLocation: false,
    showInstallPop: false,
    default_deduction: 0, //判断积分抵扣默认是否开启

    showPage: true, //为了解决跳转的时候显示自提点的bug #64574
    delivery_amount: 0, //门店起送金额

    phone_bill_pro_goods: false, //是否话费充值pro版，根据url是否有mobile来判断

    clickMiniTemplate: false, //判断是否已经点击订阅订单
    // 供应商定位和经纬度
    // supp_adress:'',
    supp_point: {
      lng: '',
      lat: '',
      address: ''
    },
    recommend_goods: [], //满额包邮推荐商品
    // 电费充值规格组合id
    electricity_Guide: "",
    electricity: false,
    // 充值户号
    eleUser: [],
    ele_no_showAdress: false,
    // 二开页面设置插件-胜天半子#79514
    sexSelect: '1',
    showArea: false,
    // 使用微信地址，页面设置插件
    use_wechat_address: false,
    design_info: {
      cityName: "",
      countyName: "",
      detailInfo: "",
      provinceName: "",
      telNumber: "",
      userName: "",
    },

    ferightExplainPop: false,
    freightExplain: {},

    o2odeliverName: "自提点", //门店自提点自定义名称
    o2oSelfCarry: {},
    deliveryTimeShow: false,
    costSpecShow: false,
    selectCommunityShow: false,
    serviceRegionShow: false,

    //同城配送
    cityDelivery: null,
    cityDelivery_community: {},
    cityDelivery_community_id: 0,
    cityDelivery_deliveryTime: {},
    yz_subscribe_disabled: false,

    //分时预约商品
    reserve_tel_name: '',
    reserve_mobile: '',
    reserve_order: null,
    reserve_obj_text: "预约人员",
    plugin_setting: '', //插件信息 获取默认地址
    camilo_resources_coupon_type: '', //插件id：140 卡券商品 卡券商品 1直冲2卡券
    recharge_number: '',

    addressList_caller:"",  //地址组件调用着，识别是地址调用还是发票插件调用
    //油卡充值
    oil_mobile:"",
    oil_account:"",
    oil_pre_id:"",

    consigneeName: '', // 自提点提货人自定义
    consigneeMobile: '' // 自提点提货人手机号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('=== 调试中... ===',options);
    wx.getStorage({
      key: "yz_basic_info",
      success: (res) => {
        this.setData({
          reserve_obj_text: res.data.lang.reserve_simple.reserve_obj || '预约人员',
        });
      },
    });
    this.handleQueryData(options);
    let yz_basic_info = wx.getStorageSync('yz_basic_info');
    this.setData({
      vip_show:yz_basic_info.globalParameter.vip_show?yz_basic_info.globalParameter.vip_show:false
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });

    const value = wx.getStorageSync("integral");
    const loveName = wx.getStorageSync('yz_basic_info') ? wx.getStorageSync('yz_basic_info').love : '';
    if (value) {
      this.setData({
        integral: value,
        love_name: loveName
      });
    }
    let plugin_setting = wx.getStorageSync("yz_basic_info").plugin_setting || '';
    this.setData({
      plugin_setting
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.submit_active = true;
    this.setData({
      showPage: true,
    });
    if (this.data.selected == 10) {
      // 供应商订单配送自动定位
      this._getLocation((res) => {
        let point = app.qqMapTransBMap(parseFloat(res.location.lng), parseFloat(res.location.lat));
        this.setData({
          'supp_point.lng': point.lng,
          'supp_point.lat': point.lat,
          'supp_point.address': res.address
        });
      });
    }
  },
  tolocation() {
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=suppligoodsOrde',
    });
  },
  setFreightExplainPop() {
    this.setData({
      ferightExplainPop: !this.data.ferightExplainPop
    });
  },
  getWxAdress() {
    wx.chooseAddress({
      success: (res) => {
        console.log(res, 'sssss');
        let e = res;
        this.setData({
          userAdress: `${e.provinceName} ${e.cityName} ${e.countyName}`,
          design_address: `${e.detailInfo}`,
          design_info: e
        });
        this._requestByAddress()
      }
    });
  },
  async handleQueryData(options) {
    //不同购买方式
    this.setData({
      options: options,
    });

    if (options.tag) {
      this.setData({
        _root_tag: options.tag,
      });
    }
    let userLocationFlag = await this.checkAlbum("scope.userLocation");
    console.log("userLocationFlag", userLocationFlag);
    if (!userLocationFlag) {
      return app.tips("获取位置失败，请重新进入后授权");
    }

    if (!app.globalData.qqmapkey) {
      app._getTemplate().then((res) => {
        this.getCurrentOrderLocation();
      });
    } else {
      this.getCurrentOrderLocation();
    }

    if (options.fromStock && options.fromStock != '') {
      this.setData({
        fromStock: options.fromStock,
      });
    }

    // 聚合cps
    if (options.iscps) {
      this.setData({
        _root_tag: "cps",
        iscps: options.iscps,
      });
    }
    if (options.mobile) {
      this.setData({
        phone_bill_pro_goods: true,
        recharge_mobile: options.mobile
      });
    }
    if (options.cpstype) {
      this.setData({
        cpstype: options.cpstype,
      });
    }
    //end

    if (options.activity_id) {
      this.setData({
        activity_id: options.activity_id,
      });
    }

    if (options.ind) {
      this.setData({
        ind: options.ind,
      });
    }

    if (options.reserve_order) {
      this.setData({
        reserve_order: JSON.parse(options.reserve_order)
      });
    }

    //是否为一键开团（拼团）
    let isOpenTeam = !app._isTextEmpty(options.level_id);
    //是否为去参团（拼团）
    let isJoinTeam = !app._isTextEmpty(options.team_id);
    this.setData({
      isOpenTeam,
      isJoinTeam,
    });

    if (options.changeSelfCarry) {
      let changeSelfCarry = JSON.parse(options.changeSelfCarry);
      if (options.ind == 12) {
        this.setData({
          o2oSelfCarry: changeSelfCarry,
        });
      } else {
        this.setData({
          defaultSelfCarry: changeSelfCarry,
        });
      }
    }

    //如果Storage里有保存自提点的信息则自动获取填写
    let _zdtInfo = wx.getStorageSync("selfCarryInfo");
    if (_zdtInfo) {
      _zdtInfo = JSON.parse(_zdtInfo);
      this.setData({
        "linkinfo.name": _zdtInfo.distributionUserName || "",
        "linkinfo.mobile": _zdtInfo.distributionUserMobile || "",
      });
    }

    // 设置主要参数
    this.setData({
      _goodsId: options.goodsId || "",
      _optionsId: options.optionsId || "",
      _total: options.total || 1,
    });

    if (options.cart_ids && options.cart_ids != 'undefined') {
      this.setData({
        _cart_ids: options.cart_ids ? JSON.parse(options.cart_ids) : [],
      });
    }

    // if (this.data._root_tag == this.data.TAG_ACTION_BUY || this.data._root_tag == "store") {
      if (options.store_id && options.store_id != 'undefined') {
        // 门店拓客
        this.setData({
          store_id: options.store_id,
        });
      }
    // }

    if (options.electricity && options.electricity == "electricity") {
      this.setData({
        electricity: true
      });
    }

    if(options.oil_account && options.oil_mobile){
      this.setData({
        oil_account:options.oil_account,
        oil_mobile:options.oil_mobile
      });
    }
    // 置换亿栈债务人id
    if(options.debtId){
      this.setData({
        debtId:options.debtId
      })
    }

    if (this.data._root_tag != "POrder" && this.data._root_tag != "store") {
      //第请求接口获取配送方式后，取默认第一个的dispatch_type_id再请求预下单接口;  挂单POrder走固定的配送方式
      this.getDispatchMethod();
    } else {
      this.handleBuy();
    }
  },
  // 获取配送方式
  getDispatchMethod(cart_ids) {
    if (this.data._root_tag == "communityBuy") {
      // 社区团购直接设置，走配送方式接口返回为空，前端自定义，自提点不可更换
      let dispatch = [{ dispatch_type_id: 8, name: "自提点" }];
      this.setData({
        dispatch: dispatch,
        selected: 8
      });
      this.handleBuy();
      return;
    }
    let json = {
      goods_id: this.data._goodsId ? this.data._goodsId.toString() : "",
      cart_ids: this.data._cart_ids.toString() || cart_ids,
      store_id: this.data.options.store_id || this.data.options.groupStoreID,
      model: "",
    };
    if (this.data._root_tag == "store") {
      json.model = "store";
    }
    if (this.data._root_tag == "warehouse") {
      let _goods_ids = [];
      JSON.parse(this.options.goodCollection).forEach(item => {
        _goods_ids.push(item.goods_id);
      });
      json.goods_ids = JSON.stringify(_goods_ids);
    }

    let urlStr = app.getNetAddresss("memberCart.dispatch-type.index");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if(!app._isTextEmpty(this.data.debtId)){
            // 置换亿栈地址默认为快递
            this.setData({
              dispatch:[{dispatch_type_id: 1,name: "快递"}],
              selected:res.data && res.data.length > 0 ? res.data[0].dispatch_type_id : 0
            })
          }else{
            this.setData({
              dispatch: res.data,
              selected: res.data && res.data.length > 0 ? res.data[0].dispatch_type_id : 0, //默认第一
            });
            this.data.dispatch.forEach((items, i) => {
              if (items.dispatch_type_id == 8) {
                console.log("有自提点配送方式，请求定位获取自提点列表");
                if (this.data.ind) {
                  this.setData({
                    selected: this.data.ind,
                    selectedMode: i,
                    ind: false,
                  });
                }
              } else if (items.dispatch_type_id == 12) {
                //从门店自提点列表选择后来
                if (this.data.ind == 12 && this.data.o2oSelfCarry && this.data.o2oSelfCarry.id) {
                  this.setData({
                    selected: 12,
                    selectedMode: i
                  });
                }
              }
            });
          }
          if (this.data._root_tag == "store") {
            this._getStoreCartBuy(this.data.storeCarts);
          } else {
            this.handleBuy();
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  handleBuy(is_again) {
    // is_again判断是否重新请求数据  选择地址后是1   优惠券或者抵扣是2
    switch (this.data._root_tag) {
    case this.data.TAG_ACTION_BUY:
    case "appointment_goods":
    case "yun_sign_goods":
    case "yunqian_api":
    case "cps":
    case "starGroup":
    case "blindBox":
    case "fromExchange":
    case "newRetail":
    case "auction":
    case "zhpGroup":
    case "o2oDeposit":
      // 通常是单个商品的预下单
      if (!is_again) {
        if (this.data.options.store_id) {
          // 门店拓客  门店预约
          this._initStore("is_activity");
        } else if (this.data.options.groupStoreID && this.data.options.groupStoreID != 0 && this.data.options.groupStoreID != "undefined") {
          //门店拼团
          this._initStore();
        }
        // 只为了获取配送方式
      } else if (this.data._root_tag == "fromExchange" && is_again === "2") {
        //会员中心-兑换中心-去兑换（商城商品）
        this._getDataActionBuy(0);
        return;
      }
      this._getDataActionBuy(); // 直接购买
      break;
    case this.data.TAG_ACTION_CART: // 商城购物车结算
    case "packagBuy": // 商品套餐
    case "-10": // 一口价
    case "communityBuy": // 社区团购
      this.data.isCartsOrder = true;
      // 通常是购物车的预下单
      this._getDataActionCart();
      break;
    case "store":
      this.data.isCartsOrder = true;
      if (!is_again) {
        // 门店购物车购买
        if (this.data.options.isCash == 1) {
          // 门店过期(续费 isCash =='1')商品下单
          this.getCashGood();
        } else {
          this._initStore();
        }
      } else {
        this._getDataActionStoreCart(); // 门店结算
      }
      break;
    case "rentCartBuy":
    case "rentBuy":
      if (!is_again) {
        // 租赁购物车或租赁预下单
        this.setData({
          currentIndex: "999",
          isRent: true,
        });

        this._getRentDataActionCart([], []);
        this._getRentTimeList();
        this._judgeIsRight();
      } else {
        this._rentGoodBuy();
      }
      break;
    case "POrder":
      //挂单商品
      this.getPendingOrder_type(); //批发区下单页类型判断,即导航栏判断
      break;
    default:
      this._getDataActionBuy(); // 直接购买
    }
  },
  // 处理单个商品的预下单 设置预下单链接  提交订单链接  类型额外的数据
  handleDataActionBuyUrl(json, tag) {
    if (this.data.isRent) {
      // 租赁
      this.data.order_url = "plugin.lease-toy.api.order.create";
    } else if (this.data.fromStock == 1 || this.data.fromStock == 2) {
      //云库存
      this.data.pre_order_url = app.getNetAddresss("plugin.agency.api.goods-buy.index");
      this.data.order_url = "plugin.agency.api.create.index";
      let agencySaleman = this.selectComponent("#agencySaleman");
      if (this.data.fromStock == 2) {
        this.data.order_other_json = {
          is_retail: true, //云库存零售传值
          salesman_uid: (agencySaleman && agencySaleman.data.self_member_id) || "" //销售员id
        };
      }
    } else if (this.data.isOpenTeam || this.data.isJoinTeam) {
      // 拼团
      this.data.order_other_json = {
        option_level_id: this.options.option_level_id, //规格层级id
      };

      if (this.data.isOpenTeam) {
        this.data.order_other_json.level_id = this.options.level_id; //一键开团 拼团层级id
        this.data.pre_order_url = "plugin.fight-groups.frontend.controllers.team.pre-open-team";
      } else if (this.data.isJoinTeam) {
        this.data.order_other_json.team_id = this.options.team_id; //一键参团 拼团层级id
        this.data.pre_order_url = "plugin.fight-groups.frontend.controllers.team.pre-join-team";
      }

      this.data.order_url = "plugin.fight-groups.frontend.controllers.create.index";

      if (this.options.groupStoreID && this.options.groupStoreID != 0 && this.options.groupStoreID != "undefined") {
        this.data.order_other_json.store_id = this.options.groupStoreID;
        //门店拼团
        this.data.pre_order_url = this.data.isOpenTeam ? "plugin.fight-groups.frontend.store.frontend-team.pre-open-team" : "plugin.fight-groups.frontend.store.frontend-team.pre-join-team";
        this.data.order_url = "plugin.fight-groups.frontend.store.create.index";
      }
    } else if (this.options.tag == "appointment_goods") {
      this.data.order_url = "plugin.appointment.frontend.order.create";
    } else if (this.options.type == "groupBuy_open" || this.options.type == "groupBuy_join") {
      this.data.order_other_json = {
        at_id: this.options.at_id, //活动ID
        leader_id: this.options.leader_id || 0, //团长ID
      };
      delete json.option_id;
      this.data.pre_order_url = this.options.type == "groupBuy_open" ? "plugin.together-purchase.api.team.preOpenTeam" : "plugin.together-purchase.api.team.preJoinTeam";

      this.data.order_url = "plugin.together-purchase.api.create.index";
    } else if (this.options.type == "grabGroup_open" || this.options.type == "grabGroup_join") {
      //抢团
      this.data.order_other_json = {
        at_id: this.options.at_id, //活动ID
        leader_id: this.options.leader_id || 0, //团长ID
        snatch_option_id: this.data._optionsId,
      };
      json.option_id = 0;
      this.data.pre_order_url = this.options.type == "grabGroup_open" ? "plugin.snatch-regiment.api.team.preOpenTeam" : "plugin.snatch-regiment.api.team.preJoinTeam";

      this.data.order_url = "plugin.snatch-regiment.api.create.index";
    } else if (this.data._root_tag == "POrder") {
      this.data.order_other_json = {
        pending_order_type: this.data.selected, //批发订单使用类型
      };
      this.data.pre_order_url = "plugin.pending-order.frontend.goods-buy.index";

      this.data.order_url = "plugin.pending-order.frontend.create.index";
    } else if (this.data._root_tag == "o2oDeposit") {
      //门店定金团
      this.data.order_other_json = {
        store_id: this.options.store_id || 0, //门店ID
      };
      this.data.pre_order_url = "plugin.deposit-ladder.frontend.store.activity-buy";
    } else if (this.options.store_id) {
      if (this.data._root_tag == "reserve") {
        this.data.order_other_json = {
          date_id: this.options.date_id,
          store_id: this.options.store_id,
          goods_id: this.options.goodsId
        };
        if (tag == 'order') {
          this.data.order_other_json.date_id = this.options.date_id;
        }
        this.data.pre_order_url = "plugin.store-reserve.frontend.GoodsBuy.index";
        this.data.order_url = "plugin.store-reserve.frontend.create.index";
      } else {
        //门店拓客
        this.data.order_other_json = {
          store_id: this.options.store_id || 0, //门店ID
        };
        if (tag === "order") {
          this.data.order_other_json.mobile = this.data.linkinfo.mobile;
          this.data.order_other_json.realname = this.data.linkinfo.name;
          this.data.order_other_json.cart_ids = [];
        }

        this.data.pre_order_url = "plugin.store-cashier.frontend.store.goods-buy";
      }
      // 走门店下单
    } else if (this.options.type == "starGroup") {
      //星拼乐
      this.data.order_other_json = {
        at_id: this.options.at_id, //活动ID
        leader_id: this.options.leader_id || 0, //团ID
        goods_data: {
          goods_id: this.data._goodsId,
          total: this.options.total,
          option_id: this.options.option_id,
        },
      };
      this.data.pre_order_url = "plugin.star-spell.frontend.team.joinTeam";

      this.data.order_url = "plugin.star-spell.frontend.create.index";
    } else if (this.data._root_tag == "blindBox") {
      this.data.order_other_json = {
        activity_id: this.data.activity_id, //活动ID
        goods_id: this.data._goodsId,
      };
      this.data.pre_order_url = "plugin.blind-box.api.buy";

      this.data.order_url = "plugin.blind-box.api.create";
    } else if (this.data._root_tag == "fromExchange") {
      //会员中心-兑换中心
      if (this.options.store_id && this.options.store_id != "undefined") {
        this.data.order_other_json.store_id = this.options.store_id;
        this.data.pre_order_url = "plugin.store-cashier.frontend.store.exchange-center";
      } else {
        this.data.pre_order_url = "coupon.exchange-center.exchange-buy";
      }
    } else if (this.options.tag == "newRetail") {
      //新零售 0-自由零售 1-成为代理商订单 2-自由发货 3-线上零售 4-进货订单 5-销售代理套餐订单
      this.data.order_other_json = {
        retail_state: Number(this.options.retailState),
        level_id: Number(this.options.NRLevelId) || 0, //等级id
        sales_id: Number(this.options.sales_id) || 0, //记录id
      };
      // if (this.options.retailState == 2) {
      //   this.data.order_other_json.goods = JSON.parse(this.options.goods) || []; // 自由发货
      // }
      this.data.pre_order_url = this.newRetailApi(this.options.retailState);

      if (Number(this.options.retailState) == 0) {
        this.data.order_url = "plugin.new-retail.frontend.create.ordinary"; // 自由发货
      } else {
        this.data.order_url = "plugin.new-retail.frontend.create.index";
      }
    } else if (this.data._root_tag == "auction") {
      //拍卖商品
      this.data.order_other_json = {
        fixed_price: this.data.options.fixed_price,
        acution_sn: this.data.options.acution_sn,
      };
      this.data.pre_order_url = "plugin.auction.api.goods-buy";

      this.data.order_url = "plugin.auction.api.order-create";
    } else if (this.data._root_tag == "zhpGroup") {
      this.data.pre_order_url = "plugin.zhp-group-lottery.frontend.goods.get-goods-Info";
      json.option_id = this.data._optionsId ? this.data._optionsId : '0';
      this.data.order_other_json = {
        activity_id: this.data.activity_id,
      };
      this.data.order_url = "plugin.zhp-group-lottery.frontend.order.index";
    } else if (this.data._root_tag == "groupWork") {
      this.data.order_other_json = {
        alliance_detail_id: this.data.options.alliance_detail_id,
        activity_option_id: this.data.options.activity_option_id
      };
      this.data.pre_order_url = "plugin.group-work.frontend.modules.order.controllers.buy.index";
      this.data.order_url = "plugin.group-work.frontend.modules.order.controllers.create.index";
    } else if (this.data._root_tag == "warehouse") {
      this.data.order_other_json = {
        goods: this.options.goodCollection
      };
      this.data.pre_order_url = "plugin.warehouse.frontend.controllers.takeDelivery.goods-buy";
      this.data.order_url = "plugin.warehouse.frontend.controllers.takeDelivery.order-create";
    }else if(!app._isTextEmpty(this.data.debtId)){
      this.data.order_other_json = {
        debtor_id: this.data.options.debtId
      };
      this.data.pre_order_url = "plugin.debt-shop.frontend.goods-buy";
      this.data.order_url = "plugin.debt-shop.frontend.create";
    }

    if (this.data.reserve_order != null) {
      this.data.order_url = "plugin.reserve-simple.frontend.order.create";
      let {
        service_id,
        obj_id,
        begin_time
      } = this.data.reserve_order;
      let customer_name = this.data.reserve_tel_name;
      let customer_tel = this.data.reserve_mobile;
      json.reserve_order = {
        service_id,
        obj_id,
        begin_time,
        customer_name,
        customer_tel
      };
      json.dispatch_type_id = 0;
    }

    if (this.options.electricity == "electricity") {
      this.data.order_other_json.account_id = this.options.account_id;
    }

    if (!this.data.pre_order_url) {
      this.data.pre_order_url = "order.goods-buy";
    }

    if (!this.data.order_url) {
      if (this.data.iscps) {
        // 如果是聚合cps的商品走立即购买换这个接口
        this.data.order_url = "plugin.aggregation-cps.api.create-order";
      } else {
        this.data.order_url = "order.create";
      }
    }

    if (this.options.merchant_meeting) {
      //线下招商会商品下单，多传一个活动id
      this.data.order_other_json.merchant_meeting = this.options.merchant_meeting;
    }

    if (this.data.default_deduction != 0) {
      // 默认积分抵扣
      json.no_deduction_ids = this.data.default_deduction;
    }

    if (this.data.cityDelivery && this.data.cityDelivery.future_state == 1) {
      if (this.data.cityDelivery_deliveryTime.start_time && this.data.cityDelivery_deliveryTime.end_time) {
        json.expect_start_time = this.data.cityDelivery_deliveryTime.start_time;
        json.expect_end_time = this.data.cityDelivery_deliveryTime.end_time;
      }
    }
    if (this.data.use_wechat_address && (this.data.selected == 1 || this.data.selected == 0)) {
      // 只用于快递，并且开启了使用微信地址
      let usejson = {
        address: this.data.design_address || "",
        city: this.data.design_info.cityName,
        district: this.data.design_info.countyName,
        id: "",
        isdefault: "",
        latitude: "",
        longitude: "",
        mobile: this.data.design_info.telNumber,
        province: this.data.design_info.provinceName,
        street: "",
        uid: "",
        uniacid: "",
        username: this.data.design_info.userName,
        zipcode: "",
      };
      // 没有选择微信地址的时候，是整个adress都为空
      json.address = usejson.address?encodeURIComponent(JSON.stringify(usejson)):[];
    }
    return Object.assign(json, this.data.order_other_json);
  },
  // 处理购物车的预下单 设置预下单链接  提交订单链接  类型额外的数据
  handleDataActionCartUrl(json, tag) {
    if (this.data._root_tag == "communityBuy") {
      //社区团购
      this.data.pre_order_url = "plugin.package-deliver.frontend.cartBuy.index";
      this.data.order_other_json = {
        dispatch_type_id: 8,
        package_deliver_id: this.options.package_deliver_id,
        group_id: this.options.group_id,
      };

      this.data.order_url = "plugin.package-deliver.frontend.create.index";
    } else if (this.data._root_tag == "-10") {
      // 一口价下单
      this.data.pre_order_url = "plugin.pack-fixed-price.api.cart-buy.index";
      if (tag === "order") {
        this.data.order_other_json.cart_ids = JSON.stringify(this.data._cart_ids);
      }

      this.data.order_url = "plugin.pack-fixed-price.api.create.index";
    }

    if (this.data._root_tag == "packagBuy") {
      let packagJson = JSON.parse(this.data.options.packagJson);
      this.data.order_other_json = {
        package_id: packagJson.package_id,
        goods: JSON.stringify(packagJson.goods_list),
      };
      console.log(this.data.order_other_json, 963);
      this.data.pre_order_url = "plugin.goods-package.frontend.package.package-buy.index";
    }

    if (tag === "order" && this.data._root_tag != "-10" && this.data._root_tag != "packagBuy") {
      // 购物车下单需要购物车id
      this.data.order_other_json.cart_ids = JSON.stringify(this.data._cart_ids);
    }

    if (!this.data.pre_order_url) {
      this.data.pre_order_url = "order.cart-buy";
    }

    if (!this.data.order_url) {
      this.data.order_url = "order.create";
    }

    if (this.data.default_deduction != 0) {
      // 默认积分抵扣
      json.no_deduction_ids = this.data.default_deduction;
    }
    return Object.assign(json, this.data.order_other_json);
  },

  newRetailApi(states) {
    let state = Number(states);
    //新零售 0-自由零售 1-成为代理商订单 2-自由发货 3-线上零售 4-进货订单 5-销售代理套餐订单c
    if (state == 0) {
      return "plugin.new-retail.frontend.order.ordinaryPay";
    } else if (state == 1) {
      return "plugin.new-retail.frontend.order.purchaseRetailGoods";
    } else if (state == 2) {
      return "plugin.new-retail.frontend.order.freeSend";
    } else if (state == 3) {
      return "plugin.new-retail.frontend.order.retailCodePay";
    } else if (state == 4) {
      return "plugin.new-retail.frontend.order.purchaseStock";
    } else if (state == 5) {
      return "plugin.new-retail.frontend.order.retailCodePay";
    }
  },

  setPopShow(evt) {
    let name = evt.currentTarget.dataset.name;
    this.setData({
      [name]: !this.data[name]
    });
  },

  setInstallDateShow() {
    this.setData({
      installDateShow: !this.data.installDateShow,
    });
  },
  bindInstallDateChange(e) {
    this.setInstallDateShow();
    let val = e.detail;
    this.setData({
      installDate: parseInt(val / 1000),
      installDateText: util.formatTime(new Date(val)),
    });
  },
  // 门店配送-查看配送范围
  showDeliveryMap() {
    this.setData({
      deliveryScopeShow: true,
    });
  },
  showLocationPop() {
    this.setData({
      showInstallPop: !this.data.showInstallPop,
    });
  },
  deliveryScopeShowClose() {
    this.setData({
      deliveryScopeShow: false,
    });
  },
  confirmLocation(e) {
    this.setData({
      "location.latitude": e.detail.lat,
      "location.longitude": e.detail.lng,
      "location.address": e.detail.address,
    });
    this.showLocationPop();
  },
  _checkTaxGoods(data) {
    if (data && data.status) {
      //显示个人信息
      this.setData({
        showMyinfo: data.status,
      });
      this.data.isTaxGoods = true;
    } else {
      this.data.isTaxGoods = false;
      this.setData({
        showMyinfo: false,
      });
      //隐藏个人信息
    }
  },
  _getMemberInfo(data) {
    this.setData({
      myRealname: data.realname,
      myIdcard: data.idcard,
    });
  },
  // _getExplain(data) {
  //   this.data.explain_title = data.explain_title;
  //   this.data.explain_content = data.explain_content;
  // },
  //保税真实信息添加
  alertMyInfo() {
    this.setData({
      showFrom: true,
    });
  },
  confirmFrom(e) {
    this.setData({
      myRealname:e.detail.name,
      myIdcard:e.detail.card,
      showFrom: e.detail.status,
    });
  },
  //更换自提点
  gotochangeSelfCarry() {
    let that = this;
    //保存自提点信息到本地，任务编号: 35632
    let _memberInfoes = {
      distributionUserName: this.data.linkinfo.name ? this.data.linkinfo.name : "",
      distributionUserMobile: this.data.linkinfo.mobile ? this.data.linkinfo.mobile : "",
    };
    try {
      wx.setStorageSync("selfCarryInfo", JSON.stringify(_memberInfoes));
    } catch (e) {
      console.log(e);
    }

    let url =
      "/packageC/selfCarry/selfCarry_info/selfCarry_info?tag=" +
      that.data.options.tag +
      "&goodsId=" +
      that.data.options.goodsId +
      "&cart_ids=" +
      that.data.options.cart_ids +
      "&optionsId=" +
      that.data.options.optionsId +
      "&total=" +
      that.data.options.total +
      "&goods=" +
      JSON.stringify(this._assembleGoods()) +
      "&ind=" +
      that.data.selected;

    console.log(that.data.isOpenTeam, "that.data.isOpenTeam");
    if (that.data.isOpenTeam) {
      url = url + "&level_id=" + that.options.level_id + "&option_level_id=" + that.options.option_level_id;
    } else if (that.data.isJoinTeam) {
      url = url + "&team_id=" + that.options.team_id + "&option_level_id=" + that.options.option_level_id;
    }

    if (this.data._root_tag == "warehouse") {
      // 圈仓
      url = url + "&goodCollection=" + this.options.goodCollection;
    }

    if (this.options.store_id) {
      // 门店id
      url = url + "&store_id=" + this.options.store_id;
    }

    wx.redirectTo({
      url: url,
    });
  },

  // 切换配送方式
  setDispatch(e) {
    let title = e.detail.title;
    this.data.dispatch.forEach((items) => {
      if (items.name == title) {
        this.setData({
          selected: items.dispatch_type_id,
          selectedMode: e.detail.index,
        });
      }
    });
    if (this.data.selected == 10) {
      // 供应商订单配送自动定位
      this._getLocation((res) => {
        let point = app.qqMapTransBMap(parseFloat(res.location.lng), parseFloat(res.location.lat));
        this.setData({
          'supp_point.lng': point.lng,
          'supp_point.lat': point.lat,
          'supp_point.address': res.address
        });
      });
    }
    if (this.data.selected == "11") {
      //selected = 11 同城配送
      this.getDeliverySetting();
    } else {
      this._requestByAddress();
    }

  },

  getDeliverySetting() {
    if (this.data.cityDelivery != null) {
      this._requestByAddress();
      return;
    }
    let urlStr = app.getNetAddresss("plugin.city-delivery.frontend.order.getDeliverySetting");
    app._postNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let changeData = {};
          changeData.cityDelivery = res.data;

          if (res.data.fence_setting) {
            changeData["markers_2[0].longitude"] = res.data.fence_setting.store_longitude;
            changeData["markers_2[0].latitude"] = res.data.fence_setting.store_latitude;
            changeData["delivery.longitude"] = res.data.fence_setting.store_longitude;
            changeData["delivery.latitude"] = res.data.fence_setting.store_latitude;
            if (res.data.fence_setting.delivery_area) {
              changeData["polygons_2[0].points"] = res.data.fence_setting.delivery_area.map((item) => {
                let o = {};
                o.longitude = item[0];
                o.latitude = item[1];
                return o;
              });
            }
          }
          changeData.need_lat = 1;

          this.data.order_data.forEach((item) => {
            // *1 只是为了转数字类型
            if ((res.data.min_amount * 1) > (item.goods_price * 1)) {
              changeData.yz_subscribe_disabled = true; //商品价格不够最低配送，按钮灰色不能提交
            }
          });
          this.setData(changeData);
          this.selectComponent(`.deliveryTime`).setListData(res.data.time_setting, res.data.default_choose);
          if (!res.data.default_choose) {
            this._requestByAddress();
          }
        }
      }
    });
  },

  //直接购买
  _getDataActionBuy(is_exchange) {
    let that = this;
    let _json = {
      goods_id: this.data._goodsId,
      total: this.data._total,
      option_id: this.data._optionsId || '0',
      member_coupon_ids: this._assembleCoupons(),
      orders: JSON.stringify(this._assembleDeduction()),
      address: encodeURIComponent(JSON.stringify(this.data.currentAddress)), //encodeURIComponent为了解决地址#号问题
      dispatch_type_id: this.data.selected,
      mark: this.data.options.mark ? this.data.options.mark : 0,
    };

    //自提点开启
    if (this.data.selected == 8) {
      _json.package_deliver_id = this.data.defaultSelfCarry.id;
    }
    if (this.data.selected == 12) {
      // 门店自提点
      _json.package_deliver_id = this.data.o2oSelfCarry.id;
    }

    if (this.data._root_tag == "fromExchange") {
      //兑换中心商品
      _json.data = JSON.parse(this.data.options.exchangeData);
      _json.is_exchange = is_exchange == 0 ? 0 : 1;
    }

    if (this.options.tag == "newRetail" && this.options.retailState == 2) {
      _json.goods = JSON.parse(this.options.goods) || []; // 自由发货
    }
    _json = this.handleDataActionBuyUrl(_json);
    let urlStr = app.getNetAddresss(this.data.pre_order_url);
    wx.showLoading({
      title: "加载中",
      icon: "none",
      duration: 1500,
    });
    if (this.data.clicktag == 0) {
      this.setData({
        clicktag: 1,
      });
      app._postNetWork({
        url: urlStr,
        data: _json,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(that.options, res, 'ssawwww');
            if (that.options.tag == "reserve") {
              // 门店预约商品
              if (res.data.reserve_date) {
                this.setData({
                  reserveDate: res.data.reserve_date.date
                });
              }
              if (res.data.reserve_deduction) {
                this.setData({
                  reserve_deduction: res.data.reserve_deduction
                });
              }
              if (res.data.reserve_deduction_love) {
                this.setData({
                  reserve_deduction_love: res.data.reserve_deduction_love
                });
              }
            }
            if (that.options.type == "groupBuy_open" || that.options.type == "groupBuy_join") {
              that.setData({
                isGetAgreementPay: true,
                AgreementPay: that.data.goodsInfo.together_purchase_agreement ? that.data.goodsInfo.together_purchase_agreement : "",
              });
            }

            that.setData({
              goodsInfo: res.data,
              cup_notice: true,
              diyShow: false,
            });
            that._setViewData(res.data); //设置界面
            if (this.data._root_tag == "fromExchange") {
              //兑换中心
              that.defaultSelectCoupon(res.data.discount.member_coupons); //设置默认优惠券信息
            } else if (res.data.discount) {
              that._initCoupon(res.data.discount); //设置优惠券信息
            }
          } else {
            wx.showModal({
              title: "提示",
              content: res.msg,
              success(res) {
                if (res.confirm) {
                  try {
                    const orderErrReturnUrl = wx.getStorageSync('orderErrReturnUrl')
                    if (orderErrReturnUrl) {
                      wx.redirectTo({
                        url: orderErrReturnUrl
                      });
                    } else{
                      wx.navigateBack({
                        delta: 1
                      });
                    }
                  } catch (e) {
                    wx.navigateBack({
                      delta: 1
                    });
                  } 
                } else if (res.cancel) {
                  wx.navigateBack({
                    delta: 1
                  });
                }
              },
            });
          }
          setTimeout(() => {
            that.setData({
              cup_notice: true,
              clicktag: 0,
            });
            wx.hideLoading();
          }, 1000);
        },
        fail: (res) => {
          console.log(res);
        },
      });
    }
  },
  //购物车结算
  _getDataActionCart() {
    let that = this;
    let _json = {
      cart_ids: this.data._cart_ids.toString(),
      member_coupon_ids: this._assembleCoupons(),
      orders: JSON.stringify(this._assembleDeduction()),
      address: encodeURIComponent(JSON.stringify(this.data.currentAddress)),
      dispatch_type_id: this.data.selected,
    };
    if (this.data.selected == 8) {
      _json.package_deliver_id = this.data.defaultSelfCarry.id;
    }
    if (this.data.selected == 12) {
      // 门店自提点
      _json.package_deliver_id = this.data.o2oSelfCarry.id;
    }

    _json = this.handleDataActionCartUrl(_json);
    let urlStr = app.getNetAddresss(this.data.pre_order_url);
    app._getNetWork({
      url: urlStr,
      data: _json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodsInfo: res.data,
            cup_notice: true,
            diyShow: false,
          });

          that._initCoupon(res.data.discount); //设置优惠券信息
          that._setViewData(res.data); //设置界面
        } else {
          that.setData({
            cup_notice: true,
          });
          Toast(res.msg);
          wx.showModal({
            title: "提示",
            content: res.msg,
            showCancel: false,
            success(res) {
              wx.navigateBack({
                delta: 1,
              });
            },
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  // 获取门店数据
  _initStore(str) {
    var that = this;
    this.setData({
      recipient_name: "",
      recipient_mobile: "",
    });
    let store_id = this.options.groupStoreID && this.options.groupStoreID != "undefined" ? this.options.groupStoreID : this.data.store_id;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.get-store-info.get-info-by-store-id");
    urlStr += "&store_id=" + store_id;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            store_info: res.data,
            recipient_name: res.data.store_carry.name,
            recipient_mobile: res.data.store_carry.number,
          });
          if (str !== "is_activity" && !that.options.groupStoreID) {
            that._getDataActionStoreCart();
          }
          // 门店配送规则数据
          if ((res.data.store_delivery && res.data.store_delivery.delivery_status) || res.data.need_lat == 1) {

            that.setData({
              need_lat: res.data.need_lat, //跑腿配送插件，res.data.need_lat为1的时候，需要设置经纬度
              delivery_status: res.data.store_delivery.delivery_status,
              delivery_note: res.data.store_delivery ? res.data.store_delivery.delivery_note : "",
              delivery_amount: res.data.store_delivery ? res.data.store_delivery.delivery_amount : 0,
            });

            let delivery_area = res.data.store_delivery && res.data.store_delivery.delivery_area != "" ? res.data.store_delivery.delivery_area : [];
            let locations = res.data.store_delivery ? res.data.store_delivery.locations : {};
            let arr_delivery_area = [];
            delivery_area.forEach((item, index) => {
              arr_delivery_area.push([Number(item.R), Number(item.Q)]);
            });
            that.setData({
              delivery_area: arr_delivery_area,
              locations: [Number(locations.longitude).toFixed(6), Number(locations.latitude).toFixed(6)],
            });
            if (that.data.locations && that.data.locations.length > 0) {
              that.setData({
                "markers_2[0].longitude": that.data.locations[0],
                "markers_2[0].latitude": that.data.locations[1],
                "delivery.longitude": that.data.locations[0],
                "delivery.latitude": that.data.locations[1],
              });
            }
            if (that.data.delivery_area && that.data.delivery_area.length > 0) {
              let points = [];
              for (let i = 0; i < that.data.delivery_area.length; i++) {
                points.push({
                  longitude: that.data.delivery_area[i][0],
                  latitude: that.data.delivery_area[i][1],
                });
              }
              that.setData({
                "polygons_2[0].points": points,
              });
            }
          }
        } else {
          Toast(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //门店过期商品下单
  getCashGood() {
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.enter.getSetGoodsId");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goods_id: res.data.goods_id,
          });
          if (!res.data.store) {
            that.setData({
              _root_tag: "-2",
              _goodsId: res.data.goods_id,
              store_id: 0,
            });
            that._getDataActionBuy();
          } else {
            that.setData({
              _root_tag: "store",
              store_info: res.data.store,
              store_id: res.data.store.id || res.data.store.store_id,
            });
            that._getDataActionStoreCart();
          }
        } else {
          Toast(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //门店购物车商品
  _getDataActionStoreCart() {
    if (!this.data.store_id) {
      return;
    }
    if (this.data.storeCarts.length > 0) {
      // 已经有storeCarts就不重复请求了
      this.setData({
        cup_notice: true,
      });
      this._getStoreCartBuy(this.data.storeCarts);
      return;
    }
    let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.index");
    urlStr += "&store_id=" + this.data.store_id;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let storeCarts = [];
          res.data.forEach((item) => {
            storeCarts.push(item.id);
          });
          that.setData({
            cup_notice: true,
            storeCarts: storeCarts,
          });
          this.getDispatchMethod(that.data.storeCarts.toString());
        } else {
          that.setData({
            cup_notice: true,
          });
          wx.showToast({
            icon: "none",
            title: "无商品",
            duration: 1500,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //门店结算
  _getStoreCartBuy(cart_ids) {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.cart-buy");
    urlStr += "&cart_ids=" + cart_ids;
    urlStr += "&store_id=" + that.data.store_id;
    urlStr += "&dispatch_type_id=" + this.data.selected;
    if (this.data.selected == 8) {
      urlStr += "&package_deliver_id=" + this.data.defaultSelfCarry.id;
    }
    if (this.data.selected == 12) {
      // 门店自提点
      urlStr += "&package_deliver_id=" + this.data.o2oSelfCarry.id;
    }
    urlStr += "&member_coupon_ids=" + this._assembleCoupons();
    urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
    urlStr += "&address=" + encodeURIComponent(JSON.stringify(this.data.currentAddress));
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodsInfo: res.data,
          });
          that._initCoupon(res.data.discount); //设置优惠券信息
          that._setViewData(res.data, cart_ids); //设置界面
        } else {
          that.setData({
            none_loc: false,
          });
          if (that.data.showAddressList) {
            return;
          }
          if (res.msg === "请完善地址经纬度信息") {
            // 门店配送提示不能返回上一页 #62588
            wx.showModal({
              title: '提示',
              content: "请完善收件人的地址经纬度信息",
              confirmText: '确认',
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  console.log(res);
                }
              }
            });
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
              confirmText: '确认',
              showCancel: false,
              success(response) {
                if (response.confirm) {
                  if (res.msg.indexOf('配送范围') < 0) {
                    wx.navigateBack({
                      delta: 1,
                    });
                  }
                }
              }
            });
            // Toast(res.msg);
            // setTimeout(() => {
            //   wx.navigateBack({
            //     delta: 1,
            //   });
            // }, 4000);
          }
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  //租赁购物车结算
  _getRentDataActionCart(right, rent) {
    if (this.data._root_tag == "rentCartBuy") {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.lease-toy.api.order.cart-buy");
      urlStr += "&lease_rights=" + right;
      urlStr += "&lease_term=" + rent;
      urlStr += "&cart_ids=" + this.data._cart_ids.toString();
      urlStr += "&member_coupon_ids=" + this._assembleCoupons();
      urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
      urlStr += "&address=" + encodeURIComponent(JSON.stringify(this.data.currentAddress));
      urlStr += "&dispatch_type_id=" + this.data.selected;
      //自提点开启
      if (this.data.selected == 8) {
        urlStr += "&package_deliver_id=" + this.data.defaultSelfCarry.id;
      }
      if (this.data.selected == 12) {
        // 门店自提点提货
        urlStr += "&package_deliver_id=" + this.data.o2oSelfCarry.id;
      }
      urlStr += "&mark=" + (this.data.options.mark ? this.data.options.mark : 0);
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              goodsInfo: res.data,
              cup_notice: true,
            });

            that._initCoupon(res.data.discount); //设置优惠券信息
            that._setViewData(res.data); //设置界面
          } else {
            that.setData({
              cup_notice: true,
            });
            Toast(res.msg);
          }
        },
        fail: (res) => {
          console.log(res);
        },
      });
    } else if (this.data._root_tag == "rentBuy") {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.lease-toy.api.order.goods-buy");
      urlStr += "&lease_rights=" + right;
      urlStr += "&lease_term=" + rent;
      urlStr += "&goods_id=" + this.data._goodsId;
      urlStr += "&total=" + this.data._total;
      urlStr += "&option_id=" + this.data._optionsId;
      urlStr += "&member_coupon_ids=" + this._assembleCoupons();
      urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
      urlStr += "&address=" + encodeURIComponent(JSON.stringify(this.data.currentAddress));
      urlStr += "&dispatch_type_id=" + this.data.selected;
      //自提点开启
      if (this.data.selected == 8) {
        urlStr += "&package_deliver_id=" + this.data.defaultSelfCarry.id;
      }
      if (this.data.selected == 12) {
        // 门店自提点提货
        urlStr += "&package_deliver_id=" + this.data.o2oSelfCarry.id;
      }
      urlStr += "&mark=" + (this.data.options.mark ? this.data.options.mark : 0);
      if (this.data.clicktag == 0) {
        this.setData({
          clicktag: 1,
        });
        app._getNetWork({
          url: urlStr,
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              that.setData({
                goodsInfo: res.data,
                cup_notice: true,
              });

              that._initCoupon(res.data.discount); //设置优惠券信息
              that._setViewData(res.data); //设置界面
            } else {
              Toast(res.msg);
            }
            setTimeout(() => {
              that.setData({
                clicktag: 0,
              });
            }, 1000);
          },
          fail: (res) => {
            console.log(res);
          },
        });
      }
    }
  },
  //获取租期列表
  _getRentTimeList() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.lease-toy.api.lease-term.index");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            rentTime: res.data.list,
            rentFree: res.data.level.rent_free,
            agreeCon: res.data.lease_toy_set,
            rent_deposit_free: res.data.level.deposit_free,
            rent_free: res.data.level.rent_free,
          });
          // let article_1 = that.data.agreeCon.lease_toy_pact ? that.data.agreeCon.lease_toy_pact : '';
          /**
           * WxParse.wxParse(bindName , type, data, target,imagePadding)
           * 1.bindName绑定的数据名(必填)
           * 2.type可以为html或者md(必填)
           * 3.data为传入的具体数据(必填)
           * 4.target为Page对象,一般为this(必填)
           * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
           */
          // WxParse.wxParse('article_1', 'html', article_1, that);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  _rentGoodBuy() {
    if (this.data.isOpenRight) {
      let rentTimeRight = "";
      const value = wx.getStorageSync("rentTimeRight");
      if (value) {
        rentTimeRight = value;
      }
      this._getRentDataActionCart(rentTimeRight, []);
    } else {
      if (this.data.currentIndex == "999") {
        let rentTimeSelf = "";
        const value = wx.getStorageSync("rentTimeSelf");
        if (value) {
          rentTimeSelf = value;
        }
        if (!app._isTextEmpty(rentTimeSelf)) {
          this._getRentDataActionCart([], rentTimeSelf);
        } else {
          this._getRentDataActionCart([], []);
        }
      } else {
        let rentTimeChoose = "";
        const value = wx.getStorageSync("rentTimeChoose");
        if (value) {
          rentTimeChoose = value;
        }
        if (!app._isTextEmpty(rentTimeChoose)) {
          this._getRentDataActionCart([], rentTimeChoose);
        }
      }
    }
  },

  // 挂单
  getPendingOrder_type() {
    //获取批发区下单页类型判断
    //挂单不适合配送方式
    let urlStr = app.getNetAddresss("plugin.pending-order.frontend.wholesale-area.pending-order-type");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 1,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.status == 0) {
            let dispatch = [{
              name: "零售",
              dispatch_type_id: 0,
            },
            {
              name: "自用",
              dispatch_type_id: 1,
            },
            ];
            that.setData({
              dispatch: dispatch,
              selected: 0,
            });
          } else {
            let dispatch = [{
              name: "自用",
              dispatch_type_id: 1,
            },];
            that.setData({
              dispatch: dispatch,
              selected: 1,
            });
          }
          that._getDataActionBuy();
        } else {
          Toast(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  //显示地址pop
  showAddress() {
    //获取收货地址
    this.setData({
      showAddressList: true,
      addressList_caller:"express"
    });
  },
  invoiceShowAddressFun(){
    this.setData({
      showAddressList: true,
      addressList_caller:"invoice"
    });
  },
  confirmSelectAddress(e) {
    let info;
    if (e.detail.loc) {
      info = e.detail.form;
    } else {
      info = e.detail;
    }
    if(this.data.addressList_caller == "express"){
      this._setAddressViewData(info);
      this._requestByAddress();
      this.setData({
        showAddressList: false,
      });
    } else if(this.data.addressList_caller == "invoice") {
      this.selectComponent('.invoicePop').setAddress(info);
      this.setData({
        showAddressList: false,
      });
    }
    
  },
  //设置地址界面
  _setAddressViewData(model) {
    if (model == undefined || model == "" || model == []) {
      return;
    }
    if (this.data.selected == "11") {
      if (!model.latitude || !model.longitude) {
        app.confirm("请重新编辑您的地址，在地图上选择您所在的位置", null, false);
        return;
      }
    }
    //设置地址id
    this.data.currentAddId = model.id || model.address_id;
    this.data.currentAddress = model;
    this.setData({
      realname: app._isTextEmpty(model.username) ? "" : model.username,
      mobile: app._isTextEmpty(model.mobile) ? "" : model.mobile,
      address: app._isTextEmpty(model.province) ? "" : model.province + " " + model.city + " " + model.district + " " + (app._isTextEmpty(model.street) ? "" : model.street + " ") + model.address,
    });
  },

  //组装优惠券json信息
  _assembleCoupons() {
    let coupons = [];
    for (let i = 0; i < this.data.checkCouponList.length; i++) {
      if (this.data.is_coupon_SELE) {
        //开启折叠优惠券
        let conpon_arr = this.data.checkCouponList[i].has_conpon_id;
        // console.log("............", this.data.coupons_temp[this.data.checkCouponList[i].coupon_id].num);
        coupons = coupons.concat(conpon_arr.slice(0, this.data.coupons_temp[this.data.checkCouponList[i].coupon_id].num));
        this.setData({
          use_coupon_size: coupons.length,
        });
      } else {
        coupons.push(this.data.checkCouponList[i].id);
      }
    }
    return coupons;
  },
  //组装优惠抵扣信息
  _assembleDeduction() {
    let deductions = [];
    for (let i = 0; i < this.data.checkDeductionList.length; i++) {
      if (this.data.checkDeductionList[i]) {
        deductions.push(this.data.checkDeductionList[i]);
      }
    }
    return deductions;
  },
  _initDiyForm() {
    if (JSON.stringify(this.data.orders_goods) != "{}") {
      //解决填写完表单后，去操作其他会重新请求接口的覆盖了，导致填写记录为空了
      return;
    }
    let orders_goods = {};
    for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
      for (let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++) {
        if (this.data.goodsInfo.orders[j].order_goods[i].diy_form) {
          let model = {};
          model.pre_id = this.data.goodsInfo.orders[j].order_goods[i].pre_id;
          model.diyform_data_id = "";
          orders_goods[model.pre_id] = model;
        }
      }
    }
    this.setData({
      orders_goods: orders_goods,
    });
  },
  findGoodOpen() {
    for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
      if (this.data.goodsInfo.orders[j].camilo_resources_coupon_type) {
        // 卡券商品
        this.setData({
          camilo_resources_coupon_type: this.data.goodsInfo.orders[j].camilo_resources_coupon_type,
        });
        if (this.data.plugin_setting.yz_supply_camilo_resources.is_default_order_address == 1) {
          // 是否开启默认地址
          this.setData({
            _show_address: true
          });
          this.data.currentAddId = 1; //地址没有id  写死一个
          let {
            address,
            city,
            district,
            province,
            street,
            mobile,
            username
          } = this.data.plugin_setting.yz_supply_camilo_resources;
          this._setAddressViewData({
            address,
            city,
            district,
            province,
            street,
            mobile,
            username,
            address_id: 1
          }); // 设置地址界面
        }
      }
      if (this.options.electricity && this.options.electricity == "electricity") {
        this.setData({
          electricity_Guide: this.data.goodsInfo.orders[j].order_goods[0].pre_id,
          ele_no_showAdress: this.data.goodsInfo.orders[j].order_goods[0] ? this.data.goodsInfo.orders[0].not_show_address : false,
          eleUser: this.data.goodsInfo.orders[j].order_goods[0] ? this.data.goodsInfo.orders[0].user_account : ''
        });
      }
      if (this.data.goodsInfo.orders[j].require_mobile) {
        console.log("有商品开启话费慢充！！！");
        let _tips = "";
        if (this.data.goodsInfo.orders[j].tips) {
          _tips = this.data.goodsInfo.orders[j].tips.replace(/<img/g, '<img style="width:100%"');
        }
        this.setData({
          recharge_tips: _tips,
          show_recharge_mobile: this.data.goodsInfo.orders[j].order_goods[0].pre_id,
        });
      }
      //油卡充值
      if(this.data.oil_mobile && this.data.oil_account){
        this.data.oil_pre_id = this.data.goodsInfo.orders[j].order_goods[0].pre_id;
      }
      for (let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++) {
        if (this.data.goodsInfo.orders[j].order_goods[i].diy_form) {
          console.log("有商品开启自定义表单！！！");
          this.data.hasGoodOpenDF = true;
        }
      }
    }
  },
  _checkDiyForm() {
    for (let i in this.data.orders_goods) {
      if (!this.data.orders_goods[i].diyform_data_id) {
        // this.data.submit_active = true;
        return false;
      }
    }
    return true;
  },
  _setDiyForm(pre_id, diyform_data_id) {
    for (let i in this.data.orders_goods) {
      if (this.data.orders_goods[i].pre_id == pre_id) {
        this.data.orders_goods[i].diyform_data_id = diyform_data_id;
        this.setData({
          orders_goods: this.data.orders_goods,
        });
        return;
      }
    }
  },
  _findDiyForm(pre_id) {
    for (let i in this.data.orders_goods) {
      if (this.data.orders_goods[i].pre_id == pre_id) {
        return this.data.orders_goods[i].diyform_data_id;
      }
    }
    return false;
  },
  _assembleDiyForm() {
    let orders_goods = [];
    for (let i in this.data.orders_goods) {
      orders_goods.push(this.data.orders_goods[i]);
    }
    return orders_goods;
  },

  onTELChange(e) {
    this.setData({
      recharge_mobile: e.detail,
    });
  },
  assembleGoodsTELData() {
    //组装商品话费慢充信息
    let newGoodsDF = [];
    let modelDF = {};

    if (this.options.electricity == "electricity") {
      modelDF.pre_id = this.data.electricity_Guide;
      modelDF.account_id = this.options.account_id;
    } else if(this.data.oil_account && this.data.oil_mobile){  //油卡充值
      modelDF.pre_id = this.data.oil_pre_id;
      modelDF.account = this.data.oil_account;
      modelDF.mobile = this.data.oil_mobile;
    } else {
      modelDF.pre_id = this.data.show_recharge_mobile;
      modelDF.mobile = this.data.recharge_mobile;
    }
    newGoodsDF.push(modelDF);
    return newGoodsDF;
  },

  //设置界面
  _setViewData(data, cart_ids) {
    this.setData({
      _show_address: this.isOrderAddress_M(data.orders),
      recommend_goods: data.dispatch.recommend_goods ? data.dispatch.recommend_goods : []
    });
    if (data.is_agency_restock && data.is_agency_restock == 1) {
      this.setData({
        _show_address: true,
      });
    }
    if (this.data._show_address) { //跟H5一样有这个判断
      this.setData({
        selected: 0
      });
    }
    this._setAddressViewData(data.dispatch.default_member_address); //设置地址界面

    this.setData({
      consigneeName: data.dispatch.custom_data ? data.dispatch.custom_data.custom_consignee : '提货人姓名',
      consigneeMobile: data.dispatch.custom_data ? data.dispatch.custom_data.custom_phone : '提货人手机'
    });

    this._initDiyForm();
    if (data.discount && data.discount.default_deduction && data.discount.default_deduction != 0) {
      this.data.default_deduction = data.discount.default_deduction;
    }

    if (this.data.default_deduction != 0) {
      // 默认积分抵扣要获取order_deductions里checked=true的传给第二次接口
      for (let i = 0; i < data.orders.length; i++) {
        let arr = data.orders[i].order_deductions;
        if (!(data.orders[i].order_deductions instanceof Array)) {
          arr = Object.values(data.orders[i].order_deductions);
        }
        arr.map((item) => {
          if (item.checked) {
            this._screenDiscount(data.orders[i], item);
          }
        });
      }
    }

    // let that = this;
    this.findGoodOpen(); // 循环订单列表是否开启表单和慢充
    if (!this.data.getParams_status) {
      this.data.getParams_status = true;
      this.getParams(cart_ids);
    }
    this.checkOrders(data); //判断有订单是否有绑定域名

    this.data.dispatch.forEach((items, i) => {
      if (items.dispatch_type_id == 8) {
        console.log("有自提点配送方式，请求定位获取自提点列表");
        if (JSON.stringify(this.data.defaultSelfCarry) == "{}") {
          this._getLocation(() => {
            this.getList("shop");
          });
        }
      }
      if (items.dispatch_type_id == 12) {
        console.log("有门店自提点配送方式，请求定位获取自提点列表");
        if (!this.data.o2oSelfCarry.id) {
          this._getLocation(() => {
            this.getList("o2o");
          });
        }
      }
    });
    if(this.data.selected == 11){
      this.getDeliverySetting()
    }
    this.setData({
      order_data: data.orders,
      price: data.total_price, //设置总价格（合计）
      total_items: data.amount_items,
      discount_amount_items: data.discount_amount_items,
      service_fee_items: data.service_fee_items,
      service: data.orders[0].order_fees,
      none_loc: true,
      clicktag: 0,
    });

    if (this.data._root_tag == "store" && this.data.price < 0) {
      wx.showToast({
        icon: "none",
        title: "下单错误",
        duration: 1500,
      });
    }
    if (data.dispatch.use_wechat_address) {
      this.setData({
        use_wechat_address: data.dispatch.use_wechat_address
      });
    }
  },
  isOrderAddress_M(_data) {
    //判断是否有订单需要填写地址，有一单需要填写地址则需要填写地址才可以下单
    //return false 提交订单需要填写地址
    for (let j = 0; j < _data.length; j++) {
      if (this.data.phone_bill_pro_goods) {
        if (!_data[j].not_show_address) {
          // console.log("有订单需要填写地址");
          return false;
        }
      } else if(this.data.oil_account && this.data.oil_mobile){
        if (!_data[j].not_show_address ) {
          // console.log("有订单需要填写地址");
          return false;
        }
      }else {
        if (!_data[j].need_address) {
          console.log("有订单需要填写地址");
          return false;
        }
      }

    }
    return true;
  },
  checkOrders(data) {
    for (let i = 0; i < data.orders.length; i++) {
      if (data.orders[i].plugin_id === 58) {
        this.setData({
          plugin_id: 58,
        });
      }
    }

    for (let i = 0; i < data.orders.length; i++) {
      if ("domain" in data.orders[i]) {
        this.setData({
          isDomain: true,
          domain: data.orders[i].domain,
        });
      } else {
        this.setData({
          isDomain: false,
        });
        return;
      }
    }
  },
  // 整合了发票、是否显示个人信息接口
  getParams(cart_ids) {
    let json = {};
    let that = this;
    if (this.data._root_tag == "store" && !cart_ids) {
      return;
    } else if (this.data._root_tag == "store" && cart_ids) {
      this.setData({
        _cart_ids: cart_ids,
      });
    }
    let good_ids = [];
    // 不清楚this.data.options.cart_ids这个字段作用，但是这个字段导致选择完自提点后返回报错，打印这个cart_ids为字符串得undefined
    if (this.data.options.cart_ids && this.data.options.cart_ids != "undefined") {
      this.setData({
        _cart_ids: this.data.options.cart_ids ? JSON.parse(this.data.options.cart_ids) : [],
      });
    }

    if (this.data.isCartsOrder) {
      // 购物车商品下单的循环商品
      this.setData({
        _cart_ids: this.data.options.cart_ids ? JSON.parse(this.data.options.cart_ids) : [],
      });

      for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
        for (let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++) {
          good_ids.push(this.data.goodsInfo.orders[j].order_goods[i].goods_id);
        }
      }
    } else {
      if (this.data.options.goodsId) {
        this.setData({
          _goodsId: Number(this.data.options.goodsId),
        });
      }
      good_ids.push(this.data._goodsId);
    }
    let urlStr = app.getNetAddresss("from.div-from.get-params");
    json = {
      goods_ids: JSON.stringify(good_ids),
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (that.options.type != "groupBuy_open" || that.options.type != "groupBuy_join") {
            //拼购显示自己的支付协议
            that.setData({
              isGetAgreementPay: true,
              AgreementPay: res.data.getPayProtocol ? res.data.getPayProtocol : "",
            });
          }
          this.setData({
            freightExplain: res.data.freightExplain
          });
          try {
            that.setData({
              storeSearchBtn: res.data.storeSearch || {},
              openCueCoupon: res.data.getCouponSet == 0 ? false : true, //是否开启下单优惠券提示
            });
            that._checkTaxGoods(res.data.isDisplay);
            if (res.data.getMemberInfo) {
              that._getMemberInfo(res.data.getMemberInfo);
            }
            // if (res.data.explain) {
            //   that._getExplain(res.data.explain);
            // }
            that.getInvoice(res.data.sinvoice);
          } catch (error) {
            console.log(error);
          }
        } else {
          that.setData({
            isGetAgreementPay: false,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  // 发票数据
  getInvoice(data) {
    let address = {
      realname: this.data.realname,
      mobile: this.data.mobile,
      address: this.data.address
    }
    this.selectComponent('.invoicePop').initData({sinvoice: data, address});
  },
  subInvoice(data) {
    // 弹窗获取发票数据
    this.setData({
      invoice_list: data.detail, //72638
    });
  },

  //初始化优惠券
  _initCoupon(data) {
    if (data.deduction_lang) {
      this.setData({
        deduction_lang: data.deduction_lang
      });
    }
    this.setData({
      isShowCoupon: data.whether_show_coupon == "1" ? true : false,
    });
    let coupon = data.member_coupons;
    this.setData({
      is_coupon_SELE: data.coupon_show == "1" ? true : false,
    });
    this.setData({
      coupon_size: coupon.length,
    });
    if (coupon != undefined && coupon != "" && coupon != null) {
      if (this.data.is_coupon_SELE) {
        //按过期时间排序
        let arr2 = coupon.sort((a, b) => {
          return a.expired_at - b.expired_at;
        });
        this.initSelectCoupon(arr2);
      } else {
        this.setData({
          coupons: coupon,
        });
      }
    }
  },
  //初始化带有默认选中优惠券
  defaultSelectCoupon(coupon) {
    let checkCouponList = [];
    coupon.forEach((item, ind) => {
      if (item.checked == true) {
        checkCouponList.push(item);
      }
    });
    this.setData({
      coupon_size: coupon.length,
      coupons: coupon,
      use_coupon_size: checkCouponList.length,
      checkCouponList: checkCouponList,
    });
    console.log(this.data.coupons);
  },
  //折叠优惠券
  initSelectCoupon(coupon) {
    let coupon_data = coupon;
    let result = [];
    let temp = {};

    for (let i = 0; i < coupon_data.length; i++) {
      let num = 0; //同类型已选中并符合使用条件的优惠券数量
      let valid = 0; //最高限制使用数量
      let has_conpon_id = [coupon_data[i].id];
      if (coupon_data[i].checked) {
        num++;
      }
      if (coupon_data[i].valid) {
        valid++;
      }
      for (let j = i + 1; j < coupon_data.length; j++) {
        // console.log("33333333==================", coupon_data[j].coupon_id)
        if (coupon_data[i].coupon_id == coupon_data[j].coupon_id) {
          if (coupon_data[j].checked) {
            num++;
          }
          if (coupon_data[j].valid) {
            valid++;
          }
          has_conpon_id.push(coupon_data[j].id);
          coupon_data.splice(j, 1);
          j--;
        }
      }
      let _data = coupon_data[i];
      _data.has_conpon_id = has_conpon_id;
      _data.valid_num = valid;
      result.push(_data);
      temp[coupon_data[i].coupon_id] = {};
      temp[coupon_data[i].coupon_id].num = num;
    }
    this.setData({
      coupons_temp: temp,
      coupons: result,
    });
    console.log(this.data.coupons, this.data.coupons_temp);
  },
  changeConpon(e) {
    let valObj = e.target.dataset.item;
    let num = e.detail;
    let index = e.target.dataset.index;
    console.log("=================", e.detail, valObj);
    if (num > valObj.valid_num) {
      wx.showToast({
        icon: "none",
        title: "使用张数已达上限",
        duration: 1000,
      });
      clearTimeout(this.data.timer);
      this.data.timer = setTimeout(() => {
        // 注意此时修改 value 后会再次触发 change 事件
        this.data.coupons_temp[valObj.coupon_id].num = valObj.valid_num;
        this.setData({
          coupons_temp: this.data.coupons_temp,
        });
      }, 200);
      return;
    } else if (num == "" || num == undefined || num == 0) {
      wx.showToast({
        icon: "none",
        title: "暂不使用请取消勾选",
        duration: 1000,
      });
      return;
    } else {
      clearTimeout(this.data.timer);
      this.data.coupons_temp[valObj.coupon_id].num = num;
      this.setData({
        coupons_temp: this.data.coupons_temp,
      });
    }

    // clearTimeout方法，以便控制连续触发带来的无用调用
    let value = {
      detail: true,
      currentTarget: {
        dataset: {
          index: index,
          item: valObj,
        },
      },
    };
    if (this.data.timeoutId) {
      clearTimeout(this.data.timeoutId); // 先清除之前的延时，并在下面重新开始计算时间
    }
    this.data.timeoutId = setTimeout(() => {
      // 100毫秒以后执行方法
      this.selectCoupon(value);
    }, 1000); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
  },

  //提货人输入
  infonamebtn(e) {
    let infoname = e.detail;
    this.setData({
      "linkinfo.name": infoname,
    });
  },
  infonameclear() {
    this.setData({
      "linkinfo.name": "",
    });
  },
  infomobileclear() {
    this.setData({
      "linkinfo.mobile": "",
    });
  },
  //提货人手机输入
  infomobilebtn(e) {
    let infomobile = e.detail;
    this.setData({
      "linkinfo.mobile": infomobile,
    });
  },
  //选择地址后重新计算数据
  _requestByAddress() {
    //重新计算
    this.handleBuy(1);
  },

  //判断是否选择权益商品
  _judgeIsRight() {
    if (this.data.isOpenRight) {
      this.setData({
        isRightChoose: false,
      });
    } else {
      this.setData({
        isRightChoose: true,
      });
    }
  },
  //权益商品选择事件
  rentSelect(e) {
    let isOpenRight = e.detail;
    this.setData({
      isOpenRight: isOpenRight,
    });
    //1.判断是否选择权益商品，有则租期按照会员权益日期计算
    this._clearStorage();
    this._judgeIsRight();
    if (this.data.isOpenRight) {
      let arr = [];
      this.data.order_data.forEach((val) => {
        val.order.order_goods.forEach((item) => {
          let obj = {
            goods_id: item.goods_id,
            total: item.total,
          };
          arr.push(obj);
        });
      });
      wx.setStorage({
        key: "rentTimeRight",
        data: JSON.stringify(arr),
      });
      this._getRentDataActionCart(JSON.stringify(arr), []);
    } else if (!this.data.isOpenRight) {
      this.setData({
        currentIndex: "999",
      });
      this._getRentDataActionCart([], []);
    }
  },
  //清除租赁localstorage
  _clearStorage() {
    wx.removeStorage({
      key: "rentTimeSelf",
    });
    wx.removeStorage({
      key: "rentTimeChoose",
    });
    wx.removeStorage({
      key: "rentTimeRight",
    });
  },
  switchChange(e) {
    let dindex = e.currentTarget.dataset.dindex;
    let orindex = e.currentTarget.dataset.orindex;
    let pre_id = this.data.order_data[orindex].pre_id;
    let item = e.currentTarget.dataset.item;
    let codeind = e.currentTarget.dataset.codeind;

    if (item.checked) {
      this.setData({
        ['order_data[' + orindex + '].order_service_fees[' + codeind + '].checked']: false,
        ['order_data[' + orindex + '].order_service_fees[' + codeind + '].show']: false,
        ["service_fee." + pre_id]: [],
      });
    } else {
      this.setData({
        ['order_data[' + orindex + '].order_service_fees[' + codeind + '].checked']: true,
        ['order_data[' + orindex + '].order_service_fees[' + codeind + '].show']: true,
        ["service_fee." + pre_id]: [item.code],
      });
    }
    this.serviceFeesHandle(this.data.order_data[orindex], this.data.order_data[orindex].order_deductions[dindex]);
    //重新计算
    this.handleBuy(2);
  },
  //抵扣选择响应
  discountHandle(e) {
    let dischecked = e.detail;
    let dindex = e.currentTarget.dataset.dindex;
    let orindex = e.currentTarget.dataset.orindex;
    let tag = e.currentTarget.dataset.tag;
    if (!this.data.none_loc) {
      // 超出门店配送范围不可以使用积分抵扣
      dischecked = false;
    }

    if (tag == "discount") {
      if (Object.prototype.toString.call(this.data.order_data[orindex].order_deductions) == "[object Object]") {
        // object要用.的方式调用
        this.setData({
          ["order_data[" + orindex + "].order_deductions." + dindex + ".checked"]: dischecked,
        });
      } else if (Object.prototype.toString.call(this.data.order_data[orindex].order_deductions) == "[object Array]") {
        this.setData({
          ["order_data[" + orindex + "].order_deductions[" + dindex + "].checked"]: dischecked,
        });
      }
      this._screenDiscount(this.data.order_data[orindex], this.data.order_data[orindex].order_deductions[dindex]);
    } else if (tag == "serviceFee") {
      let pre_id = this.data.order_data[orindex].pre_id;
      this.setData({
        ["service_fee." + pre_id]: e.detail,
      });
      console.log(e.detail, this.data.service_fee, 's:::::');

      this.serviceFeesHandle(this.data.order_data[orindex], this.data.order_data[orindex].order_deductions[dindex]);
    }

    //重新计算
    this.handleBuy(2);
  },
  // 留言
  noteHandle(e) {
    let preid = e.target.dataset.preid;
    let item = e.target.dataset.item;
    let val = e.detail.value;
    this.setData({
      ["note." + preid]: val,
    });
    // 触发抵扣事件
    this.deductionListHandle(item);
  },
  //筛选抵扣
  _screenDiscount(item, value) {
    this.deductionListHandle(item, value);
  },
  serviceFeesHandle(item, value) {
    //服务费、运费复选框
    this.deductionListHandle(item);
  },

  deductionListHandle(item, value) {
    let checkDeductionList = this.data.checkDeductionList;
    let service_fee = this.data.service_fee;
    let note = this.data.note;
    let isHasPreId = false;

    if (checkDeductionList.length > 0) {
      checkDeductionList.map((deduction, index) => {
        if (deduction && deduction.pre_id == item.pre_id) {
          isHasPreId = true;
          if (value && value.checked) {
            // 选中的时候检查是否有对应的code
            if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) == -1) {
              deduction.deduction_ids.push(value.code);
            }
          } else if (value && !value.checked) {
            // 取消选中的时候检查去掉对应的code
            if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) > -1) {
              deduction.deduction_ids.splice(deduction.deduction_ids.indexOf(value.code), 1);
            }
          }

          // 留言和安装选项重新赋值
          deduction.note = note[item.pre_id];
          deduction.service_fee = service_fee[item.pre_id];
        }
      });
    }
    if (!isHasPreId) {
      checkDeductionList.push({
        deduction_ids: value && value.code ? [value.code] : [],
        pre_id: item.pre_id,
        note: note[item.pre_id],
        service_fee: service_fee[item.pre_id],
      });
    }
    this.setData({
      checkDeductionList
    });
    // console.log('checkDeductionList:', this.data.checkDeductionList)
  },

  //选择自定义租期
  rentSelfChoose() {
    this._clearStorage();
    this.setData({
      currentIndex: "999",
    });
    this.setData({
      rentShow: true,
    });
  },
  rentShowClose(event) {
    if (event.detail === "confirm") {
      if (app._isTextEmpty(this.data.tenancy)) {
        wx.showToast({
          icon: "none",
          title: "租期不能为空",
          duration: 1000,
        });
        return;
      }
      let obj = {
        days: this.data.tenancy,
        lease_term_id: 0,
      };
      wx.setStorage({
        key: "rentTimeSelf",
        data: JSON.stringify(obj),
      });
      this._getRentDataActionCart([], JSON.stringify(obj));
      // 异步关闭弹窗
      setTimeout(() => {
        this.setData({
          rentShow: false,
        });
      }, 1000);
    } else {
      this.setData({
        rentShow: false,
      });
      console.log("取消自定义租期！！！");
    }
  },
  //自定义租期数值绑定
  rentShowinp(e) {
    let rentval = e.detail;
    this.setData({
      tenancy: rentval,
    });
  },
  //自定义租期值清除
  rentclear() {
    this.setData({
      tenancy: "",
    });
  },
  //选择租期
  rentTimeChoose(e) {
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    if (this.data.currentIndex == index) {
      this.setData({
        currentIndex: "999",
      });
      this._clearStorage();
      this._getRentDataActionCart([], []);
    } else {
      this._clearStorage();
      this.setData({
        currentIndex: index,
      });
      let obj = {
        days: 0,
        lease_term_id: item.id,
      };
      wx.setStorage({
        key: "rentTimeChoose",
        data: JSON.stringify(obj),
      });
      this._getRentDataActionCart([], JSON.stringify(obj));
    }
  },

  //优惠券
  showCoupon() {
    if (this.data.coupon_size == 0) {
      wx.showToast({
        icon: "none",
        title: "暂无优惠券使用",
        duration: 1500,
      });
      return;
    }
    this.setData({
      popupCouponSpecs: true,
    });
  },
  //选择优惠券
  selectCoupon(e) {
    let couponBol = e.detail;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    console.log(couponBol, index, item, e.type);
    this.setData({
      ["coupons[" + index + "].checked"]: couponBol,
    });
    this._screenCoupon(couponBol, item, e.type);
    //设置view
    this._setCouponView();
    //重新计算
    this.handleBuy(2);
  },
  //筛选数据优惠券状态
  _screenCoupon(couponBol, valObj, type) {
    let tarValue = valObj;
    let checkCouponList = this.data.checkCouponList;
    if (this.data.checkCouponList.length > 0) {
      for (let i = 0; i < this.data.checkCouponList.length; i++) {
        if (this.data.checkCouponList[i].id == tarValue.id) {
          checkCouponList.splice(i, 1);
        }
      }
    }
    if (this.data.is_coupon_SELE && type) {
      //开启折叠优惠券并且为点击复选框为选中状态
      this.data.coupons_temp[tarValue.coupon_id].num = couponBol ? 1 : 0;
      this.setData({
        coupons_temp: this.data.coupons_temp
      });
    }
    if (couponBol) {
      //选中添加
      checkCouponList.push(tarValue);
    } else {
      //取消选中
      this.setData({
        cup_notice: true
      });
    }
    this.setData({
      checkCouponList: checkCouponList
    });
  },
  //设置view
  _setCouponView() {
    this.setData({
      use_coupon_size: this.data.checkCouponList.length,
    });
  },
  mustSelectCoupon() {
    // 后台设置，下单前判断有优惠券数量但没使用时，是否提示并展开选择优惠券弹窗，只提示一次！
    if (this.data.openCueCoupon && this.data.coupon_size > 0 && this.data.use_coupon_size < 1 && !this.data.isCueCoupon) {
      //显示优惠券列表弹窗
      // 按钮文字改变
      this.setData({
        isCueCoupon: true,
        popupCouponSpecs: true,
      });
      return true;
    }
    return false;
  },
  //关闭优惠卷
  couponclose() {
    this.setData({
      popupCouponSpecs: false,
    });
  },
  //租赁协议
  agreementbtn(e) {
    let agreeBol = e.detail;
    this.setData({
      agreement: agreeBol,
    });
  },
  //租赁弹窗显示
  showAgreement() {
    this.setData({
      agreementShow: true,
    });
  },
  agreementClose() {
    this.setData({
      agreementShow: false,
    });
  },
  toSite() {
    wx.navigateTo({
      url: "/packageE/others/application_market/binding_site/binding_site?plugin_id=" + this.data.plugin_id,
    });
  },

  //获取模板id
  getTemplate() {
    let urlStr = app.getNetAddresss("member.member.getMiniTemplateCorrespond");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 1,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          for (let i = 0; i < res.data.length; i++) {
            array.push(res.data[i].template_id);
          }
          that.setData({
            TemplateArray: array,
          });
          if (that.data.TemplateArray.length > 0) {
            wx.requestSubscribeMessage({
              tmplIds: that.data.TemplateArray,
              success(res) {
                that.setData({
                  clickMiniTemplate: true
                });
                console.log(res, "success");
                that.submitBtn();
              },
              fail(err) {
                console.log(err, "err");
                that.submitBtn();
              },
            });
          } else {
            that.submitBtn();
          }
        } else {
          Toast(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //提交订单
  submit() {
    if (this.data.yz_subscribe_disabled) return;
    if (this.data.clickMiniTemplate) {
      this.submitBtn();
    } else {
      this.getTemplate();
    }

  },
  checkDispatch() {
    if (this.data.selected == 8 || this.data.selected == 12 || this.data.selected == 15) {
      if (app._isTextEmpty(this.data.linkinfo.name)) {
        wx.showModal({
          title: "提示",
          content: "请填写提货人姓名",
          showCancel: false,
          confirmText: "确定",
          confirmColor: "#000000",
          success: (res) => {},
        });
        this.data.submit_active = true;
        return false;
      }
      if (app._isTextEmpty(this.data.linkinfo.mobile)) {
        wx.showModal({
          title: "提示",
          content: "请输入提货人手机",
          showCancel: false,
          confirmText: "确定",
          confirmColor: "#000000",
          success: (res) => {},
        });
        this.data.submit_active = true;
        return false;
      }
    }

    if (this.data.selected == 8 || this.data.selected == 12) {
      if ((this.data.selected == 8 && app._isTextEmpty(this.data.defaultSelfCarry)) || (this.data.selected == 12 && app._isTextEmpty(this.data.o2oSelfCarry))) {
        wx.showToast({
          title: "该地区暂无自提点",
          duration: 1000,
          icon: "none",
        });
        return false;
      }
      if ((this.data.selected == 8 && app._isTextEmpty(this.data.defaultSelfCarry.id)) || (this.data.selected == 12 && app._isTextEmpty(this.data.o2oSelfCarry.id))) {
        wx.showModal({
          title: "提示",
          content: "请选择自提点",
          showCancel: false,
          confirmText: "确定",
          confirmColor: "#000000",
          success: (res) => {},
        });
        this.data.submit_active = true;
        return false;
      }

      //保存自提点信息到本地，任务编号: 35632
      let _memberInfoes = {
        distributionUserName: this.data.linkinfo.name ? this.data.linkinfo.name : "",
        distributionUserMobile: this.data.linkinfo.mobile ? this.data.linkinfo.mobile : "",
      };
      try {
        wx.setStorageSync("selfCarryInfo", JSON.stringify(_memberInfoes));
      } catch (e) {
        console.log(e);
      }
    }

    if (this.data.store_info.delivery_information == 1) {
      if (this.data.selected == "2" && (app._isTextEmpty(this.data.linkinfo.name) || app._isTextEmpty(this.data.linkinfo.mobile))) {
        wx.showToast({
          icon: "none",
          title: "请输入提货人信息",
          duration: 1500,
        });
        return false;
      }
      if (this.data.selected == "2" && !/^[0-9]{1,}$/.test(this.data.linkinfo.mobile)) {
        wx.showToast({
          icon: "none",
          title: "请输入正确的联系电话",
          duration: 1500,
        });
        this.data.submit_active = true;
        return false;
      }
    }

    if (!this.data._show_address && (this.data.selected == 0 || this.data.selected == 1 || this.data.selected == 3) && !this.data.ele_no_showAdress && !this.data.reserve_order) {
      if ((this.data.selected == 0 || this.data.selected == 1) && this.data.use_wechat_address) {
        // 页面设计插件和商城设置 - 订单设置 - 调用微信地址开启了 只用于快递
        if (app._isTextEmpty(this.data.design_info.userName)) {
          app.tips('请输入收货人姓名');
          this.data.submit_active = true;
          return false;
        }
        if (app._isTextEmpty(this.data.design_info.telNumber)) {
          app.tips('请填写收货手机号');
          this.data.submit_active = true;
          return false;
        }
        if (app._isTextEmpty(this.data.userAdress)) {
          app.tips('请选择所在区域');
          this.data.submit_active = true;
          return false;
        }
        if (app._isTextEmpty(this.data.design_address)) {
          app.tips('请输入街道、楼牌号等');
          this.data.submit_active = true;
          return false;
        }
        return true;
      }
      if (app._isTextEmpty(this.data.currentAddId)) {
        wx.showModal({
          title: "提示",
          content: "请选择收货地址",
          showCancel: false,
          confirmText: "确定",
          confirmColor: "#000000",
          success: (res) => {
            this.showAddress();
          },
        });
        this.data.submit_active = true;
        return false;
      }
    }

    return true;
  },
  checkSubmit() {
    if (this.mustSelectCoupon()) {
      // 提示优惠券【51723】
      return false;
    }

    if (this.data.isDomain) {
      if (app._isTextEmpty(this.data.domain)) {
        wx.showToast({
          icon: "none",
          title: "请绑定站点",
          duration: 1500,
        });
        return false;
      }
    }

    if (this.data.cpstype == "1" && this.data.cpsTxt == "") {
      wx.showToast({
        title: "请输入帐号",
        duration: 1000,
        icon: "none",
      });
      return false;
    }

    // 手机慢充
    if (this.data.show_recharge_mobile && !this.data.recharge_mobile) {
      wx.showToast({
        icon: "none",
        title: "请输入充值手机号码！",
        duration: 1500,
      });
      return false;
    } else if (this.data.show_recharge_mobile && this.data.recharge_mobile) {
      let reg_txt = /^[1][0-9]{10}$/;
      if (!reg_txt.test(this.data.recharge_mobile)) {
        wx.showToast({
          icon: "none",
          title: "请输入正确的充值手机号码！",
          duration: 1500,
        });
        return false;
      }
    }

    if (this.data.reserve_order != null) {
      if (this.data.reserve_tel_name == '') return app.tips("请输入联系人");
      if (this.data.reserve_mobile == '') return app.tips("请输入联系电话");
    }

    if (this.data.camilo_resources_coupon_type == 1) {
      // 卡券商品
      if (!this.data.recharge_number) {
        return app.tips("请输入充值账号");
      }
    }

    if (this.options.tag == "newRetail" && this.options.retailState == 3 && this.data.price == 0) {
      //新零售-自由发货下单不能为0
      wx.showToast({
        icon: "none",
        title: "价格有误",
        duration: 1500,
      });
      this.data.submit_active = true;
      return false;
    }

    if (this.data.hasGoodOpenDF && !this._checkDiyForm()) {
      wx.showToast({
        icon: "none",
        title: "请先填写表单",
        duration: 1500,
      });
      this.data.submit_active = true;
      return false;
    }

    if (!this.checkDispatch()) {
      return false;
    }

    if (this.data.AgreementPay && !this.data.isRent) {
      if (!this.data.agreementPay) {
        wx.showToast({
          icon: "none",
          title: "请勾选支付协议",
          duration: 1500,
        });
        return false;
      }
    }

    if (this.data.isRent && !this.data.agreement) {
      wx.showToast({
        icon: "none",
        title: "请勾选租赁协议",
        duration: 1500,
      });
      this.data.submit_active = true;
      return false;
    }

    return true;
  },
  submitBtn() {
    let that = this;
    if (!this.checkSubmit()) {
      return;
    }
    let json = this._assembleJson();

    if (this.data.store_id && this.options.tag != "reserve") {
      if (this.isHasInstall()) {
        //有勾选了上门安装服务，需要填写经纬度和时间
        if (!this.data.installDate) {
          app.tips("请选择预约时间！");
          return;
        }
        if (!this.data.location && !this.data.location.latitude) {
          app.tips("请选择地理位置！");
          return;
        }
        let live_install_json = {
          live_install: {
            longitude: this.data.location.longitude,
            latitude: this.data.location.latitude,
            reserve_time: this.data.installDate,
            install_comment: this.data.install_comment,
          },
        };
        Object.assign(json, live_install_json);
      }

      this.data.order_url = "plugin.store-cashier.frontend.store.create";
    }

    switch (this.data._root_tag) {
    case "store_projects_goods":
      //* 门店核销
      this.data.order_url = "plugin.store-projects.frontend.order.create";
      json.goods_type = "store_projects_goods";
      break;
    }

    if (this.data.selected == "10") {
      if (json.supplier_driver_distribution_address) {
        if (app._isTextEmpty(json.supplier_driver_distribution_address.lat) || app._isTextEmpty(json.supplier_driver_distribution_address.lng)) {
          app.tips('请选择供应商配送定位');
          return;
        }
      }
    }
    if (this.data.selected == "11") {
      // selected == "11" 同城配送
      if (this.data.cityDelivery.distance_type == 3) {
        if (!this.data.cityDelivery_community.id) {
          app.tips("请选择配送社区");
          return;
        }
        json.community_id = this.data.cityDelivery_community.id;
      }
      if (this.data.cityDelivery.future_state == 1) {
        if (!this.data.cityDelivery_deliveryTime.start_time || !this.data.cityDelivery_deliveryTime.end_time) {
          app.tips("请选择配送时间");
          return;
        }
        json.expect_start_time = this.data.cityDelivery_deliveryTime.start_time;
        json.expect_end_time = this.data.cityDelivery_deliveryTime.end_time;
      }

    }

    console.log(this.data.submit_active);
    if (this.data.submit_active == true) {
      this.data.submit_active = false;

      let urlStr = app.getNetAddresss(this.data.order_url);
      if (this.data.clicktag == 0) {
        this.setData({
          clicktag: 1,
        });
        app._postNetWork({
          url: urlStr,
          showToastIn: false,
          data: json,
          success: (resdata) => {
            let res = resdata.data;
            that.data.submit_active = true;
            if (res.result == 1) {
              that.setData({
                showPage: false,
              });
              wx.showLoading({
                title: "跳转中",
              });
              if (that.data.iscps) {
                wx.redirectTo({
                  url: "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2" + `&iscps=${that.data.iscps ? true : false}`,
                });
                return;
              }
              if (that.options.option_level_id) {
                wx.redirectTo({
                  url: "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2" + "&name=groups",
                });
                return;
              }
              if (that.data.store_id) {
                // 门店
                wx.redirectTo({
                  url: "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2&store_id=" + that.data.store_id,
                });
                return;
              }
              // 盲盒
              if (that.data._root_tag == "blindBox") {
                wx.redirectTo({
                  url: "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2&name=" + that.data._root_tag,
                });
                return;
              }
              wx.redirectTo({
                url: "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2",
              });
            } else {
              Toast(res.msg);
            }
            setTimeout(() => {
              that.setData({
                clicktag: 0,
              });
            }, 1000);
          },
          fail: (res) => {
            console.log(res);
          },
        });
      }
    }
  },
  isHasInstall() {
    //判断是否有勾选了上门安装服务
    for (let j = 0; j < this.data.goodsInfo.service_fee_items.length; j++) {
      if (this.data.goodsInfo.service_fee_items[j].code == "liveInstall") {
        return true;
      }
    }
    return false;
  },
  inpCpsTxt(e) {
    console.log(e);
    let txt = e.detail.value;
    this.setData({
      cpsTxt: txt,
    });
  },

  //组装商品信息
  _assembleGoods() {
    let newGoods = [];
    for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
      for (let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++) {
        let model = {};
        model.goods_id = this.data.goodsInfo.orders[j].order_goods[i].goods_id;
        model.total = this.data.goodsInfo.orders[j].order_goods[i].total;
        model.option_id = this.data.goodsInfo.orders[j].order_goods[i].goods_option_id;
        newGoods.push(model);
      }
    }
    return newGoods;
  },
  //组装json数据
  _assembleJson() {
    let json = {
      //公共数据
      address: encodeURIComponent(JSON.stringify(this.data.currentAddress)),
      goods: JSON.stringify(this._assembleGoods()),
      member_coupon_ids: JSON.stringify(this._assembleCoupons()),
      orders: JSON.stringify(this._assembleDeduction()),
      // 发票
      // invoice_type: this.data.invoice_list.invoice_type === "electron" ? 0 : 1,
      // rise_type: this.data.invoice_list.invoice_status === "person" ? 1 : 0,
      // call: this.data.invoice_list.call,
      // email: this.data.invoice_list.email,
      // company_number: this.data.invoice_list.company_number,
      //新的发票-发票插件
      invoice:this.data.invoice_list,
      mark: this.data.options.mark ? this.data.options.mark : 0,
      dispatch_type_id: this.data.selected, //配送方式 ，1：快递 ||2：门店自提||3：门店配送（送货上门）||8：自提点
    };
    if (this.data.use_wechat_address && (this.data.selected == 1 || (this.data.selected == 0 && !this.data.use_wechat_address))) {
      // 只用于快递，并且开启了使用微信地址
      let usejson = {
        address: this.data.design_address || "",
        city: this.data.design_info.cityName,
        district: this.data.design_info.countyName,
        id: "",
        isdefault: "",
        latitude: "",
        longitude: "",
        mobile: this.data.design_info.telNumber,
        province: this.data.design_info.provinceName,
        street: "",
        uid: "",
        uniacid: "",
        username: this.data.design_info.userName,
        zipcode: "",
      };
      // 没有选择微信地址的时候，是整个adress都为空
      json.address = usejson.address?encodeURIComponent(JSON.stringify(usejson)):[];
    }
    // 分销活动页面购买的商品，带活动id
    if (this.data.activity_id) {
      json.activity_id = this.data.activity_id;
    }
    if (this.data.hasGoodOpenDF) {
      //有商品开启自定义表单
      json.order_goods = this._assembleDiyForm();
    }
    if (this.data.show_recharge_mobile) {
      //有商品开启话费慢充
      json.order_goods = JSON.stringify(this.assembleGoodsTELData());
    }
    if (this.options.electricity == "electricity") {
      //有商品开启话费慢充
      json.order_goods = JSON.stringify(this.assembleGoodsTELData());
    }
    //油卡充值
    if(this.data.oil_account && this.data.oil_mobile){
      json.order_goods = JSON.stringify(this.assembleGoodsTELData());
    }

    if (this.data.cpstype == "1") {
      json.recharge_number = this.data.cpsTxt;
    }

    if (this.data.camilo_resources_coupon_type == 1) {
      // 直冲需要填写帐号
      json.recharge_number = this.data.recharge_number;
    }

    json = this.handleDataActionBuyUrl(json, "order");
    json = this.handleDataActionCartUrl(json, "order");

    if (this.data._root_tag == "store") {
      json.store_id = this.data.store_id;
      json.mobile = this.data.linkinfo.mobile;
      json.realname = this.data.linkinfo.name;
      json.cart_ids = JSON.stringify(this.data.storeCarts);
    } else if (this.data._root_tag == "rentCartBuy" || this.data._root_tag == "rentBuy") {
      let right = wx.getStorageSync("rentTimeRight") || "";
      let choose = wx.getStorageSync("rentTimeChoose") || "";
      let self = wx.getStorageSync("rentTimeSelf") || "";
      let lease_term = {};
      if (!app._isTextEmpty(choose)) {
        lease_term = choose;
      } else if (!app._isTextEmpty(self)) {
        lease_term = self;
      }

      json.lease_rights = app._isTextEmpty(right) == null ? [] : right;
      json.lease_term = lease_term;
      json.cart_ids = JSON.stringify(this.data._cart_ids);
    }

    if (this.data.selected == 2 || this.data.selected == 8 || this.data.selected == 12 || this.data.selected == 15) {
      json.mobile = this.data.linkinfo.mobile;
      json.realname = this.data.linkinfo.name;

      if (this.data._root_tag === 'o2oDeposit') {
        // 门店定金  后端需要把门店的地址给传过去 #86280
        this.data.currentAddId = 1; //地址没有id  写死一个
        let arr = this.data.store_info.store_address.split(' ');
        this.setAddressViewData({
          province: arr[0],
          city: arr[1],
          district: arr[2],
          street: arr[3],
          address: arr[4],
          mobile: this.store_info.store_mobile,
          username: this.store_info.store_name,
          address_id: 1
        });
        json.address = encodeURIComponent(JSON.stringify(currentAddress));
        // 设置地址界面
      }
    }

    if (this.data.selected == 8 || this.data.selected == 12) {
      json.package_deliver_id = this.data.selected == 8 ? this.data.defaultSelfCarry.id : this.data.o2oSelfCarry.id;
      delete json.address;
    }

    if (this.data.selected == 3) {
      json.mobile = this.data.store_info.store_mobile;
      json.realname = this.data.store_info.store_name;
    }
    if (this.data.selected == 10) {
      json.supplier_driver_distribution_address = this.data.supp_point;
    }

    Object.assign(json, this.data.orderLocationObj);
    return json;
  },

  //支付协议
  agreementPaybtn(e) {
    let agreeBol = e.detail;
    this.setData({
      agreementPay: agreeBol,
    });
  },
  showPay() {
    this.setData({
      agreementPayShow: true,
    });
  },
  showPayClose() {
    this.setData({
      agreementPayShow: false,
    });
  },
  showDiy(e) {
    this.setData({
      "diyform.form_id": e.currentTarget.dataset.id,
      "diyform.pre_id": e.currentTarget.dataset.preid,
    });
    if (this._findDiyForm(e.currentTarget.dataset.preid)) {
      let diyform_data_id = this._findDiyForm(e.currentTarget.dataset.preid);
      this.setData({
        "diyform.diyform_data_id": diyform_data_id,
      });
    }
    this.setData({
      diyShow: true,
    });
  },
  showDiyClose() {
    this.setData({
      diyShow: false,
    });
  },
  traCheckedData(data) {
    console.log(data);
    this._setDiyForm(data.detail.pre_id, data.detail.diyform_data_id);
    this.showDiyClose();
  },
  getList(type) {
    let that = this;
    let _type = type;
    let urlStr = app.getNetAddresss("plugin.package-deliver.frontend.deliver.getList");
    if (_type == "o2o") {
      urlStr = app.getNetAddresss("plugin.package-deliver.frontend.store.deliver.getList");
    }
    let point = app.qqMapTransBMap(parseFloat(that.data.point.lng), parseFloat(that.data.point.lat));
    app._getNetWork({
      url: urlStr,
      data: {
        city_name: that.data.city,
        lat: point.lat,
        lng: point.lng,
        kwd: "",
        goods: JSON.stringify(this._assembleGoods()),
        store_id: this.data.options.store_id || 0,
        deliver_id: this.options.package_deliver_id|| ''
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (_type == "shop") {
            that.setData({
              defaultSelfCarry: JSON.stringify(that.data.defaultSelfCarry) == "{}" ? res.data.list.data[0] : that.data.defaultSelfCarry,
            });
          } else if (_type == "o2o") {
            if (!this.data.o2oSelfCarry.id) {
              this.setData({
                o2odeliverName: res.data.name,
                o2oSelfCarry: res.data.list.data[0] ? res.data.list.data[0] : "" //没有就取第一个为默认自提点
              });
            }
          }
        } else {
          wx.showToast({
            icon: "none",
            title: "获取自提点失败",
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //获取经纬度
  getCurrentOrderLocation() {
    wx.getLocation({
      type: "gcj02",
      success: (res) => {
        console.log("userLocationFlag", res);
        const latitude = res.latitude;
        const longitude = res.longitude;
        this._setOrderLocation({
          lat: latitude,
          lng: longitude,
        });
      },
    });
  },
  //根据经纬度转换具体地址名称
  _setOrderLocation(e) {
    let that = this;
    app
      .getReverseGeocoder(e.lat, e.lng)
      .then((res) => {
        console.log("userLocationFlag", res);
        let recommend = res.address_component;
        let orderLocationObj = {
          positioning_success: 1,
          province: recommend.province,
          city: !app._isTextEmpty(recommend.city) ? recommend.city : recommend.province,
        };
        that.data.orderLocationObj = orderLocationObj;
      })
      .catch((err) => {
        console.log(err);
      });
  },

  async checkAlbum(scopeName) {
    let writePhotosAlbum = await this.getAuthSetting(scopeName);
    return new Promise((resolve, reject) => {
      if (!writePhotosAlbum) {
        wx.showModal({
          title: "请开启授权",
          content: "是否跳转设置页开启授权",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting[scopeName]) {
                    resolve(true);
                  } else {
                    resolve(false);
                  }
                },
              });
            } else if (res.cancel) {
              resolve(false);
            }
          },
          fail: () => {
            resolve(false);
          },
        });
      } else resolve(true);
    });
  },
  getAuthSetting(authName) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (!res.authSetting[authName]) {
            wx.authorize({
              scope: authName,
              success() {
                resolve(true);
              },
              fail() {
                resolve(false);
              },
            });
          } else resolve(true);
        },
        fail() {
          resolve(false);
        },
      });
    });
  },
  toO2oSearchDiyBtn() {
    //门店搜索插件 自定义下单页按钮
    try {
      wx.redirectTo({
        url: this.data.storeSearchBtn.app_url,
      });
    } catch (e) {
      console.log(e);
    }
  },
  toFullPage() {
    // 跳转满额包邮页
    if (this.data._root_tag == this.data.TAG_ACTION_BUY) {
      //立即购买的，把他添加到购物车，从包邮页去结算变成购物车结算
      // 设置主要参数
      let urlStr = app.getNetAddresss("postageIncludedCategory.member-cart.store");
      app._postNetWork({
        url: urlStr,
        data: {
          goods_id: this.data._goodsId,
          total: this.data._total || 1,
          option_id: this.data._optionsId || 0
        },
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            let _cart_ids = [];
            _cart_ids.push(Number(res.data.cart_id));
            wx.navigateTo({
              url: '/packageE/orderullPackage/orderullPackage?cart_id=' + JSON.stringify(_cart_ids)
            });
          }
        },
        fail: (res) => {
          console.log(res);
        },
      });

    } else if (this.data._root_tag == this.data.TAG_ACTION_CART) {
      // 购物车下单 JSON.stringify(this.data._cart_ids)
      wx.navigateTo({
        url: '/packageE/orderullPackage/orderullPackage?cart_id=' + this.options.cart_ids
      });
    }
  },
  // 二开页面开发-胜天半子#79514
  onChange(e) {
    this.setData({
      sexSelect: e.detail
    });
  },
  cell_from_inp(e) {
    if (e.currentTarget.dataset.key == 'name') {
      this.setData({
        'design_info.userName': e.detail.value
      });
    }
    if (e.currentTarget.dataset.key == 'phone') {
      this.setData({
        'design_info.telNumber': e.detail.value
      });
    }
    if (e.currentTarget.dataset.key == 'adress') {
      this.setData({
        design_address: e.detail.value,
        'design_info.detailInfo': e.detail.value
      });
    }
  },
  tapShowArea() {
    this.setData({
      showArea: true
    });
  },
  confirmArea(e) {
    this.setData({
      userAdress: `${e.detail[0].name} ${e.detail[1].name} ${e.detail[2].name}`,
      'design_info.provinceName': e.detail[0].name,
      'design_info.cityName': e.detail[1].name,
      'design_info.countyName': e.detail[2].name
    });
  },
  changeCityDeliveryCommunity(e) {
    this.setData({
      cityDelivery_community_id: e.detail
    });
  },
  setCityDeliveryCommunity() {
    let cityDelivery_community = this.data.cityDelivery.community_setting.community_list.find((item) => {
      return item.id == this.data.cityDelivery_community_id;
    });
    this.setData({
      cityDelivery_community,
      selectCommunityShow: false
    });
  },
  openCityDeliveryDay() {
    this.selectComponent(`.deliveryTime`).setPopShow();
  },
  cityDeliveryDayConfirm(evt) {
    this.setData({
      cityDelivery_deliveryTime: evt.detail
    });
    this.handleBuy();
  },
});