// pages/dangerregister/dangerregister.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    curRole: '',
    // 总的安全类别
    secType: [
      {
        name: '安全资料类'
      },
      {
        name: '现场检查类'
      }
    ],
    //
    curSelectSecType: '',
    // 安全检查类别
    secCheckType: [],
    // 安全检查类别替代
    secCheckTypeReplace: [],
    // 当前选择的安全检查类别
    curSelectSecCheckTypeReplace: '',
    // 安全检查内容
    secCheckContent: [],
    // 当前选择的安全检查内容
    curSelectCheckContent: '',
    // 发现问题
    secCheckDiscover: [],
    // 整改建议
    suggestion: '',
    // 检查依据
    basis: '',
    // 企业id
    companyId: app.globalData.currentEnter.companyId,
    // 隐患验收人
    hdAcceptancePerson: "",
    // 隐患描述
    hdDesc: "",
    // 检查日期
    hdInspectDate: '',
    // 检查专家
    hdInspectExpert: '',
    // 隐患级别 1 2
    hdLevel: 1,
    // 隐患名称
    hdName: '',
    // 隐患图片
    hdPic: null,
    // 隐患整改日期
    hdRectificationDate: '',
    // 隐患整改图片
    hdRectificationPic: null,
    // 隐患整改建议
    hdRectificationSug: '',
    // 隐患状态 0 正在整改 1 整改完毕
    hdStatus: 0,
    // 隐患预览图片
    imgsrcurl: '',
    // 整改预览照片
    imgrecturl: '',
    // 隐患图片文件路径
    hdFilePath: '',
    // 整改图片文件路径
    rectFilePath: '',
    // 整改期限
    recDeadLine:'',
    // 整改评价
    recEvaluation:'',
    //录入日期
    entryDate:'xcx',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.companyId = app.globalData.currentEnter.companyId;
    console.log(this.formatDate())
    const hdInspect = this.formatDate()
    this.setData({
      hdInspectDate:hdInspect
    })

  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
    wx.setNavigationBarTitle({
      title: '新增隐患',
    })
    wx.setNavigationBarColor({
      backgroundColor: '#090D9C',
      frontColor: '#ffffff',
    })
    wx.request({
      url: app.globalData.appBaseUrl + '/api/enterpriseSafetyInspectionContent',
      method: 'GET',
      header: {
        Authorization: app.globalData.Authorization
      },
      data: {
        county:app.globalData.appCounty,
        level: 1,
        page: 0,
        size: 9999
      },
      success: res => {
    
        this.setData({
          secCheckType: res.data.content
        })
      }
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },
  formatDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    
  },
  formatDate1() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    
  },
   //安全类别
   chooseSecType(e){

    let that=this;
    that.setData({
    
    // 安全检查类别替代
    secCheckTypeReplace: [],
    // 当前选择的安全检查类别
    curSelectSecCheckTypeReplace: '',
    // 安全检查内容
    secCheckContent: [],
    // 当前选择的安全检查内容
    curSelectCheckContent: '',
    // 发现问题
    secCheckDiscover: [],
     // 隐患名称
     hdName: '',
    })

    wx.request({
      url: app.globalData.appBaseUrl + '/api/enterpriseSafetyInspectionContent',
      method: 'get',
      header: {
        Authorization: app.globalData.Authorization
      },
      data: {
        county:app.globalData.appCounty,
        level: 1,
        type: that.data.secType[e.detail.value].name,
        page: 0,
        size: 99999,
      },
      success: (res) => {
      
        this.setData({
          secCheckTypeReplace: [...res.data.content],
          curSelectSecType: that.data.secType[e.detail.value].name
        })
      }
    })
  },
