<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>
    </view>

    <view class="page-main">
      <scroll-view scroll-y="true" class="page-main-scroll">
        <view class="detail-list u-p-t-20" v-for="(item, index) in detailSource" :key="item.id">
          <view class="cen_card" style="padding: 20rpx 0px 0px">
            <view class="cell_box uni-flex uni-row">
              <view class="cell_info">
                <view class="text_lightblue">车间</view>
                <view>
                  {{ jobContent.workShopCode }}
                </view>
              </view>
              <view class="cell_info">
                <view class="text_lightblue">生产线</view>
                <view>
                  {{ item.subList[0].productionLineCode }}
                </view>
              </view>
              <view class="cell_info">
                <view class="text_lightblue">班组</view>
                <view>
                  {{ jobContent.team }}
                </view>
              </view>
              <view class="cell_info">
                <view class="text_lightblue">班次</view>
                <view>
                  {{ jobContent.shift }}
                </view>
              </view>
            </view>
            <view class="split_line"></view>
          </view>

          <view class="">
            <comProductDetailCard :dataContent="item" :settingParam="jobContent" :isShowLocation="false" @remove="updateData" @updateData="updateData" :locationAreaTypeList="toLocationAreaTypeList"> </comProductDetailCard>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="page-footer">
      <view class="uni-flex u-col-center space-between padding_10" style="background-color: ghostwhite; width: 100%">
        <view class="">
          <locationCompare ref="comScanLocation" title="收货库位" :isShowEdit="jobContent.allowModifyLocation == 'TRUE'" :recommendLocationCode="jobToLocationCode" :locationCode="toLocationCode" @getLocation="scanLocationCode" :locationAreaTypeList="toLocationAreaTypeList"> </locationCompare>
        </view>
        <view class="uni-flex uni-row">
          <button class="btn_single_commit" hover-class="btn_commit_after" @click="commit">提交</button>
        </view>
      </view>
    </view>

    <win-scan-button @goScan="openScanPopup"></win-scan-button>
    <win-scan-pack ref="scanPopup" @getResult="getScanResult" :title="'制品标签'" headerType="HMQ"></win-scan-pack>
    <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 { getManagementPrecisions } from '@/common/balance.js'

import { getProductReceiptJobDetail, takeProductReceiptJob, cancleTakeProductReceiptJob, productReceiptJobsubmit } from '@/api/request2.js'
import { goHome, navigateBack, getPackingNumberAndBatch } from '@/common/basic.js'

import { getDirectoryItemArray, getInventoryStatusName } from '@/common/directory.js'

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

