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

Page({
  data: {
    currentTab: '1',
    noData: '../../../images/noData.png',
    dataListTips: '暂无数据',
    serviceStaffname: '',
    showModal: false, // 控制弹窗显示
    form: {
      estimatedCompleteTime: '', // 存储选择的日期
      acceptName: wx.getStorageSync('username'),
      acceptTime: util.getRealToday(),
    },
    //表格请求参数~~
    table1: {
      name: 'getInstallationOrderList',
      page: 1,
      offset: 1,
      pagecount: 9999,
      returntype: 'Map',
      parammaps: {
        statusName: '待处理',
        roleId: app.globalData.g_roleId,
        userId: app.globalData.g_userId,
      },
    },
    table2: {
      name: 'getInstallationOrderList',
      page: 1,
      offset: 1,
      pagecount: 9999,
      returntype: 'Map',
      parammaps: {
        serviceStaffIds: '',
        customerName: '',
        statusName: '已完成',
        roleId: app.globalData.g_roleId,
        userId: app.globalData.g_userId,
        completeStartTime: util.get15daysAgo(),
        completeEndTime: util.getRealToday(),
      },
    },
    itemObj: {},
    installerList: [],
    pendingList: [],
    processedList: [],
  },

  onLoad: function () {
    this.getList()
    this.getinstallerList()
  },
  onShow: function () {
    // 根据当前选中的tab刷新对应的列表
    if (this.data.currentTab === '1') {
      this.getList()
    } else {
      this.getList2()
    }
  },

  // 服务人员
  getinstallerList() {
    var send_data = [
      {
        name: 'getUsersSelect',
        offset: 0,
        pagecount: 0,
        parammaps: {
          enable: '1',
        },
      },
    ]

    util.getDataByNames(send_data, this.handleInstallerList)
  },
  handleInstallerList(res) {
    console.log(res, '服务人员')
    const obj = res.data
    if (obj.getUsersSelect) {
      this.setData({
        installerList: obj.getUsersSelect.list,
      })
    }
  },
  //加载表格
  getList() {
    this.setData({
      ['table1.parammaps.roleId']: app.globalData.g_roleId,
      ['table1.parammaps.userId']: app.globalData.g_userId,
    })
    util.getDataByName(this.data.table1, this.getListSuccess1)
  },
  getList2() {
    this.setData({
      ['table2.parammaps.roleId']: app.globalData.g_roleId,
      ['table2.parammaps.userId']: app.globalData.g_userId,
    })
    util.getDataByName(this.data.table2, this.getListSuccess2)
  },
  getListSuccess1: function (res) {
    const obj = res.data
    if (obj.list != null) {
      this.setData({
        pendingList: res.data.list,
        ['table1.parammaps.offset']: res.data.pageNum,
        ['table1.total']: res.data.total,
      })
    } else {
      this.setData({
        pendingList: [],
        ['table1.parammaps.offset']: 1,
      })
    }
  },
  getListSuccess2: function (res) {
    const obj = res.data
    if (obj.list != null) {
      this.setData({
        processedList: res.data.list,
        ['table2.parammaps.offset']: res.data.pageNum,
        ['table2.total']: res.data.total,
      })
    } else {
      this.setData({
        processedList: [],
        ['table2.parammaps.offset']: 1,
      })
    }
  },

  //日期1
  bindDateChange1: function (e) {
    this.setData({
      ['table2.parammaps.completeStartTime']: e.detail.value,
    })
  },
  //日期2
  bindDateChange2: function (e) {
    this.setData({
      ['table2.parammaps.completeEndTime']: e.detail.value,
    })
  },
  onInstallerChange: function (e) {
    console.log(e, 'eee')
    this.setData({
      serviceStaffname: this.data.installerList[e.detail.value].name,
      ['table2.parammaps.serviceStaffIds']: this.data.installerList[e.detail.value].id,
    })
  },

  onInputChangeClear: function (e) {
    console.log(e, 'eee')
    this.setData({
      serviceStaffname: '',
      ['table2.parammaps.serviceStaffIds']: '',
    })
  },
  onInputChange: function (e) {
    console.log(e, 'eee')
    this.setData({
      ['table2.parammaps.customerName']: e.detail.value,
    })
  },
  changeTab(e) {
    this.setData({
      currentTab: e.detail.activeKey,
      serviceStaffname: '',
      ['table2.parammaps.serviceStaffIds']: '',
    })
    // 可以在这里根据tab加载不同的数据
    if (this.data.currentTab == '1') {
      this.getList()
    } else {
      this.getList2()
    }
  },

  // 隐藏弹窗
  hideDatePicker() {
    this.setData({
      showModal: false,
    })
    wx.showToast({
      title: '已取消接单',
      icon: 'none',
      duration: 5000,
    })
  },
  // 处理日期选择
  handleDateChange(e) {
    const estimatedCompleteTime = e.detail.value // 获取选择的日期
    this.setData({
      ['form.estimatedCompleteTime']: estimatedCompleteTime,
    })
    console.log('选择的日期:', estimatedCompleteTime)
  },

  handleAccept(e) {
    var obj = e.target.dataset.id
    this.setData({
      showModal: true,
      ['form.id']: obj.id,
      ['form.statusName']: obj.statusName,
    })
  },
  handleAcceptConfirm() {
    if (!this.data.form.estimatedCompleteTime) {
      wx.showToast({
        title: '预计时间必填',
        icon: 'none',
        duration: 5000,
      })
      return
    }

    var send_data = {
      common: { returnmap: '0' },
      data: [
        {
          name: 'acceptInstallationOrder',
          type: 'e',
          parammaps: {
            orderId: this.data.form.id,
            acceptName: wx.getStorageSync('username'),
            acceptId: wx.getStorageSync('g_userId'),
            acceptTime: this.data.form.acceptTime,
            estimatedCompleteTime: this.data.form.estimatedCompleteTime,
          },
        },
        {
          name: 'insertInstallationOrderProcessLog',
          type: 'e',
          parammaps: {
            orderId: this.data.form.id,
            operationType: 'accept',
            operationUserId: wx.getStorageSync('g_userId'),
            operationUserName: wx.getStorageSync('username'),
            beforeStatus: this.data.form.statusName,
            afterStatus: '处理中',
            operationContent: '接单处理',
          },
        },
      ],
    }
    util.execDataByConfig(send_data, this.handleAcceptList)
  },
  handleAcceptList(res) {
    console.log(res, '99999')
    if (res.code == 200) {
      wx.showToast({
        title: '已成功接单',
        icon: 'success',
        duration: 5000,
      })
      this.setData({
        showModal: false,
      })
      this.getList()
    }
  },

  handleReject(e) {
    var obj = e.target.dataset.id
    wx.showModal({
      title: '驳回原因',
      editable: true,
      placeholderText: '请输入驳回原因',
      success: (res) => {
        if (res.confirm) {
          const rejectReason = res.content
          if (!rejectReason) {
            wx.showToast({
              title: '请输入驳回原因',
              icon: 'none',
              duration: 5000,
            })
            return
          }
          // 处理驳回逻辑
          var send_data = {
            common: { returnmap: '0' },
            data: [
              {
                name: 'rejectInstallationOrder',
                type: 'e',
                parammaps: {
                  orderId: obj.id,
                  rejectReason: rejectReason,
                  rejectId: wx.getStorageSync('g_userId'),
                },
              },

              {
                name: 'insertInstallationOrderProcessLog',
                type: 'e',
                parammaps: {
                  orderId: obj.id,
                  operationType: 'reject',
                  operationUserId: wx.getStorageSync('g_userId'),
                  operationUserName: wx.getStorageSync('username'),
                  beforeStatus: obj.statusName,
                  afterStatus: '接单驳回',
                  operationContent: `驳回原因:${rejectReason}`,
                },
              },
            ],
          }
          util.execDataByConfig(send_data, this.handleRejectList)
        } else if (res.cancel) {
          console.log('用户取消驳回')
          wx.showToast({
            title: '已取消驳回',
            icon: 'none',
            duration: 5000,
          })
        }
      },
    })
  },
  handleRejectList(res) {
    console.log(res, '已驳回')
    if (res.code == 200) {
      wx.showToast({
        title: '已驳回',
        icon: 'success',
        duration: 5000,
      })
      this.getList()
    }
  },
  handleSuccess(e) {
    var obj = e.target.dataset.id
    wx.showModal({
      title: '提示',
      content: '是否确认完成?',
      success: (res) => {
        if (res.confirm) {
          // 处理驳回逻辑
          var send_data = {
            common: { returnmap: '0' },
            data: [
              {
                name: 'completeInstallationOrder',
                type: 'e',
                parammaps: {
                  orderId: obj.id,
                },
              },
              {
                name: 'insertInstallationOrderProcessLog',
                type: 'e',
                parammaps: {
                  orderId: obj.id,
                  operationType: 'complete',
                  operationUserId: wx.getStorageSync('g_userId'),
                  operationUserName: wx.getStorageSync('username'),
                  beforeStatus: obj.statusName,
                  afterStatus: '已完成未验收',
                  operationContent: '完成服务工单',
                },
              },
            ],
          }
          util.execDataByConfig(send_data, this.handleSuccessList)
          // 这里可以添加驳回的具体逻辑
        } else if (res.cancel) {
          wx.showToast({
            title: '已取消完成',
            icon: 'none',
            duration: 5000,
          })
        }
      },
    })
  },
  handleSuccessList(res) {
    if (res.code == 200) {
      wx.showToast({
        title: '已完成',
        icon: 'success',
        duration: 3000,
      })
      this.getList()
    }
  },
  handleReport1(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/workbench/dailyFill/dailyFill?id=${id}`,
    })
  },
  handleReport2(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/workbench/acceptFill/acceptFill?id=${id}`, // 正确跳转到验收填写页面并传入id参数
    })
  },
  handleDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/workbench/serviceOrderDetail/serviceOrderDetail?id=${id}`,
    })
  },
})
