var app = getApp()
var that=null
var sopenFrame=null
var yunfeis=[]
var ZSubTotal=0.00
var ZSubTotal2=0.00
var Guests=""
Page( {
  data: {
    cartImg: '../../images/cart-null.png',
    tipWords: '购物车空空如也',
    addressId:0,
    contact:"",
    phone:"",
    area:"",
    province:"",
    city:"",
    county:"",
    address:"",
    contact0:"",
    phone0:"",
    area0:"",
    address0:"",
    distance0:0,
    a_name:"",
    a_tel:"",
    agentid:0,
    agenttype:0,
    productHidden:false,
    noproductHidden:true,
    loadingHidden:false,
    footerHidden:false,
    image:"",
    image0:"",
    addpic1:"../../images/add.png",
    addpic2:"../../images/add.png",
    ttype:0,
    IFFQPT:0,  
    FHEnable2:"0",
    zftype:0,
    kjpay:0,
    peitype:0,
    p_peitype:0,
    p_peitype0:0,
    pttypes:[],
    pttype:0,
    IFKD:0,
    ifxn:0,
    dhjye:0.00,
    btjje:0.00,
    xjjje:0.00,
    zyunfei:0.00,
    cartproducts:[],
    cart_Total:"￥0.00",
    cart_Total_title:"总计（包含运费）",
    savebutton:"确认购买",
    savebutton0:"确认支付",
    ifkjpay:0,
    bankid:0,
    dhjjg:0,
    banks:[],
    bankindex:0,
    myphone:"",
    PayID:"",
    IFkjPaying:0,
    IFQYPay:0,
    a_code:"",
    a_pwd:""
  },

  onLoad: function() {
      that = this
          that.rdata(0);  
      
       
      sopenFrame=setInterval(function (){
        
        if(app.globalData.IFRefreshsell==1){
            var id=app.globalData.selladdress.id
            var contact=app.globalData.selladdress.contact
            var tel=app.globalData.selladdress.tel
            var address=app.globalData.selladdress.address
            that.setData({
              addressId:id,
              contact:contact,
              phone:tel,
              province:app.globalData.selladdress.Province,
              city:app.globalData.selladdress.City,
              county:app.globalData.selladdress.County,
              address:address
            })
            app.globalData.IFRefreshsell=0
            that.getyunfei(app.globalData.selladdress.Province)
        }
        if(app.globalData.IFRefreshsell0==1){
          var addressId=app.globalData.selladdress0.addressId
          var agenttype=app.globalData.selladdress0.type
          var contact=app.globalData.selladdress0.contact
          var tel=app.globalData.selladdress0.tel
          var area=app.globalData.selladdress0.area
          var address=app.globalData.selladdress0.address
          var distance=app.globalData.selladdress0.distance
          app.globalData.IFRefreshsell0=0
          that.setData({
            agentid:addressId,
            agenttype:agenttype,
            contact0:contact,
            phone0:tel, 
            area0:area,
            address0:address,
            distance0:distance
          })
          
        }
        if(app.globalData.IFRefreshsell1==1){
             that.rdata(0);  
             app.globalData.IFRefreshsell1=0
         }
      }, 1000);
    },
    onShow: function() {
      if(app.globalData.IFRefreshsell==1){
            var id=app.globalData.selladdress.id
            var contact=app.globalData.selladdress.contact
            var tel=app.globalData.selladdress.tel
            var address=app.globalData.selladdress.address
            that.setData({
              addressId:id,
              contact:contact,
              phone:tel,
              province:app.globalData.selladdress.Province,
              city:app.globalData.selladdress.City,
              county:app.globalData.selladdress.County,
              address:address
            })
            app.globalData.IFRefreshsell=0
            that.getyunfei(app.globalData.selladdress.Province)
        }
    },onPullDownRefresh: function () {
      //在当前页面显示导航条加载动画
       wx.showNavigationBarLoading(); 
      //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
      wx.showLoading({
          title: '刷新中...',
      })
      that.rdata(1)
  },rdata: function(t) {
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      var CartId = wx.getStorageSync("CartId")
      var latitude = wx.getStorageSync("latitude")
      var longitude = wx.getStorageSync("longitude")
      var userInfodata = wx.getStorageSync("userInfo")
      if(userId&&LoginId&&userInfodata){
        var userInfo = JSON.parse(userInfodata)
        that.setData({
          kjpay:userInfo.kjpay,
          dhjye:userInfo.mfye
     })
      wx.request({
        url: app.globalData.apiurl + "/xapiajax.ashx", 
        data: { 
          action:"getshopcart2",
           userId:(!userId?"":userId),
           LoginId:(!LoginId?"":LoginId),
           latitude:(!latitude?"":latitude),
           longitude:(!longitude?"":longitude),
           CartId:(!CartId?"":CartId)
        },
        method:"GET",
        dataType:"json", 
        header: { 
          "content-type": "application/json" // 默认值
        },
        success (res) { 
            if(res.data.status==1){
            yunfeis=res.data.yunfeis
            ZSubTotal=res.data.ZSubTotal
            ZSubTotal2=res.data.ZSubTotal2
            that.setData({
                 ttype:res.data.ttype,
                 p_peitype:res.data.peitype,
                 p_peitype0:res.data.peitype0,
                 peitype:(res.data.peitype==0&&res.data.peitype0==1?1:0),
                 ifkjpay:res.data.ifkjpay,
                 bankid:(res.data.kjpaybanks.length>0?res.data.kjpaybanks[0].value:0),
                 banks:res.data.kjpaybanks,
                 cartproducts:res.data.productlist,
                 cart_Total:"￥"+res.data.ZSubTotal,
                 contact0:(res.data.addresss.length>0?res.data.addresss[0].contact:""),
                 phone0:(res.data.addresss.length>0?res.data.addresss[0].tel:""),
                 area0:(res.data.addresss.length>0?res.data.addresss[0].area:""),
                 address0:(res.data.addresss.length>0?res.data.addresss[0].address:""),
                 distance0:(res.data.addresss.length>0?res.data.addresss[0].distance:""),
                 agentid:(res.data.addresss.length>0?res.data.addresss[0].addressId:0),
                 agenttype:(res.data.addresss.length>0?res.data.addresss[0].type:0),
                 zftype:(res.data.ttype) // 当ttype==0时默认选择兑换券抵扣
             })
             
            
             wx.setStorageSync('addresss', JSON.stringify(res.data.addresss))
            if(res.data.productlist.length>0){
              that.setData({
                  productHidden:false, 
                  noproductHidden:true,
                  footerHidden:false
              })
            }else{
              that.setData({
                productHidden:true,
                noproductHidden:false,
                footerHidden:true
               })
            }
            if(res.data.address.length>0){
              var id=res.data.address[0].addressId
              var contact=res.data.address[0].contact
              var tel=res.data.address[0].tel
              var address=res.data.address[0].area+res.data.address[0].detail
              that.getyunfei(res.data.address[0].Province)
              that.setData({
                addressId:id,
                contact:contact,
                phone:tel,
                province:res.data.address[0].Province,
                city:res.data.address[0].City,
                county:res.data.address[0].County,
                address:address
              })
            }else{
              var Locationprovince = wx.getStorageSync("Locationprovince")
              if(Locationprovince){
                    that.getyunfei(Locationprovince)
              }
            }
            
            that.setData({
                loadingHidden:true
            })
          }else{
             wx.showToast({
                 title: res.data.msg,
                 icon: "none",
                 duration: 2000
             })
             that.setData({
                 loadingHidden:true
             })
             if(res.data.msg=="您未登录"||res.data.msg=="参数错误"){
                 wx.removeStorageSync('userId')
                 wx.removeStorageSync('LoginId')
                 wx.navigateBack({})
             }
          }
          if(t==1){
            //隐藏loading 提示框
            wx.hideLoading();
            //隐藏导航条加载动画
            wx.hideNavigationBarLoading();
            //停止下拉刷新
            wx.stopPullDownRefresh();
         }
          }
      })
    }else{
          wx.navigateTo({  
          url: "../login/index"
       })
    }
    },getyunfei:function(ProvinceID) {
      
      if(that.data.peitype==0){
        var userId = wx.getStorageSync("userId")
        var LoginId = wx.getStorageSync("LoginId")
        var province = that.data.province
        var city = that.data.city
        var county = that.data.county
        if(province!=""&&city!=""&&county!=""){
        wx.request({
          url: app.globalData.apiurl + "/xapiajax.ashx", 
          data: {   
            action:"getyunfei",
            userId:(userId==null?"":userId),
            LoginId:(LoginId==null?"":LoginId),
            province:province,
            city:city,
            county:county
          },
          method:"POST",
          dataType:"json", 
          header: { 
               "content-type": "application/x-www-form-urlencoded" // 默认值
          },
          success (res0) { 
              if(res0.data.status==1){
                that.setData({
                  zyunfei:res0.data.yunfei
              })
              }else{
                wx.showToast({
                  title: res0.data.msg,
                  icon: "none",
                  duration: 2000
              }) 
              }
          }
        })
      }
        /*for(var i=0;i<yunfeis.length;i++){
              if(yunfeis[i].ProvinceID==ProvinceID){
                  that.setData({
                      zyunfei:yunfeis[i].yunfei
                  })
              }
        }*/
        }else{
          that.setData({
             zyunfei:0
           })
        }
       
        var cart_Total=(parseFloat(ZSubTotal) + parseFloat(that.data.zyunfei));
        if(that.data.ttype==0||that.data.ttype==12||that.data.ttype==14){
          that.setData({
            btjje:app.changeTwoDecimal_f(ZSubTotal),
            xjjje:app.changeTwoDecimal_f((parseFloat(ZSubTotal)-parseFloat(ZSubTotal2)+parseFloat(that.data.zyunfei)))
          })
         }
        that.setData({
              cart_Total:"￥"+app.changeTwoDecimal_f(cart_Total)
        })
        if(that.data.ttype==0){
            that.setData({
              cart_Total:"￥"+app.changeTwoDecimal_f(cart_Total)
            })
         }
    },onaddpic1:function(e) {
      if(that.data.addpic1=="../../images/ajaxLoader.gif"){
        wx.showToast({
          title: "正在上传中...",
          icon: "none",
          duration: 3000
         })
      }else{
      wx.chooseImage({
        count: 1,
        sizeType: ['original'],
        sourceType: ['album', 'camera'],
        success (res) {
              const tempFilePaths = res.tempFilePaths;
              var userId = wx.getStorageSync("userId")
              var LoginId = wx.getStorageSync("LoginId")
              that.setData({
                  addpic1:"../../images/ajaxLoader.gif"
              })
              wx.uploadFile({
                url: app.globalData.apiurl + "/xapiajax.ashx", //仅为示例，非真实的接口地址
                filePath: tempFilePaths[0],
                name: 'image',
                formData: {
                  action:"uploadtempImage",
                  userId:(!userId?"":userId),
                  LoginId:(!LoginId?"":LoginId) 
                },
                success (res0){
                    var data=JSON.parse(res0.data);
                    
                   
                    if(data.status==1){
                      wx.showToast({
                        title: data.msg,
                        icon: "success",
                        duration: 1000
                      })
                         
                         that.setData({
                             image:data.pic,
                             addpic1:data.url
                        })
                    }else{
                      wx.showToast({
                        title: data.msg,
                        icon: "none",
                        duration: 2000
                    })
                      that.setData({
                            addpic1:"../../images/add.png"
                      })
                    }
                  
                }
              });
        }
      })
    }
    },onaddpic2:function(e) {
      if(that.data.addpic2=="../../images/ajaxLoader.gif"){
        wx.showToast({
          title: "正在上传中...",
          icon: "none",
          duration: 3000
         })
      }else{
      wx.chooseImage({
        count: 1,
        sizeType: ['original'],
        sourceType: ['album', 'camera'],
        success (res) {
              const tempFilePaths = res.tempFilePaths;
              var userId = wx.getStorageSync("userId")
              var LoginId = wx.getStorageSync("LoginId")
              that.setData({
                  addpic2:"../../images/ajaxLoader.gif"
              })
              wx.uploadFile({
                url: app.globalData.apiurl + "/xapiajax.ashx", //仅为示例，非真实的接口地址
                filePath: tempFilePaths[0],
                name: 'image',
                formData: {
                  action:"uploadtempImage",
                  userId:(!userId?"":userId),
                  LoginId:(!LoginId?"":LoginId) 
                },
                success (res0){
                    var data=JSON.parse(res0.data);
                    
                   
                    if(data.status==1){
                      wx.showToast({
                        title: data.msg,
                        icon: "success",
                        duration: 1000
                      })
                         
                         that.setData({
                             image0:data.pic,
                             addpic2:data.url
                        })
                    }else{
                      wx.showToast({
                        title: data.msg,
                        icon: "none",
                        duration: 2000
                      })
                      that.setData({
                            addpic2:"../../images/add.png"
                      })
                    }
                  
                }
              });
        }
      })
    }
    },selectaddress:function(e) {
      wx.setStorageSync('qygm', 1)
      wx.navigateTo({  
         url: "../myaddress/index"
      })
   },selectaddress0:function(e) {
    wx.navigateTo({  
       url: "../qhaddress/index"
    })
   },getGuestsValue:function(e) {
        Guests=e.detail.value
   },getnameValue:function(e) {
       that.setData({
           a_name:e.detail.value
       })
        
   },gettelValue:function(e) {
       that.setData({
          a_tel:e.detail.value
       })
        
   },getcodeValue:function(e) {
    that.setData({
       a_code:e.detail.value
    })
     
},getmmValue:function(e) {
  that.setData({
     a_pwd:e.detail.value
  })
   
},BankChange:function(e) {
      var index=e.detail.value;
      var value=that.data.banks[index].value
      that.setData({
        bankindex: index,
        bankid:value
      })
},getopenid:function() {
  wx.login({
    success: function (resc) {
        if (resc.code) {
            var code=resc.code;
            wx.request({
              url: app.globalData.apiurl + "/xapiajax.ashx", 
              data: {   
                action:"getopenid",
                code:code
              },
              method:"POST",
              dataType:"json", 
              header: { 
                   "content-type": "application/x-www-form-urlencoded" // 默认值
              },
              success (res0) { 
                  if(res0.data.status==1){
                     wx.setStorageSync("openid", res0.data.openid)
                     that.Shop_Pay()
                  }else{
                    wx.showToast({
                      title: res0.data.msg,
                      icon: "none",
                      duration: 2000
                  }) 
                  }
              }
            })
        }
      }
    })
},Shop_Pay:function(e) {
      var bb=true
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      var CartId = wx.getStorageSync("CartId")
      if(that.data.peitype==0){
          if(that.data.addressId==0){
              bb=false
              wx.showToast({
                  title: "请选择收货人地址",
                  icon: "none",
                  duration: 2000
              })
         }
      }else{
         if(that.data.a_name.replace(/\s+/g, "")==""){
             bb=false
             wx.showToast({
                  title: "取货人不能为空",
                  icon: "none",
                  duration: 2000
             })
         } 
         if(bb){
           if(that.data.a_tel.replace(/\s+/g, "")==""){
              bb=false
              wx.showToast({
                  title: "手机号不能为空",
                  icon: "none",
                  duration: 2000
              })
           } 
        }
        if(bb){
          if(that.data.agentid==0){
             bb=false
             wx.showToast({
                 title: "取货地址必须选择",
                 icon: "none",
                 duration: 2000
             })
          }
        }
      }
      if(bb){
        if(that.data.zftype==-1){
           bb=false
           wx.showToast({
               title: "请先选择支付方式",
               icon: "none",
               duration: 2000
           })
        }
      }
      var openid = null
      if(bb){
          openid = wx.getStorageSync("openid");
          if(that.data.zftype==2){
          if(openid!=null){
            if(openid==""){
              bb=false
              that.getopenid()
            }
          }else{
            bb=false
            that.getopenid()
          }
        }
      }
      if(bb){
       
        if(that.data.IFQYPay==0&&that.data.zftype!=2){
          that.setData({
            IFQYPay:1
          }) 
        }else{
          if(bb){
            if(that.data.zftype!=2){
            if(that.data.a_pwd.replace(/\s+/g, "")==""){
               bb=false
               wx.showToast({
                   title: "密码不能为空",
                   icon: "none",
                   duration: 2000
               })
            } 
          }
         }
         if(bb){
            if(that.data.savebutton=="确认购买"){
            
         that.setData({
             savebutton:"请稍候..."
         }) 
        
         wx.request({
          url: app.globalData.apiurl + "/xapiajax.ashx", 
          data: {   
            action:"qygm",
             userId:(!userId?"":userId),
             LoginId:(!LoginId?"":LoginId), 
             CartId:(!CartId?"":CartId),
             pwd:that.data.a_pwd,
             openid:(!openid?"":openid),
             zftype:that.data.zftype,
             peitype:that.data.peitype,
             pttype:that.data.pttype,
             bankid:that.data.bankid,
             addressId:that.data.addressId,
             name:that.data.a_name,
             tel:that.data.a_tel,
             agentid:that.data.agentid,
             agenttype:(!that.data.agenttype?1:that.data.agenttype),
             Guests:Guests,
             image:that.data.image,
             image0:that.data.image0
          },
          method:"POST",
          dataType:"json", 
          header: { 
               "content-type": "application/x-www-form-urlencoded" // 默认值
          },
          success (res0) { 
            console.log('res0为:', res0.data);
            console.log('zftype:', that.data.zftype);
              if(res0.data.status==1){
                if(that.data.zftype==4){
                  if(res0.data.IFSendSms==1){
                      that.setData({
                           myphone:res0.data.bankphone,
                           PayID:res0.data.PayID,
                           IFkjPaying:1
                      })
                   }else{
                    wx.showToast({
                      title: res0.data.SendSmsErr,
                      icon: "none",
                      duration: 3000
                     })
                   }
                }else if(that.data.zftype==2){
                  console.log('ResultId:', res0.data.ResultId);
                    if(res0.data.ResultId>0){
                      console.log('开始微信支付:', 1);
                     wx.requestPayment({ 
                  timeStamp: res0.data.timeStamp,
                  nonceStr: res0.data.noncestr,
                  package: res0.data.package,
                  signType: res0.data.signType,
                  paySign: res0.data.paySign,
                  success (res) { 
                    console.log('开始微信支付:',2);
                      wx.navigateTo({  
                        url: "../myorder/index?nav=0"
                       })
                  
                  },
                  fail (res) {  
                    //JSON.stringify(res)
                    console.log('开始微信支付:',res);
                    wx.showToast({
                    title: "支付失败",
                    icon: "none",
                    duration: 1000
                   })
                   //wx.navigateBack({})
                    }
                   })
                 }
              }else{
                  wx.showToast({
                     title: res0.data.msg,
                     icon: "none",
                     duration: 3000
                  })
                  wx.navigateTo({  
                    url: "../myorder/index?nav=0"
                   })
              
              }
              wx.setStorageSync('userInfo', JSON.stringify(res0.data.userInfo)) 
              that.setData({
                dhjye:res0.data.userInfo.dhjye
              })
              app.globalData.IFRefreshmy=1
              }else{
                
                wx.showToast({
                  title: res0.data.msg,
                  icon: "none",
                  duration: 3000
               })
              }
              that.setData({
                savebutton:"确认购买"
              })
            }
        })
            }
      }
    }
        }
    },Shop_Pay0:function(e) {
      var bb=true
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      
          if(that.data.IFkjPaying==0 || that.data.PayID==""){
              bb=false
              wx.showToast({
                  title: "还没有发送短信",
                  icon: "none",
                  duration: 2000
              })
         }
         if(bb){
         if(that.data.a_code.replace(/\s+/g, "")==""){
          bb=false
          wx.showToast({
               title: "验证码不能为空",
               icon: "none",
               duration: 2000
          })
          } 
       }
      if(bb){
        
     

            if(that.data.savebutton0=="确认支付"){
           
         that.setData({
             savebutton0:"请稍候..."
         }) 
        
         wx.request({
          url: app.globalData.apiurl + "/xapiajax.ashx", 
          data: {   
            action:"kjpay",
             userId:(!userId?"":userId),
             LoginId:(!LoginId?"":LoginId), 
             payid:that.data.PayID,
             sms_code:that.data.a_code
          },
          method:"POST",
          dataType:"json", 
          header: { 
               "content-type": "application/x-www-form-urlencoded" // 默认值
          },
          success (res0) { 
           
              if(res0.data.status==1){
                
                 if(res0.data.msg=="交易处理中"){
                  wx.showModal({
                    title: "操作提示",
                    content: res0.data.msg,
                    showCancel:false,
                    success (res1) {
                      if (res1.confirm) {
                        var sflash=setInterval(function (){
                          wx.navigateTo({  
                              url: "../myorder/index?t=" + that.data.ttype + "&nav=0"
                           })
                          clearInterval(sflash)
                       }, 6000);
                        
                      }
                    }
                  })
                    
                 }else{
                  wx.showModal({
                    title: "操作提示",
                    content: res0.data.msg,
                    showCancel:false,
                    success (res1) {
                      if (res1.confirm) {
                        wx.navigateTo({  
                          url: "../myorder/index?t=" + that.data.ttype + "&nav=0"
                         })
                      }
                    }
                  })
                 }
              }else{
                
                wx.showToast({
                  title: res0.data.msg,
                  icon: "none",
                  duration: 3000
               })
              }
              that.setData({
                savebutton0:"确认支付"
              })
            }
        })
      }
      }
  
        
    },
    closeaddcart:function(e) {
        that.setData({
            IFkjPaying:0
        })
    },
    closeaddcart0:function(e) {
        that.setData({
            IFQYPay:0
        })
    },inaddcart:function(e) {
   
    },onpttype:function(e) {
      var pttype = e.currentTarget.dataset.id
      that.setData({
           pttype:pttype
      })
      
  },onpeitype:function(e) {
    var index = e.currentTarget.dataset.id
    that.setData({
      peitype:index
    })
    if(that.data.peitype==0){
        that.getyunfei(that.data.selProvince);
    }else{
        that.getyunfei("");
    }
},onpay:function(e) {
        var id = e.currentTarget.dataset.id
        
        if(id==4){
              
              if(that.data.ifkjpay==1){
                 that.setData({
                    zftype:id
                 })
              }else{
                wx.setStorageSync('qygm', 1)
                wx.navigateTo({  
                  url: "../kjpay/index"
               })
              }
          
        }else{
          that.setData({
            zftype:id
           })
        }
    },gotodetail:function(e) {
      var id = e.currentTarget.dataset.id
      wx.navigateTo({  
        url: "../details/index?id="+id
     })
    }
})