import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import locationCompare from '@/mycomponents/location/locationCompare.vue'
import winScanPack from '@/mycomponents/scan/winScanPack.vue'
import comDetailCard from '@/mycomponents/detail/comDetailCard.vue'
import jobTop from '@/mycomponents/job/jobTop.vue'
import comProductDetailCard from '@/pages/productReceipt/coms/comProductDetailCard.vue'
import { useCountStore } from '@/store'
// 获取自定义的store
const store = useCountStore()
const { proxy } = getCurrentInstance()
const id = ref('')
const receiptJob = ref({})
const toLocationCode = ref('')
const isShowPackingCode = ref(true)
const scanCount = ref(0)
const jobContent = ref({}) // 任务内容
const subList = ref([]) // 接口返回的任务subList
const detailSource = ref([]) // 绑定在页面上的数据源
const toLocationAreaTypeList = ref([])
const managementList = ref([])
const jobStatus = ref('')
const jobToLocationCode = ref('')
const scanedPackingNumber = ref('')
const status = ref('')
const scanPopup = ref()
const comScanLocation = ref()
const comMessageRef = ref()
onLoad((option) => {
  uni.setNavigationBarTitle({
    title: `${option.title}详情`
  })
  id.value = option.id
  scanedPackingNumber.value = option.scaned || ''
  status.value = option.status || ''
})
onShow(() => {
  if (id.value != undefined) {
    // 新建的任务自动接收
    if (status.value == '1') {
      receive((callback) => {
        getDetail()
      })
    } else {
      getDetail()
    }
  }
})
// 返回首页
onNavigationBarButtonTap((e) => {
  if (e.index === 0) {
    goHome()
  }
})
// 拦截返回按钮事件
onBackPress((e) => {
  // 已经接收但是没提交任务
  if (e.from == 'backbutton') {
    if (jobStatus.value == '2') {
      // 取消承接任务
      cancleTakeProductReceiptJob(id.value)
        .then((res) => {
          uni.navigateBack()
        })
        .catch((error) => {
          uni.navigateBack()
        })
    } else {
      uni.navigateBack()
    }
    return true
  }
})
onPullDownRefresh(() => {
  getDetail()
  uni.stopPullDownRefresh()
})
// 接收
const receive = (callback) => {
  if (id.value != null) {
    takeProductReceiptJob(id.value)
      .then((res) => {
        callback()
      })
      .catch((error) => {
        showErrorMessage(error)
      })
  }
}
const getDetail = () => {
  proxy.$modal.loading('加载中....')
  getProductReceiptJobDetail(id.value)
    .then((res) => {
      uni.hideLoading()
      if (res.data == null) {
        showMessage('未获取到详情')
      } else if (res.data.subList.length > 0) {
        jobContent.value = res.data
        subList.value = res.data.subList
        jobStatus.value = res.data.status
        jobToLocationCode.value = subList.value[0].toLocationCode
        if (jobContent.value.allowModifyLocation == 'FALSE') {
          toLocationCode.value = subList.value[0].toLocationCode
        }
        toLocationAreaTypeList.value = getDirectoryItemArray(jobContent.value.toAreaTypes)
        detailSource.value = getDataSource(subList.value)
        detailSource.value.forEach((r) => {
          r.subList.forEach((s) => {
            if (scanedPackingNumber.value && scanedPackingNumber.value == s.packingNumber) {
              s.scaned = true
              s.cancleScanedHiht = true
              s.copyContent = `HMQ;V1.0;I${s.itemCode};P${s.packingNumber};B${s.batch};Q${s.qty}`
              scanPopup.value.simulateScan(s)
              scanedPackingNumber.value = ''
              // s.handleQty = s.qty
            }
          })
        })
      } else {
        showMessage('列表数据为0')
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}
const getScanResult = (result) => {
  const { label } = result
  const { packingNumber } = label
  const { batch } = label
  const { qty } = label
  const { itemCode } = label

  const detail = detailSource.value.find((r) => r.itemCode == itemCode)
  if (detail == undefined) {
    showErrorMessage(`物料号【${itemCode}】不在列表中`)
  } else {
    const itemDetail = detail.subList.find((r) => r.packingNumber == packingNumber && r.batch == batch)
    if (itemDetail == undefined) {
      showErrorMessage(`箱码[${packingNumber}]` + `批次[${batch}]不在任务列表中`)
    } else if (!itemDetail.cancleScanedHiht && itemDetail.scaned) {
      showErrorMessage(`箱码[${packingNumber}]` + `批次[${batch}]已经扫描`)
    } else {
      itemDetail.scaned = true
      itemDetail.handleQty = Number(result.label.qty)
      itemDetail.toLocationCode = toLocationCode.value
      itemDetail.labelQty = Number(result.label.qty)
      calcHandleQty(detailSource.value)
      continueScan()
    }
  }
}

// 继续扫描

const continueScan = () => {
  scanCount.value = getScanCount(subList.value)
  if (scanCount.value == subList.value.length) {
    closeScanPopup()
  } else {
    scanPopupGetFocus()
  }
}

const updateData = () => {
  calcHandleQty(detailSource.value)
}

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

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

const scanLocationCode = (location, code) => {
  toLocationCode.value = code
  detailSource.value.forEach((item) => {
    item.subList.forEach((detail) => {
      detail.toLocationCode = code
    })
  })
}

const checkLocation = () => {
  let isPass = true
  if (toLocationCode.value == '' || toLocationCode.value == null) {
    showMessageHint('请扫描收货库位', (callback) => {
      comScanLocation.value.showLocation()
    })

    return (isPass = false)
  }
  return isPass
}

const showMessageHint = (hint, callback) => {
  comMessageRef.value.showErrorMessage(hint, (res) => {
    if (res) {
      callback()
    }
  })
}

const commit = () => {
  scanCount.value = getScanCount(subList.value)
  if (scanCount.value == 0) {
    showErrorMessage('扫描数为0,请先扫描')
    return
  }
  // 校验库位、
  if (!checkLocation()) {
    return
  }

  // 扫描数量和任务数量相等，直接提交
  if (scanCount.value == subList.value.length) {
    if (checkCount()) {
      submitJob()
    }
  } else if (scanCount.value < subList.value.length) {
    // 扫描数量小于任务数量，判断是否允许部分提交
    if (jobContent.value.allowPartialComplete == 'TRUE') {
      // 提交
      if (checkCount()) {
        submitJob()
      }
    } else {
      // 不允许部分提交，提示
      showMessage('请完成扫描后,再进行提交<br>' + `已经扫描[${scanCount.value}]总共[${subList.value.length}]`)
    }
  }
}

const checkCount = () => {
  let isCheck = true
  let hint = ''
  for (let i = 0; i < detailSource.value.length; i++) {
    const item = detailSource.value[i]
    for (let j = 0; j < item.subList.length; j++) {
      const subItem = item.subList[i]
      if (calc.sub(subItem.handleQty, subItem.qty) < 0) {
        isCheck = false
        hint = `包装【${subItem.packingNumber}】实际收货数量:${subItem.handleQty}与包装数量${subItem.qty}不相等，是否继续收货?`
        break
      }
    }
  }
  if (!isCheck) {
    showQuestMessage(hint, (res) => {
      if (res) {
        submitJob()
      }
    })
  }

  return isCheck
}

const submitJob = () => {
  proxy.$modal.loading('提交中....')
  const itemCodes = []
  detailSource.value.forEach((item) => {
    itemCodes.push(item.itemCode)
  })
  getManagementPrecisions(itemCodes, toLocationCode.value, (res) => {
    if (res.success) {
      managementList.value = res.list
      const params = setParams()
      productReceiptJobsubmit(params)
        .then((res) => {
          uni.hideLoading()
          if (res.data) {
            showCommitSuccessMessage(`提交成功<br>生成预生产收货记录<br>${res.data}`)
          } else {
            showErrorMessage(`提交失败[${res.msg}]`)
          }
        })
        .catch((error) => {
          uni.hideLoading()
          showErrorMessage(error)
        })
    } else {
      uni.hideLoading()
      showErrorMessage(res.message)
    }
  })
}

const setParams = () => {
  const subList = []
  const creator = store.id

  detailSource.value.forEach((item) => {
    item.subList.forEach((detail) => {
      if (detail.scaned) {
        const info = getPackingNumberAndBatch(managementList.value, detail.itemCode, detail.packingNumber, detail.batch)
        detail.toPackingNumber = info.packingNumber
        detail.toBatch = info.batch
        detail.toContainerNumber = ''
        detail.toInventoryStatus = detail.inventoryStatus
        detail.toLocationCode = toLocationCode.value
        subList.push(detail)
      }
    })
  })
  jobContent.value.subList = subList
  jobContent.value.creator = creator
  return jobContent.value
}

const scanPopupGetFocus = () => {
  if (scanPopup.value != undefined) {
    scanPopup.value.getfocus()
  }
}

const scanPopupLoseFocus = () => {
  if (scanPopup.value != undefined) {
    scanPopup.value.losefocus()
  }
}

const showMessage = (message) => {
  setTimeout((r) => {
    scanPopupLoseFocus()
    comMessageRef.value.showMessage(message, (res) => {
      if (res) {
        scanPopupGetFocus()
      }
    })
  })
}
const showErrorMessage = (message) => {
  setTimeout((r) => {
    scanPopupLoseFocus()
    comMessageRef.value.showErrorMessage(message, (res) => {
      scanPopupGetFocus()
    })
  })
}
const showCommitSuccessMessage = (hint) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    navigateBack(1)
  })
}
const showQuestMessage = (hint, callback) => {
  this.$refs.comMessage.showQuestionMessage(hint, (res) => {
    if (res) {
      callback(true)
    }
  })
}
</script>

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