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

  data: {
    allDisabled:true,//有客户下拉时临时用来控制其他下拉不显示
    c_txt_Show:false,
    customerShow:false,
    customerNameList: [
      // {id: 11, name: "海文牧场"}, {id: 22, name: "成宏牧场"}, {id: 32, name: "瑞福牧业"}
    ],
    customerIndex:'',
    customerId:'',
    
    serviceTypeNameList: [
      { "name": "安装", "id": "安装" }, 
      { "name": "更换", "id": "更换" }, 
      { "name": "维修", "id": "维修" }, 
      { "name": "培训", "id": "培训" }, 
    ],
    servicetypeIndex:'',
    servicetypeId:'',

    visitNameList: [
      //  {id: 1215, name: "拜访单号：BF210220001 拜访人：管理员 拜访日期：2021-03-20"}
    ],
    visitIndex:'',
    visitId:'',
    telvisitNameList: [
      // {id: 456, name: "回访单号： 回访人：多秋阳 回访日期：2019-11-18"}
    ],
    telvisitIndex:'',
    telvisitId:'',

   
    receiverNameList: [
        // {id: 56, name: "Epans"},{id: 58, name: "Derek"}
    ],
    receiverIndex:'',
    receiverId:'',

    groupId: '', 
    groupName: '',

    receiverShow:false,
    r_txt_Show:false,
    receiverChoose:'false',
    telephone:"",
    location: '', 
    picIsLoading:false,
 
    rules: {
      customerName: [{ required: true, message: '客户必填', trigger: 'blur' }],
      serviceDate: [{ required: true, message: '开始服务时间必填', trigger: 'blur' }],
      employeeName: [{ required: true, message: '服务人员必填', trigger: 'blur' }],
      serviceTypeName: [{ required: true, message: '服务类型必填', trigger: 'blur' }],
      receiverName: [{ required: true, message: '接待人必填', trigger: 'blur' }],
      receiverTel: [{ required: true, message: '接待人电话必填', trigger: 'blur' }],
      describe: [{ required: true, message: '服务描述必填', trigger: 'blur' }],
      scenePhoto: [{ required: true, message: '服务单照片必填', trigger: 'blur' }],
      serviceCodePhoto0: [{ required: true, message: '现场照片必填', trigger: 'blur' }],
      location: [{ required: true, message: '必填', trigger: 'blur' }]
    
    },
    // 新增/编辑
    create: {
        dialogStatus: '',
  
        temp: {
           customerId: '', customerName: '', groupId: '',groupName: '', serviceCode: '',  serviceBeginDate: util.getToday(), employeeId: '', servicetypeId: '', employeeName: '', serviceTypeName: '',visiterId: '', visiterName: '', receiverId: '', receiverName: '',receiverTel: '', remark: '', content: '', nextId: '',  nextName: '', describe: '', serviceResult: '',telvisitId: '', stockupIds: '',telvisitName: '', stockupName: '',
           created: util.getToday(), 
           receiverChoose: 'true' ,location: '', 
           scenePhoto1: -1, scenePhoto2: -1, scenePhoto3: -1, scenePhoto4: -1,scenePhoto5: -1,scenePhoto6: -1,scenePhoto7: -1,scenePhoto8: -1,scenePhoto9: -1,serviceCodePhoto: -1,
           picname1: '', picname2: '', picname3: '', picname4: '', picname5: '', picname6: '', picname7: '', picname8: '', picname9: '',codePicname: ''
        },
    },
    scenePhotoUrlList:[],
    serviceCodePhotoUrlList:[]
    
  },

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

    console.log(app.globalData.g_lgName)

    this.setData({
      ['create.temp.employeeId']: app.globalData.g_createrId,
      ['create.temp.employeeName']: app.globalData.g_lgName
    })

    //客户下拉
    //util.getDataByName({ name:'getCustomerSelect',parammaps: {} }, this.getPickerList1)
  
  
    //获取当前位置的经纬度
    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)
    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})
    }
  },
 
   
  getPickerList4:  function (res) {
    console.log('拜访记录======>', res.data.list)
    this.setData({
      visitNameList: res.data.list
    })
  },
  getPickerList5:  function (res) {
    console.log('回访记录 =====>', res.data.list)
    this.setData({
      telvisitNameList: res.data.list
    })
  },
 
  //客户文本框输入
  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){
      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: 'getVisitByCustomerId',returntype: 'Map',parammaps: { customerId: newId }}, this.getPickerList4)
     //获取回访
     util.getDataByName({name: 'getTelvisitByCustomerId',returntype: 'Map',parammaps: { customerId: newId }}, this.getPickerList5)
      
  },
  
  //日期选择触发
  on_serviceDate_tap:function(e){
    this.setData({
      ['create.temp.serviceBeginDate']:e.detail.value
    })
  },
   
 
  //下拉框：服务类型
  change_servicetype:function(e){
    console.log('change_servicetype的选项', e.detail.value)
    var newId = this.data.serviceTypeNameList[e.detail.value]['id']
     this.setData({
       servicetypeIndex: e.detail.value,
       servicetypeId: newId,
       ['create.temp.servicetypeId']: newId,
     })
  },
  //下拉框：拜访记录关联
  change_visit:function(e){
    console.log('change_visit的选项', e.detail.value)
    var newId = this.data.visitNameList[e.detail.value]['id']
     this.setData({
       visitIndex: e.detail.value,
       visitId: newId,
       ['create.temp.visitId']: newId,
     })
  },
  //下拉框：回访记录关联
  change_telvisit:function(e){
    console.log('change_telvisit的选项', e.detail.value)
    var newId = this.data.telvisitNameList[e.detail.value]['id']
     this.setData({
       telvisitIndex: e.detail.value,
       telvisitId: newId,
       ['create.temp.telvisitId']: 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["scenePhoto" +i] = LastInsertId
            
              console.log(that.data.create.temp)
  
              that.setData({picIsLoading:false})
              
            }
          })
  
      })
    }


    // wx.uploadFile({
    //   url: app.globalData.g_url +'authdata/uploaderimage', 
    //   filePath: tempFile,
    //   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)
    //     if(that.data.scenePhotoUrlList.length == 1){
    //       that.setData({
    //         ['create.temp.scenePhoto1']: LastInsertId
    //       })
    //     } else if(that.data.scenePhotoUrlList.length == 2){
    //       that.setData({
    //         ['create.temp.scenePhoto2']: LastInsertId
    //       })
    //     } else if(that.data.scenePhotoUrlList.length == 3){
    //       that.setData({
    //         ['create.temp.scenePhoto3']: LastInsertId
    //       })
    //     } else if(that.data.scenePhotoUrlList.length == 4){
    //       that.setData({
    //         ['create.temp.scenePhoto4']: LastInsertId
    //       })
    //     } else if(that.data.scenePhotoUrlList.length == 5){
    //       that.setData({
    //         ['create.temp.scenePhoto5']: LastInsertId
    //       })
    //     } else if(that.data.scenePhotoUrlList.length == 6){
    //       that.setData({
    //         ['create.temp.scenePhoto6']: LastInsertId
    //       })
    //     } else if(that.data.scenePhotoUrlList.length == 7){
    //       that.setData({
    //         ['create.temp.scenePhoto7']: LastInsertId
    //       })
    //     } else if(that.data.scenePhotoUrlList.length == 8){
    //       that.setData({
    //         ['create.temp.scenePhoto8']: LastInsertId
    //       })
    //     } else if(that.data.scenePhotoUrlList.length == 9){
    //       that.setData({
    //         ['create.temp.scenePhoto9']: LastInsertId
    //       })
    //     } 

    //     console.log(that.data.create.temp)
        
    //   }
    // })

  },
  //删除现场照片照片
  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.scenePhoto1)
    console.log("选择现场照片",this.data.create.temp.scenePhoto2)
    console.log("选择现场照片",this.data.create.temp.scenePhoto3)
    var scenePhoto1 = this.data.create.temp.scenePhoto1
    var scenePhoto2 = this.data.create.temp.scenePhoto2
    var scenePhoto3 = this.data.create.temp.scenePhoto3
    var scenePhoto4 = this.data.create.temp.scenePhoto4
    var scenePhoto5 = this.data.create.temp.scenePhoto5
    var scenePhoto6 = this.data.create.temp.scenePhoto6
    var scenePhoto7 = this.data.create.temp.scenePhoto7
    var scenePhoto8 = this.data.create.temp.scenePhoto8
    var scenePhoto9 = this.data.create.temp.scenePhoto9
    if(index == 0){
      this.setData({
        ['create.temp.scenePhoto1']: scenePhoto2,
        ['create.temp.scenePhoto2']: scenePhoto3,
        ['create.temp.scenePhoto3']: scenePhoto4,
        ['create.temp.scenePhoto4']: scenePhoto5,
        ['create.temp.scenePhoto5']: scenePhoto6,
        ['create.temp.scenePhoto6']: scenePhoto7,
        ['create.temp.scenePhoto7']: scenePhoto8,
        ['create.temp.scenePhoto8']: scenePhoto9,
        ['create.temp.scenePhoto9']: -1,
      })
    }else if(index == 1){
      this.setData({
        ['create.temp.scenePhoto2']: scenePhoto3,
        ['create.temp.scenePhoto3']: scenePhoto4,
        ['create.temp.scenePhoto4']: scenePhoto5,
        ['create.temp.scenePhoto5']: scenePhoto6,
        ['create.temp.scenePhoto6']: scenePhoto7,
        ['create.temp.scenePhoto7']: scenePhoto8,
        ['create.temp.scenePhoto8']: scenePhoto9,
        ['create.temp.scenePhoto9']: -1,
      })
    }else if(index == 2){
      this.setData({
        ['create.temp.scenePhoto3']: scenePhoto4,
        ['create.temp.scenePhoto4']: scenePhoto5,
        ['create.temp.scenePhoto5']: scenePhoto6,
        ['create.temp.scenePhoto6']: scenePhoto7,
        ['create.temp.scenePhoto7']: scenePhoto8,
        ['create.temp.scenePhoto8']: scenePhoto9,
        ['create.temp.scenePhoto9']: -1,
      })
    } else if(index == 3){
      this.setData({
        ['create.temp.scenePhoto4']: scenePhoto5,
        ['create.temp.scenePhoto5']: scenePhoto6,
        ['create.temp.scenePhoto6']: scenePhoto7,
        ['create.temp.scenePhoto7']: scenePhoto8,
        ['create.temp.scenePhoto8']: scenePhoto9,
        ['create.temp.scenePhoto9']: -1,
      })
    } else if(index == 4){
      this.setData({
        ['create.temp.scenePhoto5']: scenePhoto6,
        ['create.temp.scenePhoto6']: scenePhoto7,
        ['create.temp.scenePhoto7']: scenePhoto8,
        ['create.temp.scenePhoto8']: scenePhoto9,
        ['create.temp.scenePhoto9']: -1,
      })
    } else if(index == 5){
      this.setData({
        ['create.temp.scenePhoto6']: scenePhoto7,
        ['create.temp.scenePhoto7']: scenePhoto8,
        ['create.temp.scenePhoto8']: scenePhoto9,
        ['create.temp.scenePhoto9']: -1,
      })
    } else if(index == 6){
      this.setData({
        ['create.temp.scenePhoto7']: scenePhoto8,
        ['create.temp.scenePhoto8']: scenePhoto9,
        ['create.temp.scenePhoto9']: -1,
      })
    } else if(index == 7){
      this.setData({
        ['create.temp.scenePhoto8']: scenePhoto9,
        ['create.temp.scenePhoto9']: -1,
      })
    } else if(index == 8){
      this.setData({
        ['create.temp.scenePhoto9']: -1,
      })
    }
  },
  //新增服务单
  change_serviceCodePhoto:function(e){
    console.log("选择服务单",e)
    var that = this
    var list  = e.detail.all
    this.setData({
      serviceCodePhotoUrlList:list
    })
 
    var tempFile = e.detail.current[0]

    wx.uploadFile({
      url: app.globalData.g_url +'authdata/uploaderimage',  
      filePath: tempFile,
      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("LastInsertId",LastInsertId)
 
          that.setData({
            ['create.temp.serviceCodePhoto']: LastInsertId
          })

          console.log(that.data.create.temp.serviceCodePhoto)
         
        
      }
    })

  },
  //删除服务单
  clear_serviceCodePhoto:function(e){
    console.log("删除服务单",e)
    var that = this
    var list  = e.detail.all
    var index = e.detail.index
    
    this.setData({
      serviceCodePhotoUrlList:list
    })

    this.setData({
      ['create.temp.serviceCodePhoto']:  -1
    })
    
  },


  //接待人文本框输入
  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' 
    })
  },



  //保存
  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)


    var  submit_data = Object.assign({}, this.data.create.temp, detail_value)
    submit_data.location= this.data.location
    console.log("保存发送：",submit_data)
    
   

    var customerId = submit_data.customerId
 
  
    submit_data.createrId = app.globalData.g_createrId
    
    submit_data.employeeId = app.globalData.g_createrId

    var send_data = {
      "name":"insertService",
      "parammaps":submit_data
    } 
    console.log("send_data",JSON.stringify(send_data))
    
    //验证必填项是否为空
    if(submit_data.customerId == ""){
      wx.showToast({title: '客户名称必填',icon: 'none',duration: 2000})
    } else if(submit_data.serviceBeginDate == ""){
      wx.showToast({title: '服务日期必填',icon: 'none',duration: 2000})
    } else if(submit_data.servicetypeId == ""){
      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.describe == ""){
      wx.showToast({title: '服务描述必填',icon: 'none',duration: 2000})
    } else if(submit_data.serviceCodePhoto == -1){
      wx.showToast({title: '服务单照片必填',icon: 'none',duration: 2000})
    } else if(submit_data.scenePhoto1 == -1){
      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.postDataByName(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:"../siteService/siteService"})
        }
      })
    } else {
      wx.showToast({
        title: '保存失败'+res.data,
        icon: 'error',
        duration: 2000,
      })
    }
  },

 
  
  onReady: function () {

  },

  
  onShow: function () {

  },

 
  onHide: function () {

  },

   
  onUnload: function () {

  },

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

  },

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

  },

 
  onShareAppMessage: function () {

  }
})