var util = require('../../../utils/util.js')
const app = getApp()

Page({
  data: {
    orderId: null,
    customerId: null,
    statusName: '',
    orderDetail: {},
    images: [], // 存储已选图片的临时路径
    records: [],
    serviceList: [], // 服务
    custormList: [], // 客户
    formObj: {
      checkUserName: app.globalData.g_lgName,
      checkUserId: app.globalData.g_userId,
      checkDate: util.getRealToday(),
      contactId: '',
      orderId: null,
      telephone: '',
    },
    receiverShow: false,
    r_txt_Show: false,
    allDisabled: true, //有客户下拉时临时用来控制其他下拉不显示
    receiverChoose: 'true',
  },

  onLoad(options) {
    const id = options.id
    this.setData({
      orderId: id,
      ['formObj.checkUserName']: app.globalData.g_lgName,
      ['formObj.checkUserId']: app.globalData.g_userId,
    })
    console.log(app.globalData.g_lgName, 'app.globalData.g_lgName')
    this.getDetail()
    this.getinstallerList()
    console.log(util.getToday(), 'util.getToday()')
  },

  // 获取服务工单基本信息 和 工单记录进度
  getDetail() {
    var send_data = [
      {
        name: 'getInstallationOrderById',
        returntype: 'Map',
        parammaps: { id: this.data.orderId },
      },
      {
        name: 'getInstallationDailyDetailByOrderId',
        returntype: 'Map',
        parammaps: { orderId: this.data.orderId },
      },
    ]
    util.getDataByNames(send_data, this.handleDetail)
  },

  handleDetail(res) {
    console.log(res, '详情页')
    var data = res.data
    if (data.getInstallationDailyDetailByOrderId.list != null) {
      this.setData({
        records: data.getInstallationDailyDetailByOrderId.list,
        orderDetail: data.getInstallationOrderById.list[0],
        customerId: data.getInstallationOrderById.list[0].customerId,
        statusName: data.getInstallationOrderById.list[0].statusName,
      })
    } else {
      this.setData({
        records: [],
        orderDetail: data.getInstallationOrderById.list[0],
        customerId: data.getInstallationOrderById.list[0].customerId,
        statusName: '',
      })
    }
    this.getCustormList()
  },

  // 服务人员
  getinstallerList() {
    var send_data = [
      {
        name: 'getUsersSelect',
        offset: 0,
        pagecount: 0,
        parammaps: {
          enable: '1',
        },
      },
    ]
    util.getDataByNames(send_data, this.handleInstallerList)
  },
  handleInstallerList(res) {
    if (res.data.getUsersSelect) {
      this.setData({
        serviceList: res.data.getUsersSelect.list,
      })
    }
  },
  // 客户对接
  getCustormList() {
    var send_data = {
      name: 'getContacts',
      returntype: 'Map',
      parammaps: { customerId: this.data.customerId },
    }
    util.getDataByName(send_data, this.handleCustormList)
  },
  handleCustormList(res) {
    console.log(res, 'res')
    if (res.data.list) {
      this.setData({
        custormList: res.data.list,
      })
    }
  },
  onSelectCustorm(event) {
    this.setData({
      ['formObj.contactName']: this.data.custormList[event.detail.value].contactName,
      ['formObj.contactId']: this.data.custormList[event.detail.value].id,
    })
  },

  onDateChange(e) {
    this.setData({
      'formObj.checkDate': e.detail.value,
    })
  },
  onSelectPerson(e) {
    this.setData({
      ['formObj.checkUserName']: this.data.serviceList[e.detail.value].name,
      ['formObj.checkUserId']: this.data.serviceList[e.detail.value].id,
    })
  },
  viewHistory() {
    var id = this.data.orderId
    wx.navigateTo({
      url: `/pages/workbench/historyFill/historyFill?id=${id}`,
    })
  },

  validateForm() {
    const { checkUserName, checkDate, contactName, telephone } = this.data.formObj
    const { images } = this.data
    if (!checkUserName) {
      wx.showToast({ title: '请填写服务人员', icon: 'none' })
      return false
    }
    if (!checkDate) {
      wx.showToast({ title: '请选择验收日期', icon: 'none' })
      return false
    }
    if (images.length === 0) {
      wx.showToast({ title: '请先选择图片', icon: 'none' })
      return
    }
    if (!contactName) {
      wx.showToast({ title: '请输入客户对接人', icon: 'none' })
      return false
    }
    if (!telephone) {
      wx.showToast({ title: '请输入电话号码', icon: 'none' })
      return
    }
    // 手机号格式校验
    const phoneRegex = /^1[3-9]\d{9}$/ // 正则表达式
    if (!phoneRegex.test(telephone)) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return
    }
    return true
  },

  goBack() {
    wx.navigateBack()
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const images = this.data.images.filter((_, i) => i !== index)
    this.setData({ images })
  },

  // 预览图片
  previewImage(e) {
    const index = e.currentTarget.dataset.index
    wx.previewImage({
      current: this.data.images[index].tempFilePath,
      urls: [this.data.images[index].tempFilePath],
    })
  },
  // 选择图片
  chooseImage() {
    const remaining = 3 - this.data.images.length
    wx.chooseMedia({
      count: remaining,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const newImages = res.tempFiles.map((item) => ({
          tempFilePath: item.tempFilePath,
          progress: 0,
          index: this.data.images.length,
          imageType: 'check_image',
        }))
        this.setData({
          images: this.data.images.concat(newImages),
        })
        this.uploadImages(newImages[0])
      },
    })
  },

  // 上传图片到服务器
  uploadImages(image) {
    // 逐个上传
    const index = image.index
    const uploadTasks = wx.uploadFile({
      url: app.globalData.g_url + 'authdata/uploaderimage',
      filePath: image.tempFilePath,
      name: 'file',
      header: {
        optname: 'insertcustompic',
        id: 1,
        token: app.globalData.g_token,
      },
      formData: {
        optname: 'insertcustompic',
        id: 1,
        token: app.globalData.g_token,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          var data = JSON.parse(res.data)
          console.log(this.data.images, '图片上传成功', '111')
          this.data.images[index].imageId = data.execresult.LastInsertId
        } else {
          wx.showToast({ title: '图片上传失败', icon: 'none' })
        }
        console.log(this.data.images, '图片上传成功', '111')
      },
      fail: () => {
        wx.showToast({ title: '图片上传失败', icon: 'none' })
      },
    })

    // 监听上传进度
    uploadTasks.onProgressUpdate((res) => {
      this.setData({
        [`images[${index}].progress`]: res.progress,
      })
    })
  },

  formSubmit(e) {
    console.log(this.data.formObj, 'this.data.formObj')
    if (!this.validateForm()) return
    this.data.formObj.orderId = this.data.orderId
    this.uploadForm()
  },
  // 验收表单上传
  uploadForm() {
    var send_data = {
      common: {
        returnmap: '0',
      },
      data: [
        {
          name: 'insertInstallationOrderImages',
          resultmaps: { list: this.data.images },
          children: [
            {
              name: 'insertInstallationOrderImages',
              type: 'e',
              parammaps: {
                orderId: this.data.orderId,
                imageId: '@insertInstallationOrderImages.imageId',
                imageType: '@insertInstallationOrderImages.imageType',
              },
            },
          ],
        },
        {
          name: 'insertInstallationOrderProcessLog',
          type: 'e',
          parammaps: {
            orderId: this.data.orderId,
            operationType: 'check',
            operationUserId: app.globalData.g_userId,
            operationUserName: app.globalData.g_lgName,
            beforeStatus: this.data.statusName,
            afterStatus: '已完成',
            operationContent: '验收服务工单',
          },
        },
        {
          name: 'checkInstallationOrder',
          type: 'e',
          parammaps: {
            orderId: this.data.formObj.orderId,
            checkUserId: this.data.formObj.checkUserId,
            checkUserName: this.data.formObj.checkUserName,
            contactId:
              this.data.receiverChoose == 'false'
                ? '@insertContacts.LastInsertId'
                : this.data.formObj.contactId,
            checkDate: this.data.formObj.checkDate,
          },
        },
      ],
    }
    // 如果对接人从下拉框中选择,则直接走之前的功能,
    // 如果对接人是新增的 则需要创建一下

    if (this.data.receiverChoose == 'false') {
      send_data.data.unshift({
        name: 'insertContacts',
        type: 'e',
        parammaps: {
          customerId: this.data.customerId, // 客户id
          contactName: this.data.formObj.contactName, // 联系人
          telephone: this.data.formObj.telephone, // 客户电话
        },
      })
    }

    console.log('send_data：', send_data)
    util.execDataByConfig(send_data, this.handleuploadForm)
  },

  handleuploadForm(res) {
    if (res.msg !== 'fail') {
      wx.showToast({
        title: '验收提交成功',
        icon: 'success',
        duration: 3000,
        success: function () {
          setTimeout(function () {
            // wx.navigateBack()
            wx.redirectTo({ url: '../serviceTicket/serviceTicket' })
          }, 1000)
        },
      })
      //  wx.navigateBack();
    } else {
      wx.showToast({
        title: '验收提交失败' + res.data,
        icon: 'error',
        duration: 4000,
      })
    }
  },

  //接待人文本框输入
  change_receiver_input: function (e) {
    var value = e.detail.value
    var customerId = this.data.customerId
    console.log(value)
    //接待人列表框
    util.getDataByName(
      { name: 'getContacts', parammaps: { customerId: customerId } },
      this.getPickerList2,
    )
  },

  getPickerList2: function (res) {
    var custormList = res.data.list
    console.log('接待人下拉数据======>', custormList)
    this.setData({
      receiverShow: true,
      allDisabled: false,
      custormList: custormList,
    })
    if (custormList !== null) {
      this.setData({ r_txt_Show: false })
    } else {
      this.setData({ r_txt_Show: true })
    }
  },
  // 电话填写
  onPhoneChange: function (e) {
    console.log('onPhoneChange', e)
    this.setData({
      ['formObj.telephone']: e.detail.value,
    })
  },
  //接待人完成
  confirm_receiver_input: function (e) {
    console.log('接收人直接输入', e)
    this.setData({
      receiverShow: false,
      allDisabled: true,
      receiverChoose: 'false',
      ['formObj.contactName']: e.detail.value,
    })
  },
  //下拉框：接待人
  change_receiver: function (e) {
    console.log('receiver的选项', e.detail.value)
    var newId = this.data.custormList[e.detail.value]['id']
    this.setData({
      receiverIndex: e.detail.value,
      ['formObj.contactId']: newId,
      ['formObj.contactName']: this.data.custormList[e.detail.value].contactName,
      receiverShow: false,
    })
  },

  //接待人列表点击
  on_rece_tap: function (e) {
    console.log('接待人列表点击')
    var newId = e.currentTarget.dataset.id
    var name = e.currentTarget.dataset.name
    var that = this

    that.setData({
      receiverShow: false,
      allDisabled: true,
      ['formObj.contactName']: name,
      ['formObj.contactId']: 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({
          ['formObj.telephone']: telephone,
        })
      },
    )
  },
})
