<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="">
            <comJobDetailCard :dataContent="item" :index="index" :settingParam="jobContent" :isShowStatus="false" @remove="updateData" @updateData="updateData" :locationAreaTypeList="toLocationAreaTypeList"> </comJobDetailCard>
          </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="目标库位" :recommendLocationCode="jobToLocationCode" :locationCode="toLocationCode" @getLocation="scanLocationCode" :isShowEdit="isCheckLocation" :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>
    <!-- <winScanPackAndLocationNoBalance ref="scanPopup" @getResult="getScanResult" :allowNullBalance="true"> </winScanPackAndLocationNoBalance> -->
    <winScanPackAndLocation :balanceFromInventoryStatuses="false" ref="scanPopup" @getResult="getScanResult" :noShowBalanceMessage="true"> </winScanPackAndLocation>
    <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 { getPutawayJobDetail, getBasicLocationByCode, putawayJobSubmit, takePutawayJob, cancleTakePutawayJob, getSwitchByCode } from '@/api/request2.js'
import { goHome, getCurrDateTime, getPackingNumberAndBatch, navigateBack, compareAsc, getSwitchInfoByCode } from '@/common/basic.js'

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

import { getTreeDataSource, calcHandleQty, calcTreeHandleQty, getScanCount } from '@/common/detail.js'

