<template>
  <view class="page-wraper">
    <view class="">
      <com-blank-view @goScan="getBusinessType" v-if="detailSource.length == 0"></com-blank-view>
    </view>
    <print ref="printService" @printCode="printCode" @templateCode="templateCode"></print>
    <view class="page-wraper" v-if="detailSource.length > 0">
      <view class="cen_card" style="background-color: #fff; margin: 10px">
        <view class="cell_box uni-flex uni-row">
          <view class="cell_info">
            <view class="text_lightblue">库位</view>
            <view>{{ fromLocationCode }}</view>
          </view>
          <view class="cell_info">
            <view class="text_lightblue">包装规格</view>
            <view>{{ getPackUnitName1(fromPack.packUnit) }}</view>
          </view>
          <view class="cell_info">
            <view class="text_lightblue">包装数量</view>
            <view>{{ fromPack.packQty }}{{ getUomInfo1(fromPack.uom) }}</view>
          </view>
        </view>
      </view>
      <view class="split_line"></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" @removeItem="removeItem(index, item)" @updateData="updateData" @removePack="removePack" :isShowFromLocation="false" :isShowToLocation="false"> </record-com-detail-card>
            </view>
            <view class="split_line"></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="">
            <view class="uni-flex uni-row">
              <text>目标包装规格:</text>
              <view class="uni-flex u-col-center uni-row" @click="showPackage">
                <view class="" style="margin-left: 5rpx; width: 100%">
                  {{ toPackUnitShow }}
                </view>
                <u-select v-model="show" mode="single-column" :list="packageList" @confirm="confirmSelect"> </u-select>
              </view>
            </view>
          </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>
    <winComScanBalance ref="scanPopup" @getBalance="getScanResult" bussinessCode="OverPackage"> </winComScanBalance>
    <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 { overPackageRecordSubmit, getPackUnitByItemCode, getBalanceByParams } from '@/api/request2.js'
import { goHome, getCurrDateTime } from '@/common/basic.js'

import { getInventoryStatusDesc, getLocationAreaTypeName, getLocationAreaTypeInfo, getListLocationAreaTypeDesc, getDirectoryItemArray, getPackUnitName, getUomInfo } from '@/common/directory.js'

import { getBusinessType, createItemInfo, createDetailInfo, calcHandleQty } from '@/common/record.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 recommendBalance from '@/mycomponents/balance/recommendBalance.vue'
import packageTarget from '@/mycomponents/package/packageTarget.vue'
import recordComDetailCard from '@/mycomponents/record/recordComDetailCard.vue'
import packUnit from '@/mycomponents/qty/packUnit.vue'
import winComScanBalance from '@/mycomponents/scan/winComScanBalance.vue'
import print from '@/mycomponents/print/print.vue'

import { useCountStore } from '@/store'
// 获取自定义的store
const store = useCountStore()
const { proxy } = getCurrentInstance()

const id = ref('')
const scanCount = ref(0)
const detailSource = ref([])
const fromLocationCode = ref('')
const isShowLocation = ref(false)
const fromLocationAreaTypeList = ref([])
const fromInventoryStatuses = ref([])
const inInventoryStatus = ref('')
const outInventoryStatus = ref('')
const businessType = ref({})
const dataContent = ref({})
const fromPackUnit = ref('')
const fromPack = ref({})
const packageList = ref([])
const show = ref(false)
const toPackUnitShow = ref('请选择')
const toPackQty = ref('')
const itemCode = ref('')
const resultData = ref({})
const scanPopup = ref()
const scanLocationCode = ref()
const toPackUnit = ref()
const comMessageRef = ref()
const printService = ref()
onLoad(() => {
  getBusinessType()
})
onLoad((option) => {
  uni.setNavigationBarTitle({
    title: option.title
  })
})
onNavigationBarButtonTap((e) => {
  if (e.index === 0) {
    goHome()
  }
})
const getBusinessType1 = () => {
  const typeCode = 'OverPackage'
  getBusinessType(typeCode, (res) => {
    if (res.success) {
      businessType.value = res.businessType
      fromInventoryStatuses.value = getDirectoryItemArray(res.fromInventoryStatuses)
      fromLocationAreaTypeList.value = res.fromLocationAreaTypeList
      openScanPopup()
    } else {
      showErrorMessage(res.message)
    }
  })
}
const getUomInfo1 = (uom) => {
  const item = getUomInfo(uom)
  if (item == '') {
    return uom
  }
  return item.label
}

