createVisit.js 6.98 KB
// packageCustomer/pages/createVisit/createVisit.js
import mapApi from "~/utils/mapapi/mapapi";
import { IMG_URL } from '~/utils/constantData'
import { commonApi } from "~/api/api"
import CustomerApi from "~/api/customerApi/index"
Page({
  data: {
    IMG_URL: IMG_URL,
    navHeight: 0,
    timeVisible: false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime() - 365 * 24 * 60 * 60 * 1000,
    maxDate: new Date().getTime() + 365 * 24 * 60 * 60 * 1000,
    selectedTime: '', // 存储已选择的时间
    tempTime: '',
    contentLength: 0,
    fileList: [],
    locationName: "",
    latitude: null,
    longitude: null,
    infoData: {}
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      this.setData({
        potentialCustomerId: options.id
      })
    }
  },

  onReady() {
    this.resultDialog = this.selectComponent('#resultDialog')
  },

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

  },

  onNavbarReady(e) {
    const { height } = e.detail || {};
    this.setData({ navHeight: height || 0 });
  },

  openTimePicker() {
    let initialDate;
    let initialFormattedTime;
    
    if (this.data.selectedTime) {
      // 如果已有选择的时间,使用已选择的时间
      initialDate = this.dateTimeToTimestamp(this.data.selectedTime);
      initialFormattedTime = this.data.selectedTime;
    } else {
      // 如果没有选择过,使用当前时间
      const now = new Date();
      initialDate = now.getTime();
      initialFormattedTime = this.formatDateTime(now);
    }
    
    this.setData({
      timeVisible: true,
      currentDate: initialDate,
      tempTime: initialFormattedTime
    });
  },

  // 弹窗确认事件
  popupConfirm() {
    this.setData({
      selectedTime: this.data.tempTime, // 保存选择的时间
      timeVisible: false,
      'infoData.visitTimeText': this.data.tempTime
    })
  },

  onChange(e) {
    const values = e.detail.getValues()
    const formattedTime = this.valuesToDateTime(values)
    this.setData({
      tempTime: formattedTime
    })
  },

  cancel() {
    this.setData({
      timeVisible: false
    })
  },

  // 将 yyyy-mm-dd hh:mm 转换为时间戳
  dateTimeToTimestamp(dateTimeStr) {
    if (!dateTimeStr) return new Date().getTime()
    
    const [datePart, timePart] = dateTimeStr.split(' ')
    const [year, month, day] = datePart.split('-')
    const [hour, minute] = timePart.split(':')
    
    return new Date(year, month - 1, day, hour, minute).getTime()
  },

  formatDateTime(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  valuesToDateTime(values) {
    const [year, month, day, hour, minute] = values.map(item => {
      return item.replace(/[年月日时分]/g, '').padStart(2, '0')
    });
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  onContactInput(e) {
    const value = e.detail.value.replace(/\s/g, '')
    this.setData({ 
      'infoData.contactName': value
    })
  },

  onContentInput(e) {
    let val = e.detail.value || ""
    if (val.length > 100) {
      val = val.substring(0, 100)
    }
    this.setData({ 
      'infoData.content': val, 
      contentLength: val.length 
    })
  },

  // 上传图片
  uploadImages() {
    let _this = this
    wx.chooseImage({
      count: 1,
      success(res) {
        console.log(res)
        let [tempFiles] = res.tempFilePaths
        let tempFilesList = tempFiles.split('.')
        let imgType = tempFilesList[tempFilesList.length - 1]
        let type = imgType == 'unknown' ? 'jpg' : imgType
        if (res?.tempFiles?.[0]?.size > 10 * 1024 * 1024) return wx.$api.showToast('图片不能大于10M')
        wx.getFileSystemManager().readFile({
          filePath: tempFiles, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success(_res) {
            wx.$api.showLoading('上传中...')
            commonApi.uploadImg({
              file: `${type}@${_res.data}`
            }).then(img => {
              wx.$api.hideLoading()
              _this.setData({
                'infoData.attachmentList': [img]
              })
            })
          }
        })
      },
      fail(err) {
        console.log(err)
      }
    })
  },

  // 图片预览
  previewImage(e) {
    let { url, index } = e.currentTarget.dataset
    let imageUrl = url?.map(v => { return v})
    wx.previewImage({
      urls: imageUrl,
      current: imageUrl[index]
    })
  },

  // 删除图片
  deleteFile(e) {
    let { index } = e.currentTarget.dataset
    let { infoData } = this.data
    infoData.attachmentList.splice(index, 1)
    this.setData({infoData})
  },

  async getLocation() {
    try {
      const loc = await wx.getLocation()
      const { latitude, longitude } = loc
      wx.$api.showLoading()
      const res = await mapApi.detailedAdrress([latitude, longitude])
      const locationName = res?.formatted_address || res?.address || "已定位"
      wx.$api.hideLoading()
      this.setData({ latitude, longitude, locationName })
    } catch (err) {
      wx.showToast({ title: "定位失败,请检查权限", icon: "none" })
    }
  },

  handleCancel() {
    if (wx.$router && wx.$router.back) {
      wx.$router.back()
    } else {
      wx.navigateBack({})
    }
  },

  handleConfirm() {
    const { infoData, potentialCustomerId, locationName } = this.data
    if (!infoData.visitTimeText || !infoData.contactName || !infoData.content) return wx.$api.showToast("请输入必填信息")
    let params = {
      potentialCustomerId,
      visitTime: infoData.visitTimeText,
      contactPerson: infoData.contactName,
      visitContent: infoData.content,
      visitPhotos: infoData.attachmentList && infoData.attachmentList[0],
      checkInLocation: locationName
    }
    if (this.data.confirmFlag) return
    this.setData({confirmFlag: true})
    wx.$api.showLoading()
    if (!params.potentialCustomerId) {
      wx.$sentry.reportParamError(
        '新增拜访参数异常: potentialCustomerId',
        params
      )
    }
    CustomerApi.addVisit(params).then(res => {
      this.setData({confirmFlag: false})
      wx.$api.hideLoading()
      const okText = '我知道了'
      let { code, message } = res
      if (this.resultDialog) {
        this.setData({
          textareaDisabled: true
        })
        if (code == 0) {
          this.resultDialog.open({
            type: 'success',
            title: '新增拜访记录成功!',
            description: '',
            okText
          })
        } else {
          this.resultDialog.open({
            type: 'fail',
            title: message,
            description: '',
            okText
          })
        }
      }
    })
  },

  // 接口请求结果弹窗确认
  onDialogOk() {
    this.handleCancel()
  },
})