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

Page({
  data: {
    orderId: null,
    selectedDate: {},
    selectedDateArray: [],
    datas: [],
    customerId: null,
    orderDetail: {},
    records: [],
  },

  onLoad(options) {
    const id = options.id
    this.setData({
      orderId: id,
    })
    this.initdatas()
    this.getDetail()
    this.getDailyFillList()
  },

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

  // 初始化日期数组
  initdatas: function () {
    const dates = []
    const today = new Date()
    // 添加今天和前两天的日期
    for (let i = 0; i < 3; i++) {
      const date = new Date(today)
      date.setDate(today.getDate() - i)
      const formatDate = this.formatDate(date)
      dates.push(formatDate)
    }
    this.setData({
      datas: dates,
      selectedDates: { [dates[0]]: true }, // 默认选中今天
      selectedDateArray: [dates[0]],
    })
  },
  // 格式化日期为 YYYY-MM-DD
  formatDate: function (date) {
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  },
  // 日期选择
  selectDate(e) {
    const date = e.currentTarget.dataset.date
    const selectedDates = { ...this.data.selectedDates }
    let selectedDateArray = [...this.data.selectedDateArray]
    // 切换选中状态
    if (selectedDates[date]) {
      // 如果当前只有一个选中的日期,不允许取消
      if (selectedDateArray.length === 1) {
        wx.showToast({
          title: '至少需要选择一个日期',
          icon: 'none',
        })
        return
      }
      delete selectedDates[date]
      selectedDateArray = selectedDateArray.filter((item) => item !== date)
    } else {
      selectedDates[date] = true
      selectedDateArray.push(date)
    }
    this.setData({
      selectedDates: selectedDates,
      selectedDateArray: selectedDateArray,
    })
    console.log(selectedDateArray, 'selectedDates')
    this.getDailyFillList()
  },
  getDailyFillList() {
    var send_data = [
      {
        name: 'getInstallationDailyData',
        returntype: 'Map',
        parammaps: { orderId: this.data.orderId, dates: this.data.selectedDateArray.join(',') },
      },
    ]
    util.getDataByNames(send_data, this.handleDailyFill)
  },
  handleDailyFill(res) {
    if (res.data.getInstallationDailyData.list) {
      res.data.getInstallationDailyData.list.map((item) => {
        item.installDate = ''
        item.todayQuantity = 0
        item.remark = ''
      })
      this.setData({
        records: res.data.getInstallationDailyData.list,
      })
    } else {
      this.setData({
        records: [],
      })
    }
  },
  onRemarkChange(e) {
    var index = e.target.dataset.index
    let records = this.data.records
    records[index].remark = e.detail.value
    this.setData({
      records: records,
    })
    console.log(this.data.records, 'remark')
  },
  onQuantityChange(e) {
    console.log(e, 'ee')
    var index = e.target.dataset.index
    let records = this.data.records
    records[index].todayQuantity = e.detail.value
    this.setData({
      records: records,
    })
    console.log(this.data.records, '数量')
  },

  // 提交每日填写
  posttDailyFill() {
    // 检查每条记录的必填项

    for (let i = 0; i < this.data.records.length; i++) {
      const record = this.data.records[i]
      record.installDate = record.date
      if (record.todayQuantity < 0) {
        wx.showToast({
          title: '请正确填写今日完成量',
          icon: 'none',
        })
        return
      }
      if (record.remark == '' || !record.remark) {
        wx.showToast({
          title: '请填写备注',
          icon: 'none',
        })
        return
      }
    }
    console.log(this.data.records, 'this.data.records')

    var send_data = {
      common: { returnmap: '0' },
      data: [
        {
          name: 'deleteInstallationDailyWriteByDates',
          type: 'e',
          parammaps: {
            datas: this.data.selectedDateArray.join(','),
            userId: app.globalData.g_userId,
            orderId: this.data.orderId,
          },
        },
        {
          name: 'submitInstallationDailyWrite',
          resultmaps: {
            list: this.data.records,
          },
          children: [
            {
              name: 'insertInstallationDailyWrite',
              type: 'e',
              parammaps: {
                orderId: this.data.orderId,
                installUserId: app.globalData.g_userId,
                installUserName: app.globalData.g_lgName,
                goodsName: '@submitInstallationDailyWrite.goodsName',
                installDate: '@submitInstallationDailyWrite.installDate',
                goodsId: '@submitInstallationDailyWrite.goodsId',
                todayQuantity: '@submitInstallationDailyWrite.todayQuantity',
                remark: '@submitInstallationDailyWrite.remark',
                projectId: '@submitInstallationDailyWrite.projectId',
                projectName: '@submitInstallationDailyWrite.projectName',
              },
            },
          ],
        },
        {
          name: 'refreshInstallationOrderDetailQuantity',
          type: 'e',
          parammaps: {
            orderId: this.data.orderId,
          },
        },
        {
          name: 'refreshInstallationOrderProcessByOrderId',
          type: 'e',
          parammaps: {
            orderId: this.data.orderId,
          },
        },
        {
          name: 'insertInstallationOrderProcessLog',
          type: 'e',
          parammaps: {
            orderId: this.data.orderId,
            operationType: 'write',
            operationUserId: app.globalData.g_userId,
            operationUserName: app.globalData.g_lgName,
            beforeStatus: '处理中',
            afterStatus: '处理中',
            operationContent: '',
          },
        },
        {
          name: 'updateDailyDetailYesterdayAndBeforeQuantity',
          type: 'e',
          parammaps: {
            orderId: this.data.orderId,
          },
        },
      ],
    }
    util.execDataByConfig(send_data, this.handleAccept)
  },

  handleAccept: function (res) {
    console.log(res, 'res')
    if (res.msg !== 'fail') {
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 3000,
        success: function () {
          // wx.redirectTo() 会关闭当前页面,返回时不会刷新
          // wx.navigateBack() 返回上一页时会触发onShow生命周期,可以在onShow中刷新数据
          setTimeout(function () {
            // wx.navigateBack()
            wx.redirectTo({ url: '../serviceTicket/serviceTicket' })
          }, 1000)
        },
      })
    } else {
      wx.showToast({
        title: '保存失败' + res.data,
        icon: 'error',
        duration: 2000,
      })
    }
  },
  handleReject() {
    wx.navigateBack()
  },

  goBack() {
    wx.navigateBack()
  },
  viewHistory() {
    var id = this.data.orderId
    wx.navigateTo({
      url: `/pages/workbench/historyFill/historyFill?id=${id}`,
    })
  },

  // 更新今日完成量
  updateTodayQuantity(e) {
    const value = parseInt(e.detail.value) || 0
    const remaining = this.data.totalQuantity - this.data.completedQuantity - value

    this.setData({
      todayQuantity: value,
      remainingQuantity: remaining >= 0 ? remaining : 0,
    })
  },

  // 保存记录
  saveRecord() {
    wx.showLoading({
      title: '保存中...',
    })

    // 这里添加保存逻辑

    setTimeout(() => {
      wx.hideLoading()
      wx.showToast({
        title: '保存成功',
        icon: 'success',
      })
    }, 1500)
  },
})
