<template>
  <view class="page-wraper">
    <view class="">
      <com-blank-view @goScan="showFromLocationPopup" v-if="detailSource.length == 0"></com-blank-view>
    </view>
    <view class="page-wraper" v-if="detailSource.length > 0">
      <view class="page-header">
        <view class="page-header-box">
          <view class="header_item u-p-t-20"> 来源库位 : {{ fromLocationCode }} </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="">
              <record-com-detail-card :dataContent="item" :index="index" :settingParam="dataContent" :isShowFromLocation="false" @removeItem="removeItem(index, item)" :isShowToLocation="false" @updateData="updateData" @removePack="removePack"> </record-com-detail-card>
            </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="">
            <requiredLocation v-if="showToLoaction" title="目标库位" :locationCode="toLocationCode" @getLocation="getToLocationCode" :locationAreaTypeList="toLocationAreaTypeList"> </requiredLocation>
          </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>
    </view>
    <win-scan-pack-and-location ref="scanPopup" @getResult="getScanResult" :allowModifyLocation="false"> </win-scan-pack-and-location>
    <com-message ref="comMessageRef" />
    <win-scan-location ref="scanLocationCode" title="来源库位" @getLocation="getLocation" :locationAreaTypeList="fromLocationAreaTypeList"></win-scan-location>
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, nextTick } from 'vue'
import { onLoad, onNavigationBarButtonTap, onReady, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { repleinshRecordSubmit, validateItemAndLocation, getPutawayRecommendLocation } from '@/api/request2.js'

import { goHome, updateTitle, getCurrDateTime, getPackingNumberAndBatchByList, deepCopyData } from '@/common/basic.js'

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

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

import { getBusinessType, createItemInfo, createDetailInfo, calcHandleQty } from '@/common/record.js'

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

import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import winScanPack from '@/mycomponents/scan/winScanPack.vue'
import requiredLocation from '@/mycomponents/location/requiredLocation.vue'
import comBlankView from '@/mycomponents/common/comBlankView.vue'
import winScanLocation from '@/mycomponents/scan/winScanLocation.vue'
import winScanPackAndLocation from '@/mycomponents/scan/winScanPackAndLocation.vue'
import recordComDetailCard from '@/mycomponents/record/recordComDetailCard.vue'
import recordDetailCard from '@/mycomponents/record/recordDetailCard.vue'
import { useCountStore } from '@/store'
// 获取自定义的store
const store = useCountStore()
const { proxy } = getCurrentInstance()
const id = ref('')
const dataContent = ref({})
const detailSource = ref([]) // 绑定在页面上的数据源
// const fromLocationInfo = ref({})
const fromLocationCode = ref('')
const fromLocationAreaTypeList = ref([])
const toLocationAreaTypeList = ref([])
const inInventoryStatus = ref('')
const outInventoryStatus = ref('')
const businessType = ref({})
const showToLoaction = ref(true)
const recommendLocationList = ref([]) // 推荐库位列表
const fromWarehouseCode = ref('') // 来源仓库
const businessTypeCode = ref('Repleinment')
const toLocationCode = ref('')
const managementList = ref([])
// const positionList = ref([])
// const show = ref(false)
// const positionInfo = ref('请选择生产线')
const comMessageRef = ref()
const show = ref(false)
const scanPopup = ref()
const scanLocationCode = ref()
onLoad((option) => {
  clear()
  getBusinessType(businessTypeCode.value, (res) => {
    if (res.success) {
      businessType.value = res.businessType
      fromLocationAreaTypeList.value = res.fromLocationAreaTypeList
      toLocationAreaTypeList.value = res.toLocationAreaTypeList
      showFromLocationPopup()
    } else {
      showErrorMessage(res.message)
    }
  })
})
// 返回首页
onNavigationBarButtonTap((e) => {
  if (e.index === 0) {
    goHome()
  }
})

const getScanResult = (result) => {
  const { balance } = result
  const { label } = result
  const pack = result.package
  const { packUnit } = pack
  const { packQty } = pack
  const item = detailSource.value.find((res) => {
    if (res.itemCode == balance.itemCode) {
      return res
    }
  })
  if (fromWarehouseCode.value == '') {
    fromWarehouseCode.value = balance.warehouseCode
  }
  if (item == undefined) {
    const itemp = createItemInfo(balance, pack)
    const newDetail = createDetailInfo(balance, pack)
    newDetail.packUnit = packUnit || ''
    newDetail.packQty = packQty
    itemp.subList.push(newDetail)
    const dataList = pack.subList
    detailSource.value.push(itemp)
    calcHandleQty(detailSource.value)
  } else {
    const detail = item.subList.find((r) => {
      if (r.packingNumber == balance.packingNumber && r.batch == balance.batch && r.locationCode == balance.locationCode && r.inventoryStatus == balance.inventoryStatus) {
        return r
      }
    })
    if (detail == undefined) {
      const newDetail = createDetailInfo(balance, pack)
      newDetail.parentNumber = pack.parentNumber
      newDetail.packingNumber = pack.number
      newDetail.parentNumber = pack.parentNumber
      newDetail.packingNumber = pack.number
      newDetail.packUnit = packUnit
      newDetail.packQty = packQty
      item.subList.push(newDetail)
      calcHandleQty(detailSource.value)
    } else if (detail.scaned == true) {
      showErrorMessage(`箱码[${balance.packingNumber}批次[${balance.batch}]已经在列表中`)
    }
  }
}

const updateData = () => {
  calcHandleQty(detailSource.value)
  for (let i = 0; i < detailSource.value.length; i++) {
    const item = detailSource.value[i]
    if (item.qty == 0) {
      detailSource.value.splice(i, 1)
    }
  }
}

const removeItem = (index, item) => {
  detailSource.value.splice(index, 1)
  updateData()
}

const removePack = () => {
  for (let i = 0; i < detailSource.value.length; i++) {
    const item = detailSource.value[i]
    if (item.subList.length == 0) {
      detailSource.value.splice(i, 1)
    }
  }
}

const openScanPopup = () => {
  if (fromLocationCode.value == '') {
    showFromLocationPopup()
    return
  }
  scanPopup.value.openScanPopupForType(fromLocationCode.value, businessType.value)
}

const showFromLocationPopup = () => {
  nextTick(() => {
    scanLocationCode.value.openScanPopup()
  })
}

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

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

const commit = () => {
  if (toLocationCode.value == '') {
    showMessage('请输入目标库位')
    return
  }

  detailSource.value.forEach((item) => {
    item.subList.forEach((detail) => {
      detail.toLocationCode = toLocationCode.value
      detail.fromLocation = fromLocationCode.value
    })
  })

  uni.showLoading({
    title: '提交中....',
    mask: true
  })

  // 记录有目标库位，需要查询管理模式
  const precisionStrategyParams = getPrecisionStrategyParams(detailSource.value)
  // 2:获取管理模式，封装参数
  getPrecisionStrategyList(precisionStrategyParams, (res) => {
    if (res.success) {
      managementList.value = res.list
      const params = setRecordParams()

      repleinshRecordSubmit(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 setRecordParams = () => {
  const subList1 = []
  const creator = store.id
  detailSource.value.forEach((item) => {
    item.subList.forEach((detail) => {
      if (detail.scaned) {
        const info = getPackingNumberAndBatchByList(managementList.value, detail.itemCode, detail.packingNumber, detail.toLocationCode, detail.batch)
        const submitItem = deepCopyData(detail)
        submitItem.toPackingNumber = info.packingNumber
        submitItem.toBatch = info.batch
        submitItem.toContainerNumber = detail.containerNumber

        submitItem.fromPackingNumber = info.packingNumber
        submitItem.fromBatch = info.batch
        submitItem.fromContainerNumber = detail.containerNumber

        submitItem.fromLocationCode = detail.locationCode
        submitItem.toLocationCode = detail.toLocationCode

        // detail.toInventoryStatus = detail.inventoryStatus
        // detail.toLocationCode = detail.toLocationCode
        submitItem.qty = detail.handleQty
        submitItem.package = ''
        submitItem.recordList = [
          {
            toInventoryStatus: detail.inventoryStatus,
            fromPackingNumber: info.packingNumber,
            fromParentPackingNumber: detail.parentNumber,
            fromBatch: info.batch,
            toPackingNumber: info.packingNumber,
            toBatch: info.batch,
            fromLocationCode: detail.locationCode,
            toLocationCode: detail.toLocationCode,
            handleQty: detail.handleQty,
            fromPackUnit: detail.packUnit,
            toPackUnit: detail.packUnit,
            fromPackQty: detail.packQty,
            toPackQty: detail.packQty
          }
        ]
        subList1.push(submitItem)
      }
    })
  })
  if (subList1.length > 0) {
    dataContent.value.toWarehouseCode = subList1[0].toWarehouseCode
  }
  dataContent.value.subList = subList1
  dataContent.value.creator = creator
  dataContent.value.fromWarehouseCode = fromWarehouseCode.value
  return dataContent.value
}
const showMessage = (message) => {
  comMessageRef.value.showMessage(message, (res) => {
    if (res) {
    }
  })
}
const showErrorMessage = (message) => {
  comMessageRef.value.showErrorMessage(message, (res) => {
    if (res) {
    }
  })
}
const showScanMessage = (message) => {
  comMessageRef.value.showScanMessage(message)
}

const afterCloseMessage = () => {
  scanPopupGetFocus()
}
const closeScanMessage = () => {
  scanPopupGetFocus()
}

const getLocation = (location, code) => {
  getFromLocationCode(location, code)
}

const getFromLocationCode = (location, code) => {
  fromLocationCode.value = code
  openScanPopup()
}
const getToLocationCode = (location, code) => {
  if (fromLocationCode.value == code) {
    uni.showToast({
      title: `来源库位[${fromLocationCode.value}]不能与目标库位[${code}]一致`,
      duration: 2000
    })
    return
  }
  toLocationCode.value = code
}

const showCommitSuccessMessage = (hint) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    clear()
  })
}
const clear = () => {
  fromLocationCode.value = ''
  fromWarehouseCode.value = ''
  detailSource.value = []
  toLocationCode.value = ''
}
</script>

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