//安全检查类别
  chooseSecCheckType(event) {
    let that = this;
    that.setData({
    
     
      // 安全检查内容
      secCheckContent: [],
      // 当前选择的安全检查内容
      curSelectCheckContent: '',
      // 发现问题
      secCheckDiscover: [],
       // 隐患名称
       hdName: '',
      })

    wx.request({
      url: app.globalData.appBaseUrl + '/api/enterpriseSafetyInspectionContent',
      method: 'get',
      header: {
        Authorization: app.globalData.Authorization
      },
      data: {
        county:app.globalData.appCounty,
        level: 2,
        page: 0,
        size: 9999,
        pid: that.data.secCheckTypeReplace[event.detail.value].id
      },
      success: (res) => {
      
        this.setData({
          secCheckContent: [...res.data.content],
          curSelectSecCheckTypeReplace: that.data.secCheckTypeReplace[event.detail.value].name
        })
      }
    })
  },
  //安全检查内容
  chooseSecCheckContent(event) {
    let that=this;
    that.setData({
    
     
      // 发现问题
      secCheckDiscover: [],
       // 隐患名称
       hdName: '',
      })
  
    wx.request({
      url: app.globalData.appBaseUrl + '/api/enterpriseSafetyMatter',
      method: 'get',
      header: {
        Authorization: app.globalData.Authorization
      },
      data: {
        inspectionContentId: this.data.secCheckContent[event.detail.value].id,
        page: 0,
        size: 9999
      },
      success: (res) => {

        this.setData({
          secCheckDiscover: res.data.content,
          curSelectCheckContent: this.data.secCheckContent[event.detail.value].name
        })
      }
    })
  },
  chooseSecCheckDiscover(event) {
    this.data.hdName = this.data.secCheckDiscover[event.detail.value].name
    this.setData({
      hdName: this.data.hdName,
      basis: this.data.secCheckDiscover[event.detail.value].basis,
      // suggestion: this.data.secCheckDiscover[event.detail.value].suggestion
    })
  },
  /**
   * 拍照
   */
  takePhoto() {
    // const ctx = wx.createCameraContext()
    // ctx.takePhoto({
    //   quality: 'high',
    //   success: (res) => {
    //     this.setData({
    //       imgsrc: res.tempImagePath
    //     })
    //   }
    // })
    wx.chooseImage({
      success: (res) => {
        this.data.hdFilePath = res.tempFilePaths[0]
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0], // 选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res1 => { // 成功的回调
            // console.log('data:image/png;base64, ' + res1.data)
            // this.imgsrc = 'data:image/png;base64,' + res1.data
            this.setData({
              imgsrcurl: 'data:image/png;base64,' + res1.data
            })
          }
        })
        // wx.uploadFile()
      }
    })
  },
  takePhoto2() {
    wx.chooseImage({
      success: (res) => {
        this.data.rectFilePath = res.tempFilePaths[0]
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0], // 选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res1 => { // 成功的回调
            // console.log('data:image/png;base64, ' + res1.data)
            // this.imgsrc = 'data:image/png;base64,' + res1.data
            this.setData({
              imgrecturl: 'data:image/png;base64,' + res1.data
            })
          }
        })
        // wx.uploadFile()
      }
    })
  },
  // 选择检查日期
  selectCheckDate(event) {
    this.setData({
      hdInspectDate: event.detail.value
    })
  },
  // 输入检查专家
  inputHdInspectExpert(event) {
    this.data.hdInspectExpert = event.detail.value
  },
  //输入隐患描述
  inputHdComment(event) {
    console.log(event,'event.....')
    if(event.detail.value!=''||event.detail.value!=null){
      this.data.comment = event.detail.value
    }
   
  },
  // 输入隐患名称
  inputHdName(event) {
    this.data.hdName = event.detail.value
  },
  // 输入隐患类型
  inputHDType(event) {
    console.log(event, 'hdTypeInput')
    this.data.hdLevel = event.detail.value
  },

  // 输入检查依据
  inpoutBasis(event) {
    this.data.basis = event.detail.value
  },

  // 输入整改建议
  inputRectSug(event) {
    // this.data.hdRectificationSug = event.detail.value
    this.data.suggestion = event.detail.value
  },
  // 输入整改评价
  inputEvaluation(event) {
    this.data.recEvaluation = event.detail.value
  },
   // 输入整改期限
   inputRectification(event) {
    this.setData({
      recDeadLine: event.detail.value
    })
  },
  // 输入整改日期
  inputRectDate(event) {
    this.setData({
      hdRectificationDate: event.detail.value
    })
  },
  // 输入验收人
  inputHdAcceptancePerson(event) {
    this.data.hdAcceptancePerson = event.detail.value
  },
  // 隐患状态
  inputHDStatus(event) {
    if((this.data.imgrecturl=== "" || this.data.imgrecturl=== null||this.data.imgrecturl === 'null'||this.data.imgrecturl === undefined)&&event.detail.value==1){
      wx.showToast({
        title: '没有整改照片',
        icon: 'error',
        duration: 1000
      })
      this.data.hdStatus = event.detail.value
      return
    }else{
      this.data.hdStatus = event.detail.value 
    }
  },
  // 提交隐患
  submitDanger() {
    
    const entryDate = this.formatDate1()
    this.setData({
      entryDate:entryDate
    })
    console.log(this.data,'this.data')
    if (this.data.comment===""||this.data.comment===undefined||this.data.comment===null||this.data.comment.trim().length === 0||/^\r*$/.test(this.data.comment)) {
      wx.showToast({
        title: '未填写隐患描述',
        icon: 'none',
        duration: 2000
      });
      return;
    }
  
    if (this.data.suggestion===""||this.data.suggestion===undefined||this.data.suggestion===null||this.data.suggestion.trim().length === 0||/^\r*$/.test(this.data.suggestion)) {
      wx.showToast({
        title: '未填写整改建议',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if((this.data.imgrecturl=== "" || this.data.imgrecturl=== null||this.data.imgrecturl === null||this.data.imgrecturl === undefined)&&this.data.hdStatus==1){
      wx.showToast({
        title: '没有整改照片',
        icon: 'error',
        duration: 2000
      })
      return
    }
    console.log(this.data.curRole)
    if (this.data.hdFilePath) {
      let county = app.globalData.appCounty
      wx.showLoading({
        title: '上传中',
      })
      let formData = {}
      
      formData = {...this.data}
      formData.county =  county;
      delete formData.hdPic
      delete formData.hdRectificationPic
      delete formData.imgsrcurl
      delete formData.imgrecturl
      delete formData.hdFilePath
      delete formData.rectFilePath
      if(this.data.comment==''||this.data.comment==null){
        delete formData.comment
      }
      if (formData.hdInspectDate) {
        formData.hdInspectDate 
      } else {
        delete formData.hdInspectDate
      }
      if (formData.hdRectificationDate) {
        formData.hdRectificationDate 
        // formData.hdRectificationDate += ' 00:00:00'
      } else {
        delete formData.hdRectificationDate
      }
      
      console.log(formData,'formData')
      wx.uploadFile({
        filePath: this.data.hdFilePath,
        name: 'hdPic',
        url: app.globalData.appBaseUrl + '/api/thHiddenDanger',
        formData: formData,
        header: {
          Authorization: app.globalData.Authorization
        },
        success: (res) => {
          console.log(res, '文件上传')
          wx.hideLoading()
          if (res.statusCode === 201) {
            wx.showToast({
              title: '上传成功',
              icon: 'success'
            })
            wx.navigateBack()
            
            // const hdId = JSON.parse(res.data).hdId
            // 进行 整改图片编辑
            // if (this.data.rectFilePath) {
            //   wx.uploadFile({
            //     filePath: this.data.rectFilePath,
            //     name: 'hdRectificationPic',
            //     url: app.globalData.appBaseUrl + '/api/thHiddenDanger',
            //     formData: {
            //       hdId: hdId,
            //       companyId: this.data.companyId
            //     },
            //     success: (res) => {
            //       console.log(res, '文件整改')
            //     }
            //   })
            // }
          } else if (res.statusCode === 401) {
            wx.redirectTo({
              url: '/pages/login/login',
            })
          }
        },
        fail: () => {
          wx.hideLoading()
          
        }
      })
    } else {
      let that=this
      let county = app.globalData.appCounty
      wx.showLoading({
        title: '上传中'
      })
      let formData = {}
      formData = {...this.data}
      formData.county =  county;
      delete formData.hdPic
      delete formData.hdRectificationPic
      delete formData.imgsrcurl
      delete formData.imgrecturl
      delete formData.hdFilePath
      delete formData.rectFilePath
      if (formData.hdInspectDate) {
        formData.hdInspectDate
      } else {
        delete formData.hdInspectDate
      }
      if(that.data.comment==''||that.data.comment==null||!that.data.comment){
        delete formData.comment
      }
      if (formData.hdRectificationDate) {
        formData.hdRectificationDate
        // formData.hdRectificationDate += ' 00:00:00'
      } else {
        delete formData.hdRectificationDate
      }
     
      wx.request({
        url: app.globalData.appBaseUrl + '/api/thHiddenDanger',
        method: 'POST',
        header: {
          'content-type': 'multipart/form-data; boundary=XXX',
          Authorization: app.globalData.Authorization
        },
        data: this.formatFormData(formData),
        success: (res) => {
          if (res.statusCode === 201) {
            wx.showToast({
              title: '上传成功',
              mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
              icon: 'success',
              duration:2000,//显示时长
              success:function(){
                wx.navigateBack({
                  delta: 1
                })
               }
            })

          
          
        }else{
          wx.showToast({
            title: '上传失败',
            icon: 'loading'
          })
        }
        },
        fail: () => {},
        complete: () => {
          wx.hideLoading()
         
        }
      })
    }
    // wx.hideLoading()
  },
  // 格式化 multipart/formdata
  formatFormData(formdata) {
    let dataString = '\r\n--XXX'
    for (const key in formdata) {
      dataString += `\r\nContent-Disposition: form-data; name="${key}"\r\n\r\n${formdata[key]}\r\n--XXX`
    }
    return dataString
  },
 
})