const showPackage = () => {
  getPackUnitByItemCode(itemCode.value)
    .then((res) => {
      if (res.data != null && res.data.list.length > 0) {
        res.data.list.forEach((item) => {
          // item.value = item.packQty;
          item.value = item.packUnit
          item.label = `${getPackUnitName(item.packUnit)}(${item.packQty}${getUomInfo1(item.uom)})`
          item.data = 'a'
        })
        packageList.value = res.data.list
        show.value = true
      } else {
        showErrorMessage('未查找到包装规格')
      }
    })
    .catch((error) => {
      showErrorMessage(`未查找到包装规格${error}`)
    })
}
const confirmSelect = (e) => {
  if (fromPackUnit.value == e[0].label) {
    showErrorMessage(`来源包装规格【${fromPackUnit.value}】与目标包装规格【${e[0].label}】不能相等`)
    return
  }
  // var toPackUnit = e[0].label.split("(")[0]
  // this.toPackUnit = toPackUnit
  // this.toPackQty = e[0].value
  toPackUnit.value = e[0].value
  const pack = packageList.value.filter((r) => r.packUnit == toPackUnit.value)[0]
  toPackQty.value = pack.packQty
  toPackUnitShow.value = e[0].label
}
// 修改库位
const handleConfirm = (fromLocationCode) => {
  scanLocationCode.value.openScanPopupSimulate(fromLocationCode)
}
const getScanResult = (result) => {
  setData(result)

  setTimeout((res) => {
    printService.value.setDefaultData()
  })
}

const setData = (result) => {
  const { balance } = result
  const { label } = result
  const pack = result.package
  fromPackUnit.value = pack.packUnit
  fromPack.value = pack
  if (fromLocationCode.value && fromLocationCode.value != balance.locationCode) {
    showErrorMessage(`箱码[${balance.packingNumber}批次[${balance.batch}]在库位[${fromLocationCode.value}]没有库存余额`)
    return
  }

  const item = detailSource.value.find((res) => {
    if (res.itemCode == balance.itemCode) {
      return res
    }
  })
  if (item == undefined) {
    if (itemCode.value != '' && itemCode.value != balance.itemCode) {
      showErrorMessage(`请扫描物料为【${itemCode.value}】的箱码`)
      return
    }
    const itemp = createItemInfo(balance, pack)
    const newDetail = createDetailInfo(balance, pack) //
    if (balance.lableQty) {
      newDetail.handleQty = balance.lableQty
    }
    newDetail.parentNumber = pack.parentNumber
    newDetail.packingNumber = pack.number
    itemp.subList.push(newDetail)
    detailSource.value.push(itemp)
    itemCode.value = balance.itemCode
    fromLocationCode.value = balance.locationCode
    scanPopupGetFocus()
  } else {
    const detail = item.subList.find((r) => {
      if (r.packingNumber == pack.number && r.batch == balance.batch && r.locationCode == balance.locationCode && r.inventoryStatus == balance.inventoryStatus) {
        return r
      }
    })
    console.log(detail)
    if (detail == undefined) {
      const newDetail = createDetailInfo(balance, pack)
      if (balance.lableQty) {
        newDetail.handleQty = balance.lableQty
      }
      newDetail.parentNumber = pack.parentNumber
      newDetail.packingNumber = pack.number
      item.subList.push(newDetail)
      scanPopupGetFocus()
    } else if (detail.scaned == true) {
      showErrorMessage(`箱码[${detail.packingNumber}批次[${balance.batch}]已经在列表中`)
    }
  }
  calcHandleQty1()
}
const calcHandleQty1 = () => {
  console.log(detailSource.value)
  // calcHandleQty(detailSource.value)
}

const showErrorMessage = (message) => {
  comMessageRef.value.showErrorMessage(message, (res) => {
    if (res) {
      scanPopupGetFocus()
    }
  })
}
const removeItem = (index, item) => {
  detailSource.value.splice(index, 1)
}

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)
    }
  }
  updateData()
}

