var app = getApp()
var that=null
var sopenFrame=null
var areas = null;
var CompanyCert=null;
var CompanyPic=null;
var UserPic=null;
var BMap = null;
var bmap=null;
Page( {
  data: {
            loadingHidden:false,
            utype:0,
            contact:"",
            sfz:"",
            ncname:"",
            CompanyName:"",
            addpic0:"",
            addpic:"",
            addpic1:"",
            CompanyNumber:"",
            address:"",
            selectHidden:true,
            sectionHidden:true,
            IFDefault:1,
            Provinces:[],
            Citys:[],
            Countys:[],
            hx_index:-1,
            hx_index0:-1,
            hx_index1:-1,
            mapmsg:"",
            area:"",
            usernameHidden:true,
            sectionHidden0:true,
            savebutton:"保存",
            username:"",
            longitude: null,//经度
            latitude: null,//纬度 
            clongitude: null,//经度
            clatitude: null,//纬度 
            markers: [{ //标记点用于在地图上显示标记的位置
            id: 1,
            latitude: null,
            longitude: null,
            iconPath: '../../images/position-picker2.png',
            width: 60,
            height: 60,
            umoney:0.00,
            umoney0:0.00,
            }],
  },

  onLoad: function() {  
      that = this
      areas = require('../../area.js');
      that.setData({
          Provinces:areas.areaslist
      })
      that.rdata()
    },rdata: function() {
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      var userInfodata = wx.getStorageSync("userInfo")
      var userInfo = JSON.parse(userInfodata)
      that.setData({
        umoney:userInfo.xjjye,
        umoney0:userInfo.jdye
      })
      wx.request({
        url: app.globalData.apiurl + "/xapiajax.ashx", 
        data: { 
          action:"getuserinfo",
           userId:(!userId?"":userId),
           LoginId:(!LoginId?"":LoginId)
        },
        method:"GET",
        dataType:"json", 
        success (res) { 
          if(res.data.status==1){
              var utype=res.data.user.utype
              
              var username=res.data.user.username
              var contact=res.data.user.realname
              var ncname=res.data.user.ncname
              var sfz=res.data.user.sfz
              var addpic1=res.data.user.avatar
              UserPic=res.data.user.yavatar
              var CompanyName=res.data.user.CompanyName
              var CompanyNumber=res.data.user.CompanyNumber
              CompanyCert=res.data.user.yCompanyCert
              CompanyPic=res.data.user.yCompanyPic
              var addpic=res.data.user.CompanyCert
              var addpic0=res.data.user.CompanyPic
              var Province=res.data.user.Province
              var City=res.data.user.City
              var County=res.data.user.County
              var address=res.data.user.address
              var latitude=res.data.user.latitude
              var longitude=res.data.user.longitude
              var index=-1
              var index0=-1
              var index1=-1
             
              var provinces=that.data.Provinces
             
              for(var i=0;i<provinces.length;i++){
                    if(provinces[i].ProvinceID==Province){
                      index=i;
                      var citys=provinces[i].City;
                      for(var j=0;j<citys.length;j++){
                           if(citys[j].CityID==City){
                                index0=j;
                                var countys=citys[j].County;
                                for(var k=0;k<countys.length;k++){
                                     if(countys[k].CountyID==County){
                                          index1=k;
                                          break;
                                     }
                                    
                                }
                                break;
                           }
                           
                      }
                      break;
                    }
              }
             
               that.setData({
                hx_index: index
              })
              var citys=(index==-1?[]:that.data.Provinces[index].City)
              that.setData({
                Citys:citys,
                hx_index0: index0
              })
              var countys=(index0==-1?[]:that.data.Citys[index0].County)
              that.setData({
                Countys:countys,
                hx_index1: index1
              })
              var ProvinceName=(!that.data.Provinces[that.data.hx_index]?"":that.data.Provinces[that.data.hx_index].ProvinceName);
              var CityName=(!that.data.Citys[that.data.hx_index0]?"":that.data.Citys[that.data.hx_index0].CityName)
              var CountyName=(!that.data.Countys[that.data.hx_index1]?"":that.data.Countys[that.data.hx_index1].CountyName)
             
              var area=ProvinceName+CityName+CountyName
             
              that.setData({
                utype:utype,
                contact:contact, 
                ncname:ncname,
                sfz:sfz,
                CompanyName:CompanyName,
                CompanyNumber:CompanyNumber,
                addpic:addpic, 
                addpic0:addpic0,
                addpic1:addpic1,
                area:area,
                address:address,
                latitude:latitude,
                longitude:longitude,
                mapmsg:"您已标注",
                username:username,
                loadingHidden:true
               })
          }else{
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
             })
          }
          }
      })
      
            
    },onarea:function(e) {
      that.setData({
          sectionHidden:false
      })
    },ProvinceChange:function(e) {
      var index=e.detail.value;
      var citys=that.data.Provinces[index].City
      that.setData({
        hx_index: index,
        hx_index0: -1,
        hx_index1: -1,
        Citys:citys
      })
      if(citys.length==0){
        that.setData({
           sectionHidden:true,
           area:that.data.Provinces[that.data.hx_index].ProvinceName
         })
      }
    },CityChange:function(e) {
      var index=e.detail.value
      var countys=that.data.Citys[index].County
      that.setData({
        hx_index0: index,
        hx_index1: -1,
        Countys:countys
      })
      if(countys.length==0){
        that.setData({
           sectionHidden:true,
           area:that.data.Provinces[that.data.hx_index].ProvinceName+that.data.Citys[that.data.hx_index0].CityName
         })
      }
    },CountyChange:function(e) {
      that.setData({
        hx_index1: e.detail.value
      })
      that.setData({
        sectionHidden:true,
        area:that.data.Provinces[that.data.hx_index].ProvinceName+that.data.Citys[that.data.hx_index0].CityName+that.data.Countys[that.data.hx_index1].CountyName
      })
    },closesection:function(e) {
      that.setData({
        sectionHidden:true
      })
    },closesection0:function(e) {
      that.setData({
        sectionHidden0:true
      })
    },insection:function(e) {
      
    },saveaddress:function(e) {
      var username = ""
      var contact = e.detail.value.contact.replace(/\s+/g, "");
      var ncname="";
      var Province=(that.data.hx_index==-1?"":that.data.Provinces[that.data.hx_index].ProvinceID)
      var City=(that.data.hx_index0==-1?"":that.data.Citys[that.data.hx_index0].CityID)
      var County=(that.data.hx_index1==-1?"":that.data.Countys[that.data.hx_index1].CountyID)
      var sfz="";
      var address="";
      var CompanyName="";
      var CompanyNumber=""; 
      var Companylatitude="";
      var Companylongitude="";
      if(that.data.utype>0){
        CompanyName = e.detail.value.CompanyName.replace(/\s+/g, "");
        CompanyNumber =e.detail.value.CompanyNumber.replace(/\s+/g, ""); 
       
        Companylatitude=that.data.latitude;
        Companylongitude=that.data.longitude;
        address=e.detail.value.address.replace(/\s+/g, "");
    }else{
        ncname=e.detail.value.ncname.replace(/\s+/g, "");
        sfz=e.detail.value.sfz.replace(/\s+/g, "");
        address=e.detail.value.address.replace(/\s+/g, "");
    }
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      var b=true
       if(b){
      if(contact==null || contact==""){
          b=false
          wx.showToast({
            title: "姓名不能为空！",
            icon: "none",
            duration: 3000
           })
      }
      }
     
    if(that.data.utype>0){
      if(b){
       if(CompanyName==""){
           b=false
           wx.showToast({
              title: (that.data.index==1?"商家":"企业") + "名称不能为空！",
              icon: "none",
              duration: 3000
           })
       }
      }
      if(b){
        if(CompanyPic==null){
         b=false
         wx.showToast({
            title: "预览图片未上传！",
            icon: "none",
            duration: 3000
         })
        }
       }
      if(b){
       if(CompanyNumber==""){
        b=false
        wx.showToast({
           title: (that.data.index==1?"证件号码":"信用代码(营业执照号") + "不能为空！",
           icon: "none",
           duration: 3000
        })
       }
      }
      if(b){
       if(CompanyCert==null){
        b=false
        wx.showToast({
           title: (that.data.index==1?"证件":"营业执照") + "未上传！",
           icon: "none",
           duration: 3000
        })
       }
      }
    }
    
    if(b){
      if(that.data.hx_index==-1){
        b=false
        wx.showToast({
          title: "省份必须选择！",
          icon: "none",
          duration: 3000
         })
      }
    }
    if(b){
      if(that.data.hx_index0==-1){
        b=false
        wx.showToast({
          title: "城市必须选择！",
          icon: "none",
          duration: 3000
         })
      }
    }
   
    if(that.data.utype>0){
      if(b){
        if(address==""){
          b=false
          wx.showToast({
            title: "详细地址不能为空！",
            icon: "none",
            duration: 3000
           })
        }
      }
      if(b){
       if(Companylatitude==""||Companylongitude==""){
        b=false
        wx.showToast({
           title: "未标注地图！",
           icon: "none",
           duration: 3000
        })
       }
      }
     }
      if(b){
        that.setData({
          savebutton:"请稍候..."
      })
      wx.request({
        url: app.globalData.apiurl + "/xapiajax.ashx", 
        data: { 
          action:"updateUserInfo2",
           userId:(!userId?"":userId),
           LoginId:(!LoginId?"":LoginId),
           contact:contact,
           ncname:ncname,
           UserPic:UserPic,
           sfz:sfz,
           CompanyName:CompanyName,
           CompanyNumber:CompanyNumber,
           CompanyCert:CompanyCert,
           CompanyPic:CompanyPic,
           Province:Province,
           City:City,
           County:County,
           address:address,
           Companylatitude:Companylatitude,
           Companylongitude:Companylongitude
        },
        method:"POST",
        dataType:"json", 
        header: { 
          "content-type": "application/x-www-form-urlencoded" // 默认值
        },
        success (res) { 
          if(res.data.status==1){
            wx.showModal({
              title: "操作提示",
              content: res.data.msg,
              showCancel:false,
              success (res0) {
                if (res0.confirm) {
                  wx.setStorageSync('userInfo', JSON.stringify(res.data.userInfo)) 
                  app.globalData.IFRefreshmy=1
                  wx.navigateBack({})
                }
              }
             })
          }else{
             wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
             })
          }
          that.setData({
            savebutton:"保存"
        })
          }
      })
      }
    },onaddpic:function(e) {
      if(that.data.addpic=="../../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;
              
              that.setData({
                  addpic:"../../images/ajaxLoader.gif"
              })
              wx.uploadFile({
                url: app.globalData.apiurl + "/xapiajax.ashx", //仅为示例，非真实的接口地址
                filePath: tempFilePaths[0],
                name: 'image',
                formData: {
                  action:"uploadtempImage"
                },
                fail: function(err) {
                  wx.showToast({
                    title: "上传出错了",
                    icon: "none",
                    duration: 2000
                })
                that.setData({
                  addpic:"../../images/add.png"
            })
                },
                success (res0){
                    var data=JSON.parse(res0.data);
                    
                   
                    if(data.status==1){
                      wx.showToast({
                        title: data.msg,
                        icon: "success",
                        duration: 1000
                      })
                         CompanyCert=data.pic;
                         that.setData({
                             addpic:data.url
                        })
                    }else{
                      wx.showToast({
                        title: data.msg,
                        icon: "none",
                        duration: 2000
                    })
                      that.setData({
                            addpic:"../../images/add.png"
                      })
                    }
                  
                }
              });
        }
      })
    }
    },onaddpic0:function(e) {
      if(that.data.addpic0=="../../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;
              
              that.setData({
                  addpic0:"../../images/ajaxLoader.gif"
              })
              wx.uploadFile({
                url: app.globalData.apiurl + "/xapiajax.ashx", //仅为示例，非真实的接口地址
                filePath: tempFilePaths[0],
                name: 'image',
                formData: {
                  action:"uploadtempImage"
                },
                success (res0){
                    var data=JSON.parse(res0.data);
                    
                   
                    if(data.status==1){
                      wx.showToast({
                        title: data.msg,
                        icon: "success",
                        duration: 1000
                      })
                         CompanyPic=data.pic;
                         that.setData({
                             addpic0:data.url
                        })
                    }else{
                      wx.showToast({
                        title: data.msg,
                        icon: "none",
                        duration: 2000
                    })
                      that.setData({
                            addpic0:"../../images/add.png"
                      })
                    }
                  
                }
              });
        }
      })
    }
    },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
                      })
                         UserPic=data.pic;
                         that.setData({
                             addpic1:data.url
                        })
                    }else{
                      wx.showToast({
                        title: data.msg,
                        icon: "none",
                        duration: 2000
                    })
                      that.setData({
                            addpic1:"../../images/add.png"
                      })
                    }
                  
                }
              });
        }
      })
    }
    },getaddressValue:function(e) {
       that.setData({
           Companyaddress:e.detail.value
       })
    },maptap(e){
      if(e.detail){
      var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
      that.setData({ 
        latitude: e.detail.latitude,
        longitude: e.detail.longitude,
        [str]: e.detail.longitude,
        [str2]: e.detail.latitude,
       });
      }
    },my_location(e) {
        //微信API定位,获取当前位置经纬度
      
    },markertap(e) {
    },regionchange(e){ 
      if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
          that.bmap.getCenterLocation({
          success: function (res) {
            latitude = res.latitude;
            longitude = res.longitude;
            var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
            that.setData({
              longitude: res.longitude,
              latitude: res.latitude,
              clongitude: res.longitude,
              clatitude: res.latitude,
              [str]: res.longitude,
              [str2]: res.latitude,
            })
          }
        })
      }
    }
    ,onmap:function() {
        
       
        
    if(that.data.latitude&&that.data.longitude){
      that.setData({
        sectionHidden0:false
    })
    that.mapCtx = wx.createMapContext('myMap')
    // 实例化百度地图API核心类
    bmap = new BMap.BMapWX({
      ak: 'HiMGaFNdmB2VSvWSkPogESxBDaLQkOuq'
    })
      var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
      that.setData({ 
        clatitude: that.data.latitude,
        clongitude: that.data.longitude,
        [str]: that.data.longitude,
        [str2]: that.data.latitude,
       });
    
    }else{
    if (that.data.hx_index!=-1 && that.data.hx_index0!=-1 && that.data.hx_index1!=-1 && that.data.Companyaddress!="") {
      that.setData({
        sectionHidden0:false
    })
    that.mapCtx = wx.createMapContext('myMap')
    // 实例化百度地图API核心类
    bmap = new BMap.BMapWX({
      ak: 'HiMGaFNdmB2VSvWSkPogESxBDaLQkOuq'
    })
      var fail = function(data) { 
        console.log(data) 
      }; 
      var success = function(data) { 
        var wxMarkerData = data.wxMarkerData; 
        var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
        that.setData({ 
          latitude: wxMarkerData[0].latitude,
          longitude: wxMarkerData[0].longitude,
          clatitude: wxMarkerData[0].latitude,
          clongitude: wxMarkerData[0].longitude,
          [str]: wxMarkerData[0].longitude,
          [str2]: wxMarkerData[0].latitude,
         });
      } 
    // 发起geocoding检索请求 
    var area = "";
    if(that.data.Provinces[that.data.hx_index]){
         area = that.data.Provinces[that.data.hx_index].ProvinceName;
    }
    if(that.data.Citys[that.data.hx_index0]){
         area += that.data.Citys[that.data.hx_index0].CityName;
    }
    if(that.data.Countys[that.data.hx_index1]){
         area += that.data.Countys[that.data.hx_index1].CountyName;
    }
    bmap.geocoding({ 
        address: area+that.data.Companyaddress, 
        fail: fail, 
        success: success
    }); 
       
    } else {
      wx.showToast({
        title: "请先选择区域和填写地址！",
        icon: "none",
        duration: 3000
    })
    }
  }
    },onupdated: function(e)  {
      that.setData({ 
        loadingHidden:true
     })
    },qcbz:function(e) {
      var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
      that.setData({
        latitude:null,
        latitude:null,
        clatitude:null,
        clatitude:null,
        [str]: null,
        [str2]: null,
        sectionHidden0:true,
        mapmsg:"" 
     })
    },qybz:function(e) {
      if(that.data.latitude&&that.data.longitude){
       that.setData({
          sectionHidden0:true,
          mapmsg:"已标注" 
       })
      }else{
         wx.showToast({
             title: "请点击地图标注！",
             icon: "none",
             duration: 3000
         })
      }
    }
})
