var util = require('../../../utils/util.js');
var bmap = require('../../../libs/bmap-wx.js'); 
var wxMarkerData = []; 
const app = getApp();

//用于保存BMap.search接口返回的数据
var wxMarkerData = []


Page({

  data: {
 
    location: '', 
  

    allDisabled:true,//有客户下拉时临时用来控制其他下拉不显示
    c_txt_Show:false,
    customerShow:false,
    customerNameList: [
      // {"id":"1","name":" 海文牧场"},{"id":"2","name":"13140成宏牧场"},{"id":"3","name":"13153瑞福牧业"},{"id":"4","name":"13314宇瑞牧场"},{"id":"5","name":"13315品源牧业"},{"id":"6","name":"17143冠县润强奶牛养殖专业合作社"},{"id":"7","name":"20128建国牧场"},{"id":"8","name":"20158光明牧场"},{"id":"9","name":"20333万发牧场"},{"id":"10","name":"20777迅达牧场"},{"id":"11","name":"20789盛源牧场"},{"id":"12","name":"20928永福牧场"},{"id":"13","name":"20987繁荣牧场"},{"id":"14","name":"21061青岛绿草原牧场"},{"id":"15","name":"21194青岛浩德瑞牧业有限公司（转东营民和牧业有限公司安装）"},{"id":"16","name":"858吉祥奶牛场"},{"id":"17","name":"hlj030"},{"id":"18","name":"一家村牧场"},{"id":"19","name":"一康牧业"},{"id":"20","name":"一康牧场"},{"id":"21","name":"万兴牧场"},{"id":"22","name":"万利刚牧场"},{"id":"23","name":"万利奶牛养殖专业合作社"},{"id":"24","name":"万合牧场（辽宁）"},{"id":"25","name":"万胜牧业有限公司"},{"id":"26","name":"万花牧场"},{"id":"27","name":"万荷牧场"},{"id":"28","name":"万隆兴牛场"},{"id":"29","name":"三元御道口牧场"},{"id":"30","name":"三元牧场"},{"id":"31","name":"三元绿荷第一牧场"},{"id":"32","name":"三元绿荷第二牧场"},{"id":"33","name":"三河绿源牧场"},{"id":"34","name":"三河鑫隆奶牛养殖有限公司"},{"id":"35","name":"三源牧业"},{"id":"36","name":"三源牧业13326"},{"id":"37","name":"上东佳宝牧业"},{"id":"38","name":"上海光明荷斯坦金山种奶牛场"},{"id":"39","name":"上海忆南养殖场"},{"id":"40","name":"上海申星奶牛场"},{"id":"41","name":"上海百立生物科技有限公司"},{"id":"42","name":"上海金山忆南牧场"},{"id":"43","name":"上海鼎健饲料有限公司"},{"id":"44","name":"上禾牧业"},{"id":"45","name":"上陵众牛"},{"id":"46","name":"上陵俊佑"},{"id":"47","name":"上陵奥兰"},{"id":"48","name":"上陵澳兰"},{"id":"49","name":"上陵牧原"},{"id":"50","name":"上陵翔达"},{"id":"51","name":"下寨合作社"},{"id":"52","name":"世强牧业"},{"id":"53","name":"世强牧业13384"},{"id":"54","name":"东利牧业"},{"id":"55","name":"东升牧场"},{"id":"56","name":"东平县戴庙乡兴达奶牛养殖专业合作社"},{"id":"57","name":"东方牧场"},{"id":"58","name":"东旭养殖场"},{"id":"59","name":"东旭牧场"},{"id":"60","name":"东昌牧业"},{"id":"61","name":"东海县益多牧业有限公司"},{"id":"62","name":"东海牧场"},{"id":"63","name":"东甲兰牧场"},{"id":"64","name":"东营市柏拉蒙奶牛繁育有限公司"},{"id":"65","name":"东营民和牧业有限公司"},{"id":"66","name":"东鑫奶牛养殖专业合作社"}
    ],
    customerIndex:'',
    customerId:'',

 
    receiverShow:false,
    r_txt_Show:false,
    receiverChoose:'false',
    telephone:"",


    receiverNameList: [
        // {id: 56, name: "Epans"},{id: 58, name: "Derek"}
    ],
    receiverIndex:'',
    receiverId:'',
    nextNameList: [
      // {id: 222, name: "拜访"}, {id: 223, name: "远程服务"}, {id: 224, name: "现场服务"}
    ],
    nextIndex:'',
    nextId:'',
    groupId: '', 
    groupName: '',

    scenePhotoUrlList:[],
    picIsLoading:false,
 
    rules: {
      customerName: [{ required: true, message: '客户必填', trigger: 'blur' }],
      vdate: [{ required: true, message: '拜访日期必填', trigger: 'blur' }],
      location: [{ required: true, message: '必填', trigger: 'blur' }],
      receiverName: [{ required: true, message: '接待人必填', trigger: 'blur' }],
      receiverTel: [{ required: true, message: '电话必填', trigger: 'blur' }],
      scenePhoto: [{ required: true, message: '服务单照片必填', trigger: 'blur' }],
      content: [{  required: true, message: '情况说明必填', trigger: 'blur' }],
    },
    // 新增/编辑
    create: {
        dialogStatus: '',
        temp: {
           customerId: '', 
           customerName: '', 
           groupId: '', 
           groupName: '', 
           vdate: util.getToday(), 
           visiterId: '', 
           visiterName: '', 
           receiverId: '', 
           receiverName: '', 
           receiverTel: '', 
           remark: '', 
           content: '', 
           nextId: '', 
           nextName: '', 
        
           created: util.getToday(), 
           receiverChoose: 'true',
           vPhoto1: -1, vPhoto2: -1, vPhoto3: -1, vPhoto4: -1,vPhoto5: -1,vPhoto6: -1,vPhoto7: -1,vPhoto8: -1,vPhoto9: -1,
           picname1: '', picname2: '', picname3: '', picname4: '', picname5: '', picname6: '', picname7: '', picname8: '', picname9: '',location:""
        },
        
    }
  },

  onLoad: function (options) {
    // 表单初始化
    wx.lin.initValidateForm(this)

    console.log(app.globalData.g_lgName)

    this.setData({
      ['create.temp.visiterId']: app.globalData.g_userId,
      ['create.temp.visiterName']: app.globalData.g_lgName
    })

    // //客户下拉
    // util.getDataByName({ name:'getCustomerSelect',parammaps: {} }, this.getPickerList1)
    // 下一步下拉数据
    util.getDataByName({ name: 'getDictListSelect4', parammaps: { "pid": "55" } }, this.getPickerList3)


    // wx.getSetting({
    //   success: (res) => {
    //     console.log(JSON.stringify(res))
    //     // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
    //     // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
    //     // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
    //     if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
    //       wx.showModal({
    //         title: '请求授权当前位置',
    //         content: '需要获取您的地理位置，请确认授权',
    //         success: function (res) {
    //           if (res.cancel) {
    //             wx.showToast({
    //               title: '拒绝授权',
    //               icon: 'none',
    //               duration: 1000
    //             })
    //           } else if (res.confirm) {
    //             wx.openSetting({
    //               success: function (dataAu) {
    //                 if (dataAu.authSetting["scope.userLocation"] == true) {
    //                   wx.showToast({
    //                     title: '授权成功',
    //                     icon: 'success',
    //                     duration: 1000
    //                   })
    //                   //再次授权，调用wx.getLocation的API
                      
                      
    //                 } else {
    //                   wx.showToast({
    //                     title: '授权失败',
    //                     icon: 'none',
    //                     duration: 1000
    //                   })
    //                 }
    //               }
    //             })
    //           }
    //         }
    //       })
    //     } else if (res.authSetting['scope.userLocation'] == undefined) {
    //       //调用wx.getLocation的API
    //     }
    //     else {
    //       //调用wx.getLocation的API
    //     }
    //   }
    // })


    //获取当前位置的经纬度
    var that=this;
    var BMap = new bmap.BMapWX({ 
      ak: 'cg35EbdsuIizrFdDoMLovCD7rqjRvtN5' 
    }); 
    //微信获取位置
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        var latitude = res.latitude//维度
        var longitude = res.longitude//经度
        var locationParam = res.latitude + ',' + res.longitude
        that.setData({
          latitude: latitude,
          longitude: longitude
        })
        console.log("当前位置的经纬度",res);
        // 向百度地图发起regeocoding检索请求 
        BMap.regeocoding({ 
          location:that.data.latitude + ',' + that.data.longitude,
          fail: function(data) { 
            console.log('fail',data) 
          }, 
          success: function(data) { 
            console.log('成！！！',data )
            that.setData({ 
              location: data.wxMarkerData[0].address,
              ['create.temp.location']: data.wxMarkerData[0].address 
            }); 
          } , 
          iconPath: '../../img/marker_red.png', 
          iconTapPath: '../../img/marker_red.png' 
      });   
      }
    })

  
  
 
    
   


 
  },

 

 
  // getPickerList1:  function (res) {
  //   console.log('客户下拉数据======>', res.data.list)
  //   this.setData({
  //     customerNameList: res.data.list
  //   })
  // },

  getPickerList3:  function (res) {
    console.log('下一步下拉数据======>', res.data.list)
    this.setData({
      nextNameList: res.data.list
    })
  },
  

  getPickerList1:  function (res) {
    console.log('客户下拉数据======>', res.data.list)
    var customerNameList = res.data.list
    this.setData({
      customerShow:true,
      allDisabled:false,
      customerNameList: customerNameList
    })
    if(customerNameList !== null){
      this.setData({c_txt_Show:false})
    } else {
      this.setData({c_txt_Show:true})
    }
  },

  //客户文本框输入
  change_customer_input:function(e){
    var value =e.detail.value
    console.log(value)
    //客户列表框
    util.getDataByName({ name:'getCustomerNameFuzzy',parammaps: {"inputvalue":value} }, this.getPickerList1)
  },

  //客户列表点击
  on_cust_tap: function (e) {
    console.log("客户列表点击")
    var newId = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    var that = this
 
    this.setData({
      customerShow:false,
      allDisabled:true,
      customerId: newId,
      ['create.temp.customerName']: name,
      ['create.temp.customerId']: newId,
    })
    //获取集团
    util.getDataByName({name: 'getgroupNameById',returntype: 'Map',parammaps: { id: newId }
    }, function(e){
      console.log(e)
      var groupId = e.data.list[0].groupId
      var groupName = e.data.list[0].groupName
      that.setData({
        ['create.temp.groupName']: groupName,
        ['create.temp.groupId']: groupId,
        groupName: groupName,
        groupId: groupId
      })
    })
    //获取接待人
    //util.getDataByName({name: 'getContacts',returntype: 'Map',parammaps: { customerId: newId }}, this.getPickerList2)
  },


  // //下拉框：客户
  // change_customer:function(e){
  //    var that = this
  //    console.log('customer的选项', e.detail.value)
  //    var newId = this.data.customerNameList[e.detail.value]['id']
  //     this.setData({
  //       customerIndex: e.detail.value,
  //       customerId: newId,
  //       ['create.temp.customerId']: newId,
  //     })
  //     //获取集团
  //     util.getDataByName({name: 'getgroupNameById',returntype: 'Map',parammaps: { id: newId }
  //     }, function(e){
  //       var groupId = e.data.list[0].groupId
  //       var groupName = e.data.list[0].groupName
  //       that.setData({
  //         ['create.temp.groupName']: groupName,
  //         ['create.temp.groupId']: groupId,
  //         groupName: groupName,
  //         groupId: groupId
  //       })
  //     })
  //     //获取接待人
  //     util.getDataByName({name: 'getContacts',returntype: 'Map',parammaps: { customerId: newId }}, this.getPickerList2)

  // },
  //日期选择触发
  on_vdate_tap:function(e){
    this.setData({
      ['create.temp.vdate']:e.detail.value
    })
  },
   

  //接待人文本框输入
  change_receiver_input:function(e){
    var value =e.detail.value
    var customerId = this.data.customerId
    console.log(value)
    //接待人列表框
    util.getDataByName({ name:'getContactsByNameApp',parammaps: {"customerId":customerId,"contactName":value,} }, this.getPickerList2)
  },

  getPickerList2:  function (res) {
    console.log('接待人下拉数据======>', res.data.list)
    var receiverNameList = res.data.list
    this.setData({
      receiverShow:true,
      allDisabled:false,
      receiverNameList: receiverNameList
    })
    if(receiverNameList !== null){
      this.setData({r_txt_Show:false})
    } else {
      this.setData({r_txt_Show:true})
    }
  },

  //接待人列表点击
  on_rece_tap: function (e) {
    console.log("接待人列表点击")
    var newId = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    var that = this

    this.setData({
      receiverShow:false,
      allDisabled:true,
      ['create.temp.receiverName']: name,
      ['create.temp.receiverId']: newId,
      receiverChoose: 'true' 
    })
    //获取电话
    util.getDataByName({name: 'getTelById',returntype: 'Map',parammaps: { id: newId }
    }, function(e){
      console.log(e)
  
      var telephone = e.data.list[0].telephone
      that.setData({
        ['create.temp.receiverTel']: telephone, 
        telephone: telephone 
      })
    })
  },

  //接待人完成
  confirm_receiver_input:function(e){
    console.log("接收人直接输入")
    this.setData({
      receiverShow:false,
      allDisabled:true,
      receiverChoose: 'false' 
    })
  },



  //下拉框：接待人
  change_receiver:function(e){
    console.log('receiver的选项', e.detail.value)
    var newId = this.data.receiverNameList[e.detail.value]['id']
     this.setData({
       receiverIndex: e.detail.value,
       receiverId: newId,
       ['create.temp.receiverId']: newId,
     })
  },
  //下拉框：下一步计划
  change_next:function(e){
    console.log('next的选项', e.detail.value)
    var newId = this.data.nextNameList[e.detail.value]['id']
     this.setData({
       nextIndex: e.detail.value,
       nextId: newId,
       ['create.temp.nextId']: newId,
     })
  },


   //新增现场照片照片
   change_scenePhoto:function(e){
    console.log("选择现场照片照片",e)

    if(this.data.picIsLoading){
        wx.showToast({title: '照片正在上传中，请稍等！',icon: 'none',duration: 2000})
    } else {
      var that = this
    var list  = e.detail.all
    this.setData({
      scenePhotoUrlList:list
    })
  
    console.log(app.globalData.g_token)
    var tempFile = e.detail.current[0]
    var allFile = e.detail.all

    allFile.forEach(function(item,index){
      that.setData({picIsLoading:true})
       console.log(item)
       console.log(index)
       console.log(index+1)
       var i = index+1
        wx.uploadFile({
          url: app.globalData.g_url +'authdata/uploaderimage', 
          filePath: item,
          name: 'file',
          header: {
            optname: 'insertcustompic',
            id: 1,
            token: app.globalData.g_token
            
          },
          formData: {
            optname: 'insertcustompic',
            id: 1,
            token: app.globalData.g_token
          },
          success (res){
            console.log( "上传图片后返回的",res.data )
            var LastInsertId = JSON.parse(res.data).execresult.LastInsertId
            console.log("scenePhotoUrlList的个数",that.data.scenePhotoUrlList.length)
            console.log("LastInsertId",LastInsertId)
            that.data.create.temp["vPhoto" +i] = LastInsertId
          
            console.log(that.data.create.temp)
            that.setData({picIsLoading:false})
            
          }
        })

    })

    }
    
 

  },
  //删除现场照片照片
  clear_scenePhoto:function(e){
    console.log("删除现场照片",e)
    var that = this
    var list  = e.detail.all
    var index = e.detail.index
    
    this.setData({
      scenePhotoUrlList:list
    })

    console.log("选择现场照片",this.data.create.temp.vPhoto1)
    console.log("选择现场照片",this.data.create.temp.vPhoto2)
    console.log("选择现场照片",this.data.create.temp.vPhoto3)
    var vPhoto1 = this.data.create.temp.vPhoto1
    var vPhoto2 = this.data.create.temp.vPhoto2
    var vPhoto3 = this.data.create.temp.vPhoto3
    var vPhoto4 = this.data.create.temp.vPhoto4
    var vPhoto5 = this.data.create.temp.vPhoto5
    var vPhoto6 = this.data.create.temp.vPhoto6
    var vPhoto7 = this.data.create.temp.vPhoto7
    var vPhoto8 = this.data.create.temp.vPhoto8
    var vPhoto9 = this.data.create.temp.vPhoto9
    if(index == 0){
      this.setData({
        ['create.temp.vPhoto1']: vPhoto2,
        ['create.temp.vPhoto2']: vPhoto3,
        ['create.temp.vPhoto3']: vPhoto4,
        ['create.temp.vPhoto4']: vPhoto5,
        ['create.temp.vPhoto5']: vPhoto6,
        ['create.temp.vPhoto6']: vPhoto7,
        ['create.temp.vPhoto7']: vPhoto8,
        ['create.temp.vPhoto8']: vPhoto9,
        ['create.temp.vPhoto9']: -1,
      })
    }else if(index == 1){
      this.setData({
        ['create.temp.vPhoto2']: vPhoto3,
        ['create.temp.vPhoto3']: vPhoto4,
        ['create.temp.vPhoto4']: vPhoto5,
        ['create.temp.vPhoto5']: vPhoto6,
        ['create.temp.vPhoto6']: vPhoto7,
        ['create.temp.vPhoto7']: vPhoto8,
        ['create.temp.vPhoto8']: vPhoto9,
        ['create.temp.vPhoto9']: -1,
      })
    }else if(index == 2){
      this.setData({
        ['create.temp.vPhoto3']: vPhoto4,
        ['create.temp.vPhoto4']: vPhoto5,
        ['create.temp.vPhoto5']: vPhoto6,
        ['create.temp.vPhoto6']: vPhoto7,
        ['create.temp.vPhoto7']: vPhoto8,
        ['create.temp.vPhoto8']: vPhoto9,
        ['create.temp.vPhoto9']: -1,
      })
    } else if(index == 3){
      this.setData({
        ['create.temp.vPhoto4']: vPhoto5,
        ['create.temp.vPhoto5']: vPhoto6,
        ['create.temp.vPhoto6']: vPhoto7,
        ['create.temp.vPhoto7']: vPhoto8,
        ['create.temp.vPhoto8']: vPhoto9,
        ['create.temp.vPhoto9']: -1,
      })
    } else if(index == 4){
      this.setData({
        ['create.temp.vPhoto5']: vPhoto6,
        ['create.temp.vPhoto6']: vPhoto7,
        ['create.temp.vPhoto7']: vPhoto8,
        ['create.temp.vPhoto8']: vPhoto9,
        ['create.temp.vPhoto9']: -1,
      })
    } else if(index == 5){
      this.setData({
        ['create.temp.vPhoto6']: vPhoto7,
        ['create.temp.vPhoto7']: vPhoto8,
        ['create.temp.vPhoto8']: vPhoto9,
        ['create.temp.vPhoto9']: -1,
      })
    } else if(index == 6){
      this.setData({
        ['create.temp.vPhoto7']: vPhoto8,
        ['create.temp.vPhoto8']: vPhoto9,
        ['create.temp.vPhoto9']: -1,
      })
    } else if(index == 7){
      this.setData({
        ['create.temp.vPhoto8']: vPhoto9,
        ['create.temp.vPhoto9']: -1,
      })
    } else if(index == 8){
      this.setData({
        ['create.temp.vPhoto9']: -1,
      })
    }
  },

  //保存
  submit:function(e){
     
    var detail_value = e.detail.values
    var detail_errors = e.detail.errors
    var detail_errors = e.detail.errors
    console.log("detail_value",detail_value)
    console.log("create.temp",this.data.create.temp)


    const submit_data = Object.assign({}, this.data.create.temp, detail_value)
   
    console.log("保存发送：",submit_data)
 
    submit_data.createrId = app.globalData.g_createrId

    submit_data.receiverChoose = this.data.receiverChoose

    submit_data.location= this.data.location

    
    var send_data = {
      "common": { "returnmap": "0" },
      "data": [
        {
          "name": "insertContactsNewApp", "type": "e",
          "parammaps": {
            "customerId":submit_data.customerId,
            "contactName": submit_data.receiverName,
            "telephone": submit_data.receiverTel,
            "address": "",
            "remark": submit_data.remark,
            "receiverChoose": this.data.receiverChoose
          }
        },
        {
          "name": "insertVisitApp",
          "resultmaps": {
            "list": [submit_data]
          },
          "children": [{
            "name": "insertVisitApp",
            "type": "e",
            "parammaps": {
              "customerId": "@insertVisitApp.customerId",
              "groupId": "@insertVisitApp.groupId",
              "vdate": "@insertVisitApp.vdate",
              "visiterId": "@insertVisitApp.visiterId",
            "receiverName": "@insertVisitApp.receiverName",
              "receiverTel": "@insertVisitApp.receiverTel",
              "remark": "@insertVisitApp.remark",
              "content": "@insertVisitApp.content",
              "nextId": "@insertVisitApp.nextId",
              "createrId": "@insertVisitApp.createrId",
              "vPhoto1": "@insertVisitApp.vPhoto1",
            "vPhoto2": "@insertVisitApp.vPhoto2",
            "vPhoto3": "@insertVisitApp.vPhoto3",
            "vPhoto4": "@insertVisitApp.vPhoto4",
            "vPhoto5": "@insertVisitApp.vPhoto5",
            "vPhoto6": "@insertVisitApp.vPhoto6",
            "vPhoto7": "@insertVisitApp.vPhoto7",
            "vPhoto8": "@insertVisitApp.vPhoto8",
            "vPhoto9": "@insertVisitApp.vPhoto9",
            "location": "@insertVisitApp.location"
    
            }
          }]
        }
      ]
    }

    console.log("send_data",JSON.stringify(send_data))
   
    //验证必填项是否为空
    if(submit_data.customerId == ""){
      wx.showToast({title: '客户名称必填',icon: 'none',duration: 2000})
    } else if(submit_data.vdate == ""){
      wx.showToast({title: '拜访日期必填',icon: 'none',duration: 2000})
    } else if(submit_data.receiverName == ""){
      wx.showToast({title: '接待人必填',icon: 'none',duration: 2000})
    } else if(submit_data.receiverTel == ""){
      wx.showToast({title: '接待人电话必填',icon: 'none',duration: 2000})
    } else if(submit_data.content == ""){
      wx.showToast({title: '情况说明必填',icon: 'none',duration: 2000})
    }  else if(this.data.picIsLoading){
      wx.showToast({title: '照片正在上传中，请稍等！',icon: 'none',duration: 2000})
    }  else {
      if( wx.getStorageSync('isLoading')  == "true"){
        wx.showToast({
          title: '正在保存中，请稍等！',
          icon: 'none',
          duration: 2000
        })
      } else {
        util.execDataByConfig(send_data, this.getListSuccess)
      }
    }

   


    
  },

  getListSuccess:  function (res) {
    console.log('table数据======>', res)
    if (res.msg !== 'fail') {
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000,
        success: function(){
          wx.redirectTo({ url:"../visitRecord/visitRecord"})
        }
      })
    } else {
      console.log(res.data)
      wx.showToast({
        title: '保存失败'+res.data,
        icon: 'error',
        duration: 2000,
      })
    }
  },

 
  
  onReady: function () {

  },

  
  onShow: function () {

  },

 
  onHide: function () {

  },

   
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

 
  onShareAppMessage: function () {

  }
})