Newer
Older
smart_construction / miniprogram / pages / addDevice / addDevice.js
zhout on 11 Aug 2020 17 KB 第一次发布提交
// miniprogram/pages/addDevice/addDevice.js
// import  WxValidate from '../../utils/WxValidate.js'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canvasHeight: '',
    canvasWidth: '',
    longitude: '',
    latitude: '',
    photopath1: '',
    photopath2: '',
    photopath3: '',
    option1: [{
        text: '雨水井',
        value: "1"
      },
      {
        text: '污水井',
        value: "2"
      },
      {
        text: '燃气井',
        value: "3"
      },
      {
        text: '热力井',
        value: "4"
      },
      {
        text: '电力井',
        value: "5"
      },
    ],
    personoption1: [],
    projectoption: [],
    show: false,
    form: {
      devcode: "",
      wellcode: "",
      welltype: "",
      welldepth: "",
      installheigt: "",
      installperson: "",
      installtimeFmt: "",
      photopath: "",
      factory: "",
      workmsg: "",
      position: "",
      description: "",
      longitude: "",
      latitude: "",
      longitude84: "",
      latitude84: "",
      devicetype: "",
      project: "",
      area: "",
      street: "",
      wellname: ""
    },
    fileList: []
  },

  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 that = this;
    //初始化表单内容为上次填写值
    var cacheForms = wx.getStorageSync('cacheList')

    if (cacheForms) {
      that.setData({
        form: cacheForms,
        devcode: cacheForms.devcode,

      })
    }
    var form = that.data.form
    //默认安装经纬度为当前位置(gcj02)
    wx.getLocation({
      type: "gcj02",
      altitude: true,
      success: function (res) {
        var longitude = 'form.longitude';
        var latitude = 'form.latitude';
        that.setData({
          [longitude]: parseFloat(res.longitude).toFixed(6),
          [latitude]: parseFloat(res.latitude).toFixed(6),
          longitude: parseFloat(res.longitude).toFixed(6),
          latitude: parseFloat(res.latitude).toFixed(6),
        });
        //获取当前坐标(wgs84),特别注意需要放在加载里面,否则获取有误
        wx.getLocation({
          type: "wgs84",
          altitude: true,
          success: function (res) {
            var longitude84 = 'form.longitude84';
            var latitude84 = 'form.latitude84';
            that.setData({
              [latitude84]: parseFloat(res.latitude).toFixed(6),
              [longitude84]: parseFloat(res.longitude).toFixed(6)
            })
          }
        })
      }
    })

    //获取人员下拉列表
    wx.cloud.callFunction({
      name: 'getPerson',
      data: {
        url: app.globalData.url + "deviceType/getUser"
      },
    }).then(res => {
      if (res.result.code == 200) {
        var users = res.result.data
        var personArr = [];
        for (var i = 0; i < users.length; i++) {
          var person = {
            text: users[i].name,
            value: users[i].name
          };
          personArr.push(person);
        }
        that.setData({
          personoption1: personArr
        })
      }
    }).catch(err => {
      console.error(err);
    })


    wx.cloud.callFunction({
      name: 'getProject',
      data: {
        url: app.globalData.url + "project/getProject"
      },
    }).then(res => {
      if (res.result.code == 200) {
        var projectList = res.result.data
        var projectArr = [];
        for (var i = 0; i < projectList.length; i++) {
          var project = {
            text: projectList[i].projectName,
            value: projectList[i].projectName
          };
          projectArr.push(project);
        }
        that.setData({
          projectoption: projectArr
        })
      }
    }).catch(err => {
      console.error(err);
    })
    var installtime = 'form.installtimeFmt';
    var dateNow = this.formatDate();
    this.setData({
      show: false,
      installtimeFmt: dateNow,
      [installtime]: dateNow,
    });
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  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;
    }

  },


  //文本换行 参数:1、canvas对象,2、文本 3、距离左侧的距离 4、距离顶部的距离 5、6、文本的宽度
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight = initHeight + leftWidth * 2; //22为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        // titleHeight += 40;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // // 标题border-bottom 线距顶部距离
    // titleHeight = titleHeight + 10;
    // return titleHeight
  },

  formValidate() {

    if (this.data.form.devcode == "") {
      wx.showToast({
        icon: 'none',
        title: '设备编号不能为空!',
      })
      return false
    }
    if (this.data.form.devcode == "") {
      wx.showToast({
        icon: 'none',
        title: '设备编号不能为空!',
      })
      return false
    }
    if (this.data.form.area == "") {
      wx.showToast({
        icon: 'none',
        title: '区不能为空!',
      })
      return false
    }
    if (this.data.form.street == "") {
      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.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) {
      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
      }
    }

    if (this.data.form.project == "") {
      wx.showToast({
        icon: 'none',
        title: '所属项目不能为空!',
      })
      return false
    }

    if (this.data.form.installtimeFmt == null) {
      wx.showToast({
        icon: 'none',
        title: '安装时间不能为空!',
      })
      return false
    }
    return true;
  },
  formSubmit: function (event) {
    if (!this.formValidate()) {
      return false;
    }
    var that = this;
    var fileList = that.data.fileList;
    for (var i = 0; i < fileList.length; i++) {
      var photopath = 'photopath' + [Number(i) + 1]
      this.setData({
        [photopath]: fileList[i].url.split("static/")[1]
      })
    }
    wx.cloud.callFunction({
      name: 'addDevice',
      data: {
        device: that.data.form,
        photopath1: that.data.photopath1,
        photopath2: that.data.photopath2,
        photopath3: that.data.photopath3,
        url: app.globalData.url + "appDeviceAdd/add"
      },
    }).then(res => {
      if (res.result.code == 500) {
        wx.showToast({
          title: '设备编号已安装!',
        })
      } else if (res.result.code == 200) {
        wx.showModal({
          content: '提交成功,是否返回?',
          success: function (res) {
            //用于回显
            wx.setStorageSync('cacheList', that.data.form)
            //提交成功后提示用户操作
            if (res.confirm) {
              wx.switchTab({
                url: '../earth/earth'
              })
            } else { //这里是点击了取消以后 
              console.log('用户点击取消')
            }
          }
        })
      }
    }).catch(err => {
      console.error(err);
      wx.showToast({
        title: "提交失败",
      })
    })
  },
  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) {
        var devcode = res.result
        var formdevcode = 'form.devcode'
        _this.setData({
          [formdevcode]: devcode
        });
        wx.cloud.callFunction({
          name: 'findModeCode',
          data: {
            devcode: devcode,
            url: app.globalData.url + "appDeviceAdd/findModeCodeByCode"
          },
        }).then(res => {
          if (res.result) {
            var formDevicetype = 'form.devicetype'
            _this.setData({
              [formDevicetype]: res.result
            });
          }
        })
      }
    })
  },
  paste() {
    var _this = this;
    wx.getClipboardData({
      success: function (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),
        });
      }
    })
  },
  selectValue(value) {

    var that = this;
    var wellType = 'form.welltype';
    that.setData({
      [wellType]: 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
    })
  },
  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
              });
            }
          }
        })
      }
    })
    // 压缩图片
    // wx.compressImage({
    //   src: event.detail.file.path,
    //   quality: 25,
    //   success: function (res) {
    //     convertpath = res.tempFilePath;
    //     //获取图片尺寸
    //     wx.getImageInfo({
    //       src: convertpath,
    //       success(res) {
    //         _this.setData({
    //           canvasHeight: res.height,
    //           canvasWidth: res.width
    //         })
    //         var ctx = wx.createCanvasContext('firstCanvas')

    //         //将图片src放到cancas内,宽高为图片大小
    //         ctx.drawImage(convertpath, 0, 0, res.width, res.height)
    //         //将声明的时间放入canvas
    //         ctx.setFontSize(30 * (res.width / 750)) //注意:设置文字大小必须放在填充文字之前,否则不生效
    //         ctx.setFillStyle('blue')
    //         var text = "编号:" + _this.data.form.devcode + "\n经度:" + _this.data.form.longitude + "\n纬度:" + _this.data.form.latitude
    //         //  _this.drawText(ctx,text,20, 70, 5, res.width)
    //         _this.drawText(ctx, text, 15 * (res.width / 750), 70 * (res.width / 750), 5, res.width)

    //         // ctx.fillText(text, 0, 40)
    //         // ctx.strokeText(_this.data.form.devcode, 0, 30)
    //         //生成水印图
    //         ctx.draw(false, function () {
    //           wx.canvasToTempFilePath({
    //             canvasId: 'firstCanvas',
    //             success: (res) => {
    //               wx.compressImage({
    //                 src: res.tempFilePath,
    //                 quality: 25,
    //                 success: function (res) {
    //                   //上传照片至服务器
    //                   wx.uploadFile({
    //                     url: app.globalData.httpsUrl + "appDeviceAdd/fileUpload",
    //                     filePath: res.tempFilePath,
    //                     name: 'file',
    //                     // formData: {
    //                     //   'devcode': '642019010001'
    //                     // },
    //                     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 image_index = event.detail.index
    var fileList_new = this.data.fileList;
    fileList_new.splice(image_index, 1);
    this.setData({
      fileList: fileList_new
    })
  },
})