const openScanPopup = () => {
  if (businessType.value) {
    scanPopup.value.openScanPopup(businessType.value)
  } else {
    getBusinessType()
  }
}

const closeScanPopup = () => {
  if (scanPopup.value) {
    scanPopup.value.closeScanPopup()
  }
}
const scanPopupGetFocus = () => {
  if (scanPopup.value) {
    scanPopup.value.getfocus()
  }
}
const commit = () => {
  if (detailSource.value.length > 0 && detailSource.value[0].subList.length > 0) {
    if (toPackUnit.value || toPackUnit.value == '包装规格') {
      showErrorMessage('请选择目标包装规格')
      return
    }
    checkSubmit()
  } else {
    showErrorMessage('没有要扫描的数据')
  }
}

const checkSubmit = () => {
  // submitJob()
  let tempHandleQty = 0
  detailSource.value.forEach((res) => {
    tempHandleQty += res.handleQty
  })
  // 包装提示
  if (tempHandleQty % toPackQty.value > 0) {
    comMessageRef.value.showQuestionMessage(`扫描数量【${tempHandleQty}】,将有1个非整包,是否提交?`, (res) => {
      if (res) {
        submitJob()
      }
    })
  } else {
    submitJob()
  }
}

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

  const params = setParams()
  console.log(`提交${JSON.stringify(params)}`)
  overPackageRecordSubmit(params)
    .then((res) => {
      uni.hideLoading()
      if (res.data) {
        const list = []
        const item = res.data
        // res.data.forEach((item) => {
        list.push({
          itemCode: item.itemCode, // 物品代码
          itemName: item.itemName, // 物品名称
          packName: item.packName, // 包装名称
          packageCode: item.toPackingNumber, // 包装号
          batch: item.toBatch, // 批次
          parentNumber: item.parentNumber, // 父包装号
          itemType: item.itemType, // 物料类型
          asnNumber: item.asnNumber, // ASN
          supplierCode: item.supplierCode, // 供应商
          qty: item.qty, // 数量
          printTimes: getCurrDateTime(), // 打印时间
          productionLineCode: item.productionLineCode, // 生产线
          barcodeString: item.barcodeString, // 标签信息
          barcodeBase64: ''
        })
        // })
        showCommitSuccessMessage(`提交成功<br>生成翻包记录<br>${list}`)
      } 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) {
        const subItem = deepCopyData(detail)
        subItem.itemCode = detail.itemCode
        subItem.itemName = detail.package.itemName
        subItem.itemDesc1 = detail.package.itemDesc1
        subItem.itemDesc2 = detail.package.itemDesc2

        subItem.fromInventoryStatus = detail.inventoryStatus
        subItem.fromQty = detail.handleQty
        subItem.fromParentPackingNumber = detail.parentNumber
        subItem.fromPackingNumber = detail.packingNumber
        subItem.fromBatch = detail.batch
        subItem.fromLocationCode = detail.locationCode
        subItem.fromPackUnit = detail.packUnit
        subItem.fromPackQty = detail.packQty

        subItem.toPackQty = toPackQty.value
        subItem.toPackUnit = toPackUnit.value
        subItem.package = ''
        subList.push(subItem)
      }
    })
  })
  dataContent.value.subList = subList
  dataContent.value.creator = creator
  return dataContent.value
}

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

const getPackUnitName1 = (packUnit) => {
  return getPackUnitName(packUnit)
}

const showScanMessage = (message) => {
  comMessageRef.value.showScanMessage(message)
}

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

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

const showCommitSuccessMessage = (hint, pointData) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    if (res) {
      detailSource.value = []
      fromLocationCode.value = ''
      dataContent.value = {}
      itemCode.value = ''
      toPackUnitShow.value = '请选择'
      toPackQty.value = ''
      if (pointData.length > 0) {
        uni.navigateTo({
          url: `/pages/point/index?points=${JSON.stringify(pointData)}`
        })
      }
    }
  })
}

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

<style scoped lang="scss">
page {
  width: 100%;
  height: 100%;
  background-color: #fff;
}

.page-wraper {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

.page-main {
  flex: 1;
  position: relative;
}

.page-main-scroll {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.page-main-list {
  /*  height: 80rpx;
	    line-height: 80rpx; */
  text-align: center;
  background: #e0e0e0;
}
</style>
