// miniprogram/pages/addDevice/addDevice.js
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    projectName: '', // 项目名称
    pageName: '',
    showMask: false,
    today: new Date().getTime(),
    longitude: '',
    latitude: '',
    option1: [],
    personoption1: [],
    projectoption: [],
    devcode: "",
    deviceMode: "",
    installtimeFmt: '',
    show: false,
    devcodeDisabled: false, // 控制设备编号不可编辑
    installTypeList:[
        {
            text: '初次安装',
            value: '1',
        },
        {
            text: '初次拆走',
            value: '2',
        },
        {
            text: '二次安装',
            value: '3',
        },
        {
            text: '二次拆走',
            value: '4',
        },
        {
            text: '正在维护',
            value: '5',
        },
        {
            text: '其他',
            value: '6',
        },
    ],
    form: {
      devcode: "",
      wellcode: "",
      welltype: "",
      welldepth: "",
      installheigt: "",
      installperson: "",
      installtimeFmt: "",
      photopath: "",
      factory: "",
      workmsg: "",
      position: "",
      description: "",
      longitude: "",
      latitude: "",
      longitude84: "",
      latitude84: "",
      devicetype: "",
      project: "",
      area: "",
      street: "",
      wellname: "",
      photopath1: '',
      photopath2: '',
      photopath3: '',
      installType: '', // 设备安装情况
    },
    fileList: [],
    detail: "",
    markers: [{
        id: 100,
        // iconPath: "../../images/point.png",
        latitude:  '',
        longitude:  '',
        // label:'1',
        width: 25,
        height: 35
      }],
  },

  onDisplay() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  formatDate() {
    var date = new Date();
    // return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    var seperator1 = "-";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    month = month > 9 ? month : "0" + month;
    strDate = strDate > 9 ? strDate : "0" + strDate;
    hour = hour > 9 ? hour : "0" + hour;
    minute = minute > 9 ? minute : "0" + minute;
    second = second > 9 ? second : "0" + second;
    var currentdate =
      date.getFullYear() +
      seperator1 +
      month +
      seperator1 +
      strDate +
      " " +
      hour + ":" +
      minute + ":" +
      second;
    return currentdate;

  },
  onConfirm(event) {
    var installtime = 'form.installtimeFmt';
    this.setData({
      show: false,
      installtimeFmt: this.formatDate(event.detail),
      [installtime]: this.formatDate(event.detail),
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    console.log(wx.getStorageSync('resultObject').longitude, 'ppppp');
    _this.setData({
        'form.project': app.globalData.selectProjectName || wx.getStorageSync('resultObject').project,
        'projectName': app.globalData.selectProjectName || wx.getStorageSync('resultObject').project,
        'markers[0].latitude': Number(wx.getStorageSync('resultObject').latitude) ,
        'markers[0].longitude': Number(wx.getStorageSync('resultObject').longitude),
        // 'markers[0].label':'10',
        'markers[0].width': 18,
        'markers[0].id':1,
        'markers[0].height': 30,
        latitude:Number(wx.getStorageSync('resultObject').latitude),
        longitude:Number(wx.getStorageSync('resultObject').longitude)
    })
    //获取人员下拉列表
    // wx.request({
    //   method: "POST",
    //   url: app.globalData.httpsUrl + "deviceType/getUser",
    //   data:{
    //     tips:'repair'
    //   },
    //   header: {
    //     'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
    //   },
    //   success(res) {
    //     if (res.data.code == 200) {
    //       var users = res.data.data
    //       var personArr = [];
    //       for (var i = 0; i < users.length; i++) {
    //         var person = {
    //           text: users[i].name,
    //           value: users[i].name
    //         };
    //         personArr.push(person);
    //       }
    //       _this.setData({
    //         personoption1: personArr
    //       })
    //     }
    //   }
    // })
    //获取项目下拉列表

    wx.request({
      method: "POST",
      url: app.globalData.httpsUrl + "project/getProject",
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success(res) {
        if (res.data.code == 200) {
          var projectList = res.data.data
          var projectArr = [];
          for (var i = 0; i < projectList.length; i++) {
            var project = {
              text: projectList[i].projectName,
              value: projectList[i].projectName
            };
            projectArr.push(project);
          }
          _this.setData({
            projectoption: projectArr
          })
        }
      }
    })

    //获取井类型下拉列表
wx.request({
  method: "POST",
  url: app.globalData.httpsUrl + "appDeviceAdd/getWellTypeList",   
  header: {
    'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
  },
  success(res){
    if (res.data) {
      var welltype = res.data
      var welltypeArr = [];
      for (var i = 0; i < welltype.length; i++) {
        var type = {
          text: welltype[i].text,
          value: welltype[i].value
        };
        welltypeArr.push(type);
      }
      _this.setData({
        option1: welltypeArr
      })
    }
  }
})

   //跳转时带入参数返回哪页
    if (options.pageName) {
      this.setData({
        pageName: options.pageName
      })
    }
  //跳转时带入参数设备的安装信息
    if (wx.getStorageSync('resultObject')) {
      var formObject =  wx.getStorageSync('resultObject')
      _this.setData({
        form: formObject,
        detail: formObject
      })

      _this.setData({
        ['form.installperson']:  app.globalData.userName,
        ['form.installtimeFmt']: "",
        ['form.workmsg']: "",
        // ['form.description']: ""
      })

      const {
        fileList = []
      } = _this.data;
      if (formObject.photopath1 != "") {
        var file1 = {
          url: app.globalData.httpsUrl + "static/" + formObject.photopath1
        }
        fileList.push(file1)
      }
      if (formObject.photopath2 != "") {
        var file2 = {
          url: app.globalData.httpsUrl + "static/" + formObject.photopath2
        }
        fileList.push(file2)
      }
      if (formObject.photopath3 != "") {
        var file3 = {
          url: app.globalData.httpsUrl + "static/" + formObject.photopath3
        }
        fileList.push(file3)
      }
      if (formObject.photopath4 != "") {
        var file4 = {
          url: app.globalData.httpsUrl + "static/" + formObject.photopath4
        }
        fileList.push(file4)
      }
      if (formObject.photopath5 != "") {
        var file5 = {
          url: app.globalData.httpsUrl + "static/" + formObject.photopath5
        }
        fileList.push(file5)
      }
      if (formObject.photopath6 != "") {
        var file6 = {
          url: app.globalData.httpsUrl + "static/" + formObject.photopath6
        }
        fileList.push(file6)
      }
      _this.setData({
        fileList
      });
    }
    var installtime = 'form.installtimeFmt';
    var dateNow = this.formatDate();
    this.setData({
      installtimeFmt: dateNow,
      [installtime]: dateNow,
    });
  },

  // 数据监听节点
  observers:{
    'form.devcode': function(newValue, oldValue){ //监听
        if(newValue.length) {
            this.setData({ // 通过监听器，自动计算sum的值
              devcodeDisabled: true
            })
        }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.removeStorageSync('resultObject')
    // this.setData({
    //     'form.project': app.globalData.selectProjectId,
    //     'projectName': app.globalData.selectProjectName,
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },


  /**
   * 校验只要是数字（包含正负整数，0以及正负浮点数）就返回true
   **/

  isNumber: function (val) {
    var regPos = /^[0-9]*$/; //非负浮点数
    var regNeg = /^(-?\d+)(\.\d+)?$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
      return false;
    } else {
      return true;
    }
  },
//   cleaable 清除经度
  clearLongitude() {
    var _this = this;
    _this.setData({
      'form.longitude': '',
    });
  },
//   清除纬度
  clearclearLatitude() {
    var _this = this;
    _this.setData({
      'form.latitude': '',
    });
  },


  formValidate() {

    if (this.data.form.devcode == "") {
      wx.showToast({
        icon: 'none',
        title: '设备编号不能为空！',
      })
      return false
    }
    if (this.data.form.wellcode == "") {
      wx.showToast({
        icon: 'none',
        title: '井编号不能为空！',
      })
      return false
    }
    if (this.data.form.devicetype == "") {
      wx.showToast({
        icon: 'none',
        title: '设备类型不能为空！',
      })
      return false
    }
    if (this.data.form.installType == "") {
        wx.showToast({
          icon: 'none',
          title: '设备安装情况不能为空！',
        })
        return false
      }
    console.log('---------', this.data.form.longitude);
    if (this.data.form.longitude == "" || this.data.form.latitude == "") {
      wx.showToast({
        icon: 'none',
        title: '经纬度不能为空！',
      })
      return false
    }

    if (this.data.form.position == "") {
      wx.showToast({
        icon: 'none',
        title: '位置描述不能为空！',
      })
      return false
    }
    if (this.data.form.installperson == null ||
      this.data.form.installperson == '') {
      wx.showToast({
        icon: 'none',
        title: '运维人员不能为空！',
      })
      return false
    }
    if (this.data.form.project == "") {
      wx.showToast({
        icon: 'none',
        title: '所属项目不能为空！',
      })
      return false
    }


    if (this.data.form.welldepth != null) {
      if (this.isNumber(this.data.form.welldepth)) {
        wx.showToast({
          icon: 'none',
          title: '井深必须为数值！',
        })
        return false
      }
    }
    if (this.data.form.installheigt != null) {
      if (this.isNumber(this.data.form.installheigt)) {
        wx.showToast({
          icon: 'none',
          title: '到井口距离必须为数值！',
        })
        return false
      }
    }

    return true;
  },

  //获取与上次修改的信息
  changeMsg: function () {
    var formNew = this.data.form;
    var formOld =  this.data.detail || JSON.parse(this.data.detail);
    var descpNew = "";
    if (formNew.devcode != formOld.devcode) {
      descpNew += "修改设备编号,原值:" + formOld.devcode + ",新值:" + formNew.devcode + ";"
    }
    if (formNew.devicetype != formOld.devicetype) {
      descpNew += "修改设备类型,原值:" + formOld.devicetype + ",新值:" + formNew.devicetype + ";"
    }
    if (formNew.area != formOld.area) {
      descpNew += "修改区,原值:" + formOld.area + ",新值:" + formNew.area + ";"
    }
    if (formNew.street != formOld.street) {
      descpNew += "修改街道,原值:" + formOld.street + ",新值:" + formNew.street + ";"
    }
    if (formNew.wellname != formOld.wellname) {
      descpNew += "修改井名称,原值:" + formOld.wellname + ",新值:" + formNew.wellname + ";"
    }
    if (formNew.factory != formOld.factory) {
      descpNew += "修改权属单位,原值:" + formOld.factory + ",新值:" + formNew.factory + ";"
    }
    if (formNew.installheigt != formOld.installheigt) {
      descpNew += "修改井口距离,原值:" + formOld.installheigt + ",新值:" + formNew.installheigt + ";"
    }
    if (formNew.installperson != formOld.installperson) {
      descpNew += "修改运维人员,原值:" + formOld.installperson + ",新值:" + formNew.installperson + ";"
    }
    if (formNew.latitude != formOld.latitude) {
      descpNew += "修改纬度,原值:" + formOld.latitude + ",新值:" + formNew.latitude + ";"
    }
    if (formNew.longitude != formOld.longitude) {
      descpNew += "修改经度,原值:" + formOld.longitude + ",新值:" + formNew.longitude + ";"
    }
    if (formNew.position != formOld.position) {
      descpNew += "修改位置描述,原值:" + formOld.position + ",新值:" + formNew.position + ";"
    }
    if (formNew.wellcode != formOld.wellcode) {
      descpNew += "修改井编号,原值:" + formOld.wellcode + ",新值:" + formNew.wellcode + ";"
    }
    if (formNew.welldepth != formOld.welldepth) {
      descpNew += "修改井深,原值:" + formOld.welldepth + ",新值:" + formNew.welldepth + ";"
    }
    if (formNew.welltype != formOld.welltype) {
      descpNew += "修改井类型,原值:" + formOld.welltype + ",新值:" + formNew.welltype + ";"
    }
    if (formNew.project != formOld.project) {
      descpNew += "修改所属项目,原值:" + formOld.project + ",新值:" + formNew.project + ";"
    }
    if (this.data.form.photopath1 != formOld.photopath1 ||
      this.data.form.photopath2 != formOld.photopath2 ||
      this.data.form.photopath3 != formOld.photopath3) {
      descpNew += "修改照片;"
    }
    if ("" != formNew.description) {
      descpNew += formNew.description;
    }
    this.setData({
      ['form.description']: descpNew
    })
  },

  //提交表单
  formSubmit: function (event) {
    //表单验证
    if (!this.formValidate()) {
      return false;
    }
    //自动生成修改内容
    this.changeMsg();
    //提交权限限制（只有施工人员能修改）
    // if(app.globalData.role!='repair'){
    //   wx.showToast({
    //     icon: 'none',
    //     title: '无权限修改',
    //     duration:2000
    //   })
    //   return false
    // }
    var that = this;
    var fileList = that.data.fileList;
    console.log('要保存的图片列表', fileList);
    that.setData({
        'form.photopath1' : '',
        'form.photopath2' : '',
        'form.photopath3' : '',
        'form.photopath4' : '',
        'form.photopath5' : '',
        'form.photopath6' : '',
    })
    for (var i = 0; i < fileList.length; i++) {
      var photopath = 'form.photopath' + [Number(i) + 1]
      this.setData({
        [photopath]: fileList[i].url.split("static/")[1]
      })
    }
    delete that.data.form.installtime 
    delete that.data.form.createtime 
    wx.request({
      method: "POST",
      url: app.globalData.httpsUrl + "appDeviceLog/add",
      data: that.data.form,
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success(res) {
        if (res.data.code == 200) {
          wx.showModal({
            content: '提交成功，是否返回？',
            success: function (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: that.data.pageName
                })
              } else { //这里是点击了取消以后 
                console.log('用户点击取消')
              }
            }
          })
        }
      },
      fail(err) {
        wx.showToast({
          title: "提交失败",
        })
      }
    })
  },
  //报存录入的input信息
  confirm(event) {
    var that = this;
    var formValue = event.detail.value;
    var formName = event.target.dataset.id;
    var fromN = 'form.' + [formName];
    that.setData({
      [fromN]: formValue
    })
  },

  //扫码
  scan() {
   var _this = this
    wx.scanCode({
      success(res) {
        console.log(res)
        _this.setData({
            ['form.devcode']: res.result
          })
      }
    })
  },
  showAddress :function(longitude, latitude, self) {
    // 实例化腾讯地图API核心类  
    qqmapsdk = new QQMapWX({
      key: 'BGPBZ-C5O3P-ROUDR-LWC4J-63EKH-V5FRX'//此处使用你自己申请的key  
    })
    // 腾讯地图调用接口  
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        self.setData({
          'form.area':res.result.address.slice(0,res.result.address.indexOf('区')+1),
          'form.street':res.result.address.slice(res.result.address.indexOf('区')+1)
        })
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
      }
    });
  },
  //粘贴经纬度
  paste() {
    console.log('paste');

    var _this = this;
    wx.getClipboardData({
      success: function (res) {
        console.log('剪切板内容', res);
        var longitude = 'form.longitude';
        var latitude = 'form.latitude';
        var longitude84 = 'form.longitude84';
        var latitude84 = 'form.latitude84';
        _this.setData({
          [longitude]: parseFloat(res.data.split(",", 4)[1]).toFixed(6),
          [latitude]: parseFloat(res.data.split(",", 4)[0]).toFixed(6),
          [longitude84]: "" == (res.data.split(",", 4)[3]) ? "" : parseFloat(res.data.split(",", 4)[3]).toFixed(6),
          [latitude84]: "" == (res.data.split(",", 4)[2]) ? "" : parseFloat(res.data.split(",", 4)[2]).toFixed(6),
          longitude: parseFloat(res.data.split(",", 4)[1]).toFixed(6),
          latitude: parseFloat(res.data.split(",", 4)[0]).toFixed(6),
        });
      }
    })
    _this.showAddress(_this.data.form.longitude,_this.data.form.latitude,_this)
  },
  selectValue(value) {
    var that = this;
    var wellType = 'form.welltype';
    that.setData({
      [wellType]: value.detail
    })
  },
    //   设置设备安装情况
    selectInstallType(value) {
        var that = this;
        var installType = 'form.installType';
        that.setData({
          [installType]: value.detail
        })
      },
    
  //运维人员默认为登录人
  // selectpersonValue(event) {
  //   var that = this;
  //   var installPerson = 'form.installperson';
  //   that.setData({
  //     [installPerson]: event.detail
  //   })
  // },
  selectprojectValue(event) {
    var that = this;
    var project = 'form.project';
    that.setData({
      [project]: event.detail,
      showMask: true
    })
  },
 
  open() {
    this.setData({
      showMask: true
    })
  },
   //隐藏textarea，防止遮挡
  close() {
    this.setData({
      showMask: false
    })
  },
  //上传照片
  afterRead(event) {
    var _this = this;
    const {
      file
    } = event.detail;
    const {
      fileList = []
    } = _this.data;
    var convertpath = "";
    wx.compressImage({
      src: event.detail.file.path,
      quality: 25,
      success: function (res) {
        convertpath = res.tempFilePath;
        wx.uploadFile({
          url: app.globalData.httpsUrl + "appDeviceAdd/fileUploadMarker",
          filePath: convertpath,
          name: 'file',
          formData: {
            'text': "编号:" + _this.data.form.devcode + "经度:" + _this.data.form.longitude + "纬度:" + _this.data.form.latitude
          },
          header: {
            "Content-Type": "multipart/form-data",
            'accept': 'application/json',
          },
          success(res) {
            if (res.data) {
              var url = JSON.parse(res.data);
              fileList.push({
                ...file,
                url: app.globalData.httpsUrl + "static/" + url.data.replace(/\\/g, "/")
              });
              _this.setData({
                fileList
              });
            }
          }
        })
      }
    })
  },
  //删除照片
  deletePhoto(event) {
    var that = this
    var image_index = event.detail.index
    var fileList_new = that.data.fileList;
    wx.showModal({
      content: '确定删除照片？',
      success: function (res) {
        if (res.confirm) {
          fileList_new.splice(image_index, 1);
          console.log('新的照片列表', fileList_new);
          that.setData({
            fileList: fileList_new
          })
          console.log('新的照片列表111', that.data.fileList);

          wx.request({
            method: "POST",
            url: app.globalData.httpsUrl + "appDeviceLog/deletePhoto",
            data: {
              devcode: that.data.form.devcode
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            },
            success(res) {
                that.setData({
                    [`form.photopath${image_index + 1}`] : ''
                })
            }
          })
        } else { //这里是点击了取消以后 
          console.log('用户点击取消')
        }
      }
    })
  }
})