import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import winScanPackAndLocation from '@/mycomponents/scan/winScanPackAndLocation.vue'
import comJobDetailCard from '@/mycomponents/detail/comJobDetailCard.vue'
import locationCompare from '@/mycomponents/location/locationCompare.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 managementList = ref([])
const fromLocationCode = ref('')
const toLocationCode = ref('')
const toLocationAreaTypeList = ref([])
const jobStatus = ref('')
const jobToLocationCode = ref('')
const isCheckLocation = ref(false)
const scanedPackingNumber = ref('')
const scanPopup = ref()
const comScanLocation = ref()
const comMessageRef = ref()
onLoad((option) => {
  id.value = option.id
  scanedPackingNumber.value = option.scaned || ''
  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') {
      // 取消承接任务
      cancleTakePutawayJob(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) {
    takePutawayJob(id.value)
      .then((res) => {
        callback()
      })
      .catch((error) => {
        showErrorMessage(error)
      })
  }
}
const getDetail = () => {
  proxy.$modal.loading('加载中...')
  getPutawayJobDetail(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
        detailSource.value = getTreeDataSource(subList.value)

        fromLocationCode.value = subList.value[0].fromLocationCode
        jobToLocationCode.value = subList.value[0].toLocationCode
        toLocationAreaTypeList.value = getDirectoryItemArray(jobContent.value.toAreaTypes)
        isCheckLocation.value = getSwitchInfoByCode('PurchasePutawayToLocationCodeValidate')
        if (isCheckLocation.value) {
          toLocationCode.value = ''
        } else {
          toLocationCode.value = jobToLocationCode.value
        }
        detailSource.value.forEach((r) => {
          r.subList.forEach((s) => {
            if (scanedPackingNumber.value && scanedPackingNumber.value == s.packingNumber) {
              s.scaned = true
              s.packList.forEach((item) => (item.scaned = true))
              s.inventoryStatus = s.inspectResult // 更新检验结果状态
              openScanPopupSimulate(s)
            }
          })
        })
      } else {
        showMessage('列表数据为0')
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}
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 calcHandleQty = () => {
  calcTreeHandleQty(detailSource.value)
  continueScan()
}

// 继续扫描

const continueScan = () => {
  scanCount.value = getScanCount(subList.value)
  if (scanCount.value == subList.value.length) {
    closeScanPopup()
  } else {
    scanPopupGetFocus()
  }
}
const updateData = () => {
  calcTreeHandleQty(detailSource.value)
}
// 模拟扫描功能
const openScanPopupSimulate = (item) => {
  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 == '') {
        fromlocationCode = l.fromLocationCode
      }
    })
  }
  scanPopup.value.openScanPopupForJobSimulate(fromlocationCode, fromlocationList, jobContent.value, item)
}
const openScanPopup = () => {
  let fromlocationCode = ''
  const fromlocationList = []
  // item.subList.forEach(l => {
  // 	//重复的库位不往里面插入
  // 	var location = fromlocationList.find(res => res == l.fromLocationCode)
  // 	if (location == undefined) {
  // 		fromlocationList.push(l.fromLocationCode);
  // 	}
  // 	//来源库位赋默认值
  // 	if (fromlocationCode == '') {
  // 		if (!l.scaned) {
  // 			fromlocationCode = l.fromLocationCode;
  // 		}
  // 	}
  // })
  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) {
      }
      // 来源库位赋默认值
      if (fromlocationCode == '') {
        if (!l.scaned) {
          fromlocationCode = l.fromLocationCode
        }
      }
    })
  }
  scanPopup.value.openScanPopupForJob(fromlocationCode, fromlocationList, jobContent.value)
}
const closeScanPopup = () => {
  scanPopup.value.closeScanPopup()
}
const getScanResult = (result) => {
  try {
    const { packingNumber } = result.label
    const { batch } = result.label
    const { qty } = result.label
    const { itemCode } = result.label
    const locationCode = result.fromLocationCode
    // const inventoryStatus = 'OK'
    const detail = detailSource.value.find((r) => r.itemCode == itemCode)

    if (detail == undefined) {
      showErrorMessage(`物料号【${itemCode}】不在列表中`)
    } else {
      const itemDetail = detail.subList.find((r) => {
        return r.packingNumber == packingNumber && r.batch == batch && r.fromLocationCode == result.fromLocationCode
      })

      if (itemDetail == undefined) {
        let isExit
        for (const subItem of detail.subList) {
          var item
          for (const pack of subItem.packList) {
            if (pack.packingNumber == packingNumber && pack.batch == batch) {
              item = pack
              isExit = pack
              break
            }
          }
          if (item != undefined) {
            subItem.scaned = true
            subItem.handleQty = 0
            item = undefined
          }
        }
        if (isExit == undefined) {
          showErrorMessage(`箱码【${packingNumber}】,批次【${batch}】库位【${result.fromLocationCode}】不在列表中`)
        } else if (isExit.scaned) {
          showMessage(`箱码【${packingNumber}】已经扫描`)
        } else {
          isExit.scaned = true
          let qty = 0
          if (result.balance != null) {
            qty = Number(result.balance.qty)
          } else {
            qty = Number(result.label.qty)
          }
          isExit.handleQty = Number(result.label.qty)
          isExit.toLocationCode = toLocationCode.value
        }
        calcTreeHandleQty(detailSource.value)
      } else {
        let scanedLength = 0
        itemDetail.packList.forEach((res) => {
          if (res.scaned) {
            scanedLength++
          }
        })
        itemDetail.fromInventoryStatus = result.balance.inventoryStatus
        if (itemDetail.scaned && scanedLength == itemDetail.packList.length) {
          showMessage(`箱码【${packingNumber}】已经扫描`)
        } else {
          itemDetail.scaned = true
          detailSource.value[0].subList.sort(compareAsc('scaned')) // 按扫描信息排序
          itemDetail.handleQty = result.label.qty
          // itemDetail.toInventoryStatus = 'OK'
          itemDetail.packList.forEach((pac) => {
            pac.scaned = true
            pac.handleQty = Number(pac.qty)
            pac.toLocationCode = toLocationCode.value
          })
          calcTreeHandleQty(detailSource.value)
          continueScan()
        }
      }
    }
  } catch (e) {
    // showMessage(e.message)
  }
}
const scanLocationCode = (location, code) => {
  toLocationCode.value = code
  detailSource.value.forEach((item) => {
    item.subList.forEach((detail) => {
      detail.toLocationCode = code
    })
  })
}
const openDetail = (item) => {
  jobDetailPopup.value.openPopup(item)
}
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) {
    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 itemCodes = []
  detailSource.value.forEach((item) => {
    itemCodes.push(item.itemCode)
  })

  // 获取管理模式，封装参数
  getManagementPrecisions(itemCodes, toLocationCode.value, (res) => {
    if (res.success) {
      managementList.value = res.list
      const params = setParams()
      console.log(params)
      putawayJobSubmit(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.singlePrice = 1
        detail.amount = 11

        detail.arriveDate = getCurrDateTime()
        detail.produceDate = getCurrDateTime()
        detail.expireDate = getCurrDateTime()

        const packList = detail.packList.filter((p) => p.scaned == true)
        detail.packList = packList

        // detail.singlePrice = detail.balance.singlePrice;
        // detail.amount = detail.balance.singlePrice * detail.handleQty;

        // detail.arriveDate = detail.balance.arriveDate;
        // detail.produceDate = detail.balance.produceDate;
        // detail.expireDate = detail.balance.expireDate;
        subList.push(detail)
      }
    })
  })

  jobContent.value.subList = subList
  jobContent.value.creator = creator
  return jobContent.value
}
const showMessage = (message) => {
  setTimeout((r) => {
    scanPopupLoseFocus()
    comMessageRef.value.showMessage(message, (res) => {
      if (res) {
        afterCloseMessage()
      }
    })
  })
}
const showErrorMessage = (message) => {
  setTimeout((r) => {
    scanPopupLoseFocus()
    comMessageRef.value.showErrorMessage(message, (res) => {
      if (res) {
        afterCloseMessage()
      }
    })
  })
}
const showQuestionMessage = (message, callback) => {
  setTimeout((r) => {
    scanPopupLoseFocus()
    comMessageRef.value.showQuestionMessage(message, (res) => {
      if (res) {
        callback(res)
      }
    })
  })
}
const scanPopupGetFocus = () => {
  scanPopup.value.packGetFocus()
}
const scanPopupLoseFocus = () => {
  scanPopup.value.packLoseFocus()
}
const afterCloseMessage = () => {
  scanPopupGetFocus()
}
const showCommitSuccessMessage = (hint) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    if (res) {
      navigateBack(1)
    }
  })
}
</script>

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