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

    <view class="page-main">
      <scroll-view scroll-y="true" class="page-main-scroll">
        <view v-for="(toLocation, index) in detailSource">
          <com-repleish-detail-card ref="comIssueDetailCardRef" :dataContent="toLocation" @updateData="updateData"> </com-repleish-detail-card>
        </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="">
          <requiredLocation ref="comScanLocation" title="目标库位" :locationCode="toLocationCode" @getLocation="scanLocationCode" :isShowEdit="jobContent.allowModifyLocation == 'TRUE'" :locationAreaTypeList="toLocationAreaTypeList"></requiredLocation>
        </view>
        <view class="uni-flex uni-row">
          <button class="btn_single_commit" hover-class="btn_commit_after" @click="submit">提交</button>
        </view>
      </view>
    </view>

    <win-scan-button @goScan="openScanDetailPopup"></win-scan-button>
    <com-scan-replish-pack ref="comScanIssuePackRef" @closeScan="closeScan" @updateData="updateData"> </com-scan-replish-pack>
    <com-message ref="comMessageRef" />
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, nextTick, watch } from 'vue'
import { onLoad, onShow, onNavigationBarButtonTap, onReady, onBackPress, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { takeRepleinshJob, cancleTakeRepleinshJob, getRepleinshJobDetail, repleinshJobSubmit } from '@/api/request2.js'

import { goHome, navigateBack, getRemoveOption, getCurrDateTime, getDirectoryItemArray, getPackingNumberAndBatch, deepCopyData } from '@/common/basic.js'

import { getDataSource } from '@/pages/issue/js/issue.js'

import { calc } from '@/common/calc.js'

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

import requiredLocation from '@/mycomponents/location/requiredLocation.vue'
import jobDetailPopup from '@/mycomponents/job/jobDetailPopup.vue'
import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import comRepleishDetailCard from '@/pages/repleinsh/coms/comRepleishDetailCard.vue'
import comScanReplishPack from '@/pages/repleinsh/coms/comScanReplishPack.vue'
import jobTop from '@/mycomponents/job/jobTop.vue'

import { useCountStore } from '@/store'
// 获取自定义的store
const store = useCountStore()
const { proxy } = getCurrentInstance()
const id = ref('')
const jobContent = ref({}) // 任务内容
const subList = ref([]) // 接口返回的任务subList
const detailSource = ref([]) // 绑定在页面上的数据源
const detailOptions = ref([])
const scanOptions = ref([])
const toLocationCode = ref('')
const toLocationAreaTypeList = ref([])
const jobStatus = ref('')
const comIssueDetailCardRef = ref()

const comMessageRef = ref()
const locationCompareRef = ref()
const scanPopup = ref()

const receiptJob = ref({})
const scanCount = ref(0)
const jobToLocationCode = ref('')
const toLocationInfo = ref({})
const businessTypeInfo = ref({})
const managementList = ref([])
const isAllReceived = ref(false)
const operation = ref('')
const comScanIssuePackRef = ref()
const locationTypes = ref()

onLoad((option) => {
  uni.setNavigationBarTitle({
    title: `${option.title}详情`
  })
  id.value = option.id
  operation.value = option.operation
  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') {
      // 取消承接任务
      cancleTakeRepleinshJob(id.value)
        .then((res) => {
          uni.navigateBack()
        })
        .catch((error) => {
          uni.navigateBack()
        })
    } else {
      uni.navigateBack()
    }
    return true
  }
})
// 拦截返回按钮事
watch(
  () => locationTypes.value,
  (newVal) => {
    const value = newVal
  }
)
// 接收
const receive = (callback) => {
  proxy.$modal.loading('加载中....')
  if (id.value != null) {
    takeRepleinshJob(id.value)
      .then((res) => {
        uni.hideLoading()
        callback()
      })
      .catch((error) => {
        uni.hideLoading()
        showErrorMessage(error)
      })
  }
}
const getDetail = () => {
  proxy.$modal.loading('加载中....')
  getRepleinshJobDetail(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
        toLocationCode.value = subList.value[0].toLocationCode
        console.log(`库位${toLocationCode.value}`)
        toLocationAreaTypeList.value = getDirectoryItemArray(jobContent.value.toAreaTypes)
        detailSource.value = getDataSource(detailSource.value, subList.value)
        setTimeout((r) => {
          resizeCollapse()
        }, 100)
      } else {
        showMessage('列表数据为0')
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}
const closeScan = () => {
  resizeCollapse()
}

const resizeCollapse = () => {
  nextTick((r) => {
    comIssueDetailCardRef.value.forEach((r) => {
      r.resizeCollapse()
    })
  })
}

const submit = () => {
  const scanCount = getScanCount(subList.value)

  // 允许部分提交
  // if (jobContent.value.allowPartialComplete == 'TRUE') {
  //   // 如果扫描数是0，提示扫描数为0，是否提交，点击确定提交，取消提示消失
  //   if (scanCount == 0) {
  //     comMessageRef.value.showQuestionMessage('扫描数为0,是否提交?', (res) => {
  //       setSubmitParamsAndSubmit()
  //     })
  //   } else {
  //     setSubmitParamsAndSubmit()
  //   }
  // } else {
  // 不允许部分提交，扫描数必须等于任务数量才可以提交
  if (scanCount == 0) {
    showErrorMessage('扫描数为0,当前补料任务不允许部分提交,请先扫描')
  } else {
    setSubmitParamsAndSubmit()
  }
  // }
}

const setSubmitParamsAndSubmit = () => {
  // 目前任务只到一个库位

  submitJob()
  // // 使用在途库，不查询管理模式
  // if (jobContent.value.useOnTheWayLocation == 'TRUE') {
  //   submitJob()
  // } else {
  //   // 获取管理模式，封装参数
  //   getManagementPrecisions(itemCodes, locationCode, (res) => {
  //     if (res.success) {
  //       managementList.value = res.list
  //       submitJob()
  //     } else {
  //       uni.hideLoading()
  //       showErrorMessage(res.message)
  //     }
  //   })
  // }
}

const submitJob = () => {
  proxy.$modal.loading('提交中....')
  const params = setParams()

  repleinshJobSubmit(params)
    .then((res) => {
      uni.hideLoading()
      if (res.data) {
        showCommitSuccessMessage(`提交成功<br>生成补料记录<br>${res.data}`)
      } else {
        showErrorMessage(`提交失败[${res.msg}]`)
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}

const setParams = () => {
  const commitSubList = []
  const createTime = getCurrDateTime()
  const creator = store.id
  detailSource.value.forEach((toLocationCodeParams) => {
    toLocationCodeParams.Items.forEach((item) => {
      item.Locations.forEach((fromLocation) => {
        fromLocation.Batchs.forEach((batch) => {
          const subItem = batch.detail

          if (subItem != undefined) {
            if (batch.Records.length > 0) {
              subItem.recordList = []
              batch.Records.forEach((r) => {
                const record = {}
                record.handleQty = r.qty

                // record.fromPackingNumber = r
                // 	.packingNumber;
                record.fromBatch = r.batch
                record.fromContainerNumber = r.containerNumber

                record.toContainerNumber = r.containerNumber
                record.toInventoryStatus = r.inventoryStatus
                record.toLocationCode = toLocationCode.value
                console.log(`提交${toLocationCode.value}`)
                record.supplierCode = r.supplierCode
                record.fromParentPackingNumber = r.parentPackingNumber

                record.fromPackingNumber = r.packingNumber
                record.toPackingNumber = r.packingNumber
                record.toPackUnit = r.packUnit
                record.toBatch = r.batch

                subItem.recordList.push(record)
              })
              commitSubList.push(deepCopyData(subItem))
            }
          }
        })
      })
    })
  })

  jobContent.value.subList = commitSubList
  jobContent.value.createTime = createTime
  jobContent.value.creator = creator
  return jobContent.value
}

const cancel = () => {
  comMessageRef.value.showSuccessMessage('是否要清空已扫描的物料和目标库位信息?', (res) => {
    if (res) {
      clearInfo()
    }
  })
}

const clearInfo = () => {
  dataContent.value.itemCodeList.forEach((res) => {
    if (res.recommendList != null) {
      res.recommendList.forEach((res1) => {
        if (res1.locationCodeList != null) {
          res1.locationCodeList.forEach((res2) => {
            if (res2.packingCodeList != null) {
              res2.packingCodeList.forEach((res3) => {
                res3.itemCode = ''
                res3.qty = 0
              })
            }
          })
        }
      })
    }
  })
}

const updateData = (record) => {
  const requestLocation = detailSource.value.find((r) => r.toLocationCode == record.toLocationCode)
  const item = requestLocation.Items.find((r) => r.itemCode == record.itemCode)
  let itemHandleQty = 0
  if (item != undefined) {
    item.Locations.forEach((l) => {
      const batch = l.Batchs.find((b) => (b.packingNumber == record.packingNumber || b.packingNumber == null || b.packingNumber == '') && b.batch == record.batch)
      let handleQty = 0
      if (batch != undefined) {
        batch.Records.forEach((res) => {
          handleQty = calc.add(handleQty, res.qty)
        })
        batch.handleQty = handleQty
        itemHandleQty = calc.add(itemHandleQty, handleQty)
        comScanIssuePackRef.value.calcBatchHandleQty(batch)
      }
    })
  }

  // item.handleQty=itemHandleQty;
}

const scanPopupGetFocus = () => {
  if (scanPopup.value != undefined) {
    scanPopup.value.getfocus()
  }
}
const showMessage = (message) => {
  comMessageRef.value.showMessage(message, (res) => {
    afterCloseMessage()
  })
}
const showErrorMessage = (message) => {
  comMessageRef.value.showErrorMessage(message, (res) => {
    afterCloseMessage()
  })
}
const showScanMessage = (message) => {
  comMessageRef.value.showScanMessage(message)
}
const showCommitSuccess = () => {
  comMessageRef.value.showCommitSuccess()
}
const showCommitSuccessMessage = (hint) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    navigateBack(1)
  })
}
const showRescanMessage = (message) => {
  comMessageRef.value.showRescanMessage(message)
}
const afterCloseMessage = () => {
  scanPopupGetFocus()
}

const closeScanMessage = () => {
  scanPopupGetFocus()
}
const confirm = (data) => {
  dataContent.value = data
}
const confirmResult = (result) => {
  dataContent.value = result
}
const openScanDetailPopup = () => {
  const datacontent = {}
  // 克隆对象，深度克隆，防止双向绑定同一个变量
  // Object.assign(datacontent, this.detailSource);
  comScanIssuePackRef.value.openScanPopup(detailSource.value, jobContent.value)
}
const closeScanPopup = () => {
  updateCommitBtn()
}
const scanLocationCode = (location, code) => {
  toLocationCode.value = code
}
const getScanCount = (subList) => {
  let scanCount = 0
  detailSource.value.forEach((toLocationCodeParams) => {
    toLocationCodeParams.Items.forEach((item) => {
      item.Locations.forEach((fromLocation) => {
        fromLocation.Batchs.forEach((batch) => {
          const subItem = batch.detail
          if (batch.Records.length > 0) {
            scanCount = calc.add(scanCount, batch.Records.length)
          }
        })
      })
    })
  })
  return scanCount
}
</script>

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