<template>
  <view class="page-wraper">
    <view class="page-header">
      <view class="page-header-box">
        <view class="header_job_top">
          <job-top :dataContent="jobContent"></job-top>
        </view>
        <view class="header_item"> 申请单号：{{ jobContent.requestNumber }} </view>
        <!-- <view class="split_line"></view> -->
      </view>
    </view>

    <view class="page-main">
      <scroll-view scroll-y="true" class="page-main-scroll">
        <view class="detail-list" v-for="(item, index) in detailSource" :key="item.id">
          <view class="">
            <com-detail-card :dataContent="item" :settingParam="jobContent" @remove="updateData" @updateData="updateData" @openDetail="openDetail"> </com-detail-card>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="page-footer">
      <view class="padding_20" style="background-color: ghostwhite; width: 100%">
        <button class="btn_single_commit" style="width: 100%" hover-class="btn_commit_after" @click="commit">提交</button>
      </view>
    </view>

    <win-scan-button @goScan="openScanPopup"></win-scan-button>
    <win-scan-pack-and-location ref="scanPopup" title="制品标签" @getResult="getScanResult"></win-scan-pack-and-location>
    <recycleDetailInfoPopup ref="jobDetailPopup"></recycleDetailInfoPopup>
    <com-message ref="comMessageRef" />
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, nextTick } from 'vue'
import { onLoad, onShow, onNavigationBarButtonTap, onReady, onBackPress, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { getProductRecycleDetail, productRecycleJobsubmit, cancleTakeProductRecycleJob, takeProductRecycleJob } from '@/api/request2.js'

import { goHome, getCurrDateTime, getPackingNumberAndBatch, navigateBack } from '@/common/basic.js'
import { getInventoryStatusName } from '@/common/directory.js'

import { getDataSource, createRecordInfo, calcHandleQty, getScanCount } from '@/common/detail.js'

import { getManagementPrecisions } from '@/common/balance.js'

import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import winScanPackAndLocation from '@/mycomponents/scan/winScanPackAndLocation.vue'
import comDetailCard from '@/mycomponents/detail/comDetailCard.vue'
import recycleDetailInfoPopup from '@/pages/productRecycle/coms/recycleDetailInfoPopup.vue'
import jobTop from '@/mycomponents/job/jobTop.vue'
import { useCountStore } from '@/store'
// 获取自定义的store
const store = useCountStore()
const { proxy } = getCurrentInstance()
const id = ref('')
const scanCount = ref(0)
const jobContent = ref({}) // 任务内容
const subList = ref([]) // 接口返回的任务subList
const detailSource = ref([]) // 绑定在页面上的数据源
const businessTypeInfo = ref({})
const managementList = ref([])
const toLocationCode = ref()
const jobStatus = ref('')
const scanPopup = ref()
const comMessageRef = ref()
const jobDetailPopup = ref()
onLoad((option) => {
  uni.setNavigationBarTitle({
    title: `${option.title}详情`
  })
  id.value = option.id
  if (id.value != undefined) {
    // 新建的任务自动接收
    if (option.status == '1') {
      receive((callback) => {
        getDetail()
      })
    } else {
      getDetail()
    }
  }
})
// 返回首页
onNavigationBarButtonTap((e) => {
  if (e.index === 0) {
    goHome()
  }
})
// 拦截返回按钮事件
onBackPress((e) => {
  // 已经接收但是没提交任务
  if (e.from == 'backbutton') {
    if (jobStatus.value == '2') {
      // 取消承接任务
      cancleTakeProductRecycleJob(id.value)
        .then((res) => {
          uni.navigateBack()
        })
        .catch((error) => {
          uni.navigateBack()
        })
    } else {
      uni.navigateBack()
    }
    return true
  }
})
onPullDownRefresh(() => {
  getDetail()
  uni.stopPullDownRefresh()
})
// 接收
const receive = (callback) => {
  proxy.$modal.loading('加载中....')
  if (id.value != null) {
    takeProductRecycleJob(id.value)
      .then((res) => {
        uni.hideLoading()
        callback()
      })
      .catch((error) => {
        uni.hideLoading()
        showErrorMessage(error)
      })
  }
}
const getDetail = () => {
  proxy.$modal.loading('加载中...')
  getProductRecycleDetail(id.value)
    .then((res) => {
      uni.hideLoading()
      if (res.data == null) {
        showMessage('未获取到详情')
      } else if (res.data.subList.length > 0) {
        jobContent.value = res.data
        jobStatus.value = res.data.status
        subList.value = res.data.subList
        subList.value.forEach((res) => {
          res.fromLocationCode = res.toLocationCode
        })
        toLocationCode.value = res.data.toLocationCode
        detailSource.value = getDataSource(subList.value)
      } else {
        showMessage('列表数据为0')
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}
const calcHandleQty1 = () => {
  calcHandleQty(detailSource.value)
  continueScan()
}
// 继续扫描
const continueScan = () => {
  scanCount.value = getScanCount(subList.value)
  if (scanCount.value == subList.value.length) {
    closeScanPopup()
  } else {
    scanPopupGetFocus()
  }
}
const calcScanCount = (closeScan) => {
  const items = subList.value.filter((r) => {
    if (r.scaned) {
      return r
    }
  })
  scanCount.value = items != null ? items.length : 0
  if (scanCount.value == subList.value.length) {
    closeScanPopup()
  }
}
const updateData = () => {
  calcHandleQty1()
}

const getScanResult = (result) => {
  try {
    const { packingNumber } = result.label
    const { batch } = result.label
    const { qty } = result.label
    const { itemCode } = result.label
    let itemDetail
    const detail = detailSource.value.find((r) => r.itemCode == itemCode)
    if (detail == undefined) {
      showMessage(`物料号【${itemCode}】不在列表中`)
    } else {
      const balanceStatus = getInventoryStatusName(result.balance.inventoryStatus)
      // 箱码、批次、库位、状态 都相等
      itemDetail = detail.subList.find((r) => {
        return r.packingNumber == packingNumber && r.batch == batch && r.fromLocationCode == result.fromLocationCode && r.inventoryStatus == result.balance.inventoryStatus
      })
      if (itemDetail) {
        // 箱码、批次、库位、状态一致
        if (itemDetail.scaned) {
          showErrorMessage(`箱码【${packingNumber}】<br>批次【${batch}】<br>库位【${result.fromLocationCode}】<br>状态【${balanceStatus}】<br>已经扫描`)
          return
        }
        itemDetail.scaned = true
        itemDetail.handleQty = Number(result.balance.qty)
        itemDetail.toInventoryStatus = result.balance.inventoryStatus
        itemDetail.inventoryStatus = result.balance.inventoryStatus
        itemDetail.balance = result.balance
        itemDetail.balance.balanceQty = Number(result.balance.qty)
        itemDetail.balance.packQty = Number(result.package.packQty)
        itemDetail.balance.packUnit = result.package.packUnit
        calcHandleQty1()
      } else {
        // 箱码、批次、库位相等
        itemDetail = detail.subList.find((r) => {
          return r.packingNumber == packingNumber && r.batch == batch && r.fromLocationCode == result.fromLocationCode
        })

        if (itemDetail) {
          // 箱码、批次、库位相等，状态不相等
          if (jobContent.value.allowModifyInventoryStatus == 'TRUE') {
            showQuestionMessage(`实际库存状态[${balanceStatus}]与推荐库存状态[${itemStatus}]不一致,是否继续退货?`, (res) => {
              if (res) {
                itemDetail.scaned = true
                itemDetail.handleQty = Number(result.balance.qty)
                itemDetail.toInventoryStatus = result.balance.inventoryStatus
                itemDetail.inventoryStatus = result.balance.inventoryStatus
                itemDetail.balance = result.balance
                itemDetail.balance.balanceQty = result.balance.qty
                itemDetail.balance.packQty = result.package.packQty
                itemDetail.balance.packUnit = result.package.packUnit
                calcHandleQty1()
              } else {
                scanPopupGetFocus()
              }
            })
          } else {
            showQuestionMessage(`任务中不允许修改库存状态,实际库存状态[${balanceStatus}]与推荐库存状态[${itemStatus}]不一致,不允许回收!`, (res) => {
              scanPopupGetFocus()
            })
          }
        } else {
          showErrorMessage(`箱码【${packingNumber}】<br>批次【${batch}】<br>库位【${result.fromLocationCode}】<br>状态【${balanceStatus}】<br>不在任务列表中`)
        }
      }
    }
    scanPopupGetFocus()
  } catch (e) {
    showErrorMessage(e.message)
  }
}
const commit = () => {
  scanCount.value = getScanCount(subList.value)
  if (scanCount.value == 0) {
    showErrorMessage('扫描数为0,请先扫描')
    return
  }
  // 允许部分提交
  // 扫描数量和任务数量相等，直接提交
  if (scanCount.value == subList.value.length) {
    submitJob()
  } else if (scanCount.value < subList.value.length) {
    // 扫描数量小于任务数量，判断是否允许部分提交
    if (jobContent.value.allowPartialComplete == 'TRUE') {
      // 提交
      submitJob()
    } else {
      // 不允许部分提交，提示
      comMessageRef.value.showErrorMessage('请完成扫描后,再进行提交<br>' + `已经扫描[${scanCount.value}]箱总共[${subList.value.length}]箱`, (res) => {
        if (res) {
          openScanPopup()
        }
      })
    }
  }
}

const submitJob = () => {
  proxy.$modal.loading('提交中...')
  const params = setParams()
  productRecycleJobsubmit(params)
    .then((res) => {
      uni.hideLoading()
      if (res.data) {
        showCommitSuccessMessage(res.data)
      } else {
        showErrorMessage(`提交失败[${res.msg}]`)
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}
const setParams = () => {
  const subList = []
  const creator = store.id

  detailSource.value.forEach((item) => {
    item.subList.forEach((detail) => {
      if (detail.scaned) {
        detail.toPackingNumber = detail.packingNumber
        detail.toContainerNumber = detail.containerNumber
        detail.toBatch = detail.batch

        detail.toLocationCode = detail.toLocationCode
        subList.push(detail)
      }
    })
  })
  jobContent.value.subList = subList
  jobContent.value.creator = creator
  return jobContent.value
}

const openScanPopup = () => {
  let fromlocationCode = ''
  const fromlocationList = []
  for (let i = 0; i < detailSource.value.length; i++) {
    const item = detailSource.value[i]
    item.subList.forEach((l) => {
      // 重复的库位不往里面插入
      const location = fromlocationList.find((res) => res == l.fromLocationCode)
      if (location == undefined) {
        fromlocationList.push(l.fromLocationCode)
      }
      // 来源库位赋默认值
      if (fromlocationCode == '') {
        if (!l.scaned) {
          fromlocationCode = l.fromLocationCode
        }
      }
    })
  }
  scanPopup.value.openScanPopupForJob(fromlocationCode, fromlocationList, jobContent.value)
}

const closeScanPopup = () => {
  scanPopup.value.closeScanPopup()
}

const scanPopupGetFocus = () => {
  scanPopup.value.packGetFocus()
}

const scanPopupLoseFocus = () => {
  scanPopup.value.packLoseFocus()
}

const openDetail = (item) => {
  jobDetailPopup.value.openPopup(item)
}

const showMessage = (message) => {
  comMessageRef.value.showMessage(message, (res) => {
    if (res) {
      scanPopupGetFocus()
    }
  })
}

const showErrorMessage = (message) => {
  comMessageRef.value.showErrorMessage(message, (res) => {
    if (res) {
      scanPopupGetFocus()
    }
  })
}
const showQuestionMessage = (message, callback) => {
  setTimeout((r) => {
    scanPopupLoseFocus()
    comMessageRef.value.showQuestionMessage(message, (res) => {
      if (res) {
        callback(res)
      }
    })
  })
}
const showCommitSuccessMessage = (hint) => {
  comMessageRef.value.showSuccessMessage(`提交成功<br>生成制品回收记录<br>:${number}`, (res) => {
    navigateBack(1)
  })
}
</script>

<style scoped lang="scss"></style>
