<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-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" :isShowLocation="true" @removeItem="removeItem(index, item)" @updateData="updateData" @removePack="removePack"> </record-com-detail-card>
            </view>
            <view class="split_line"></view>
          </view>
        </scroll-view>
      </view>

      <view class="uni-flex uni-row u-col-center" style="width: 100%">
        <view class="" style="text-align: center; font-size: 32rpx; font-weight: 700; margin-left: 10rpx"> 客户 : </view>
        <uni-data-picker v-if="detailSource.length > 0" style="padding: 20rpx; background-color: #fff" class="uni-data-picker" placeholder="请选择客户" popup-title="选择客户" :localdata="customerList" @change="reasonChange"> </uni-data-picker>
      </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="true" :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" headerType="HMQ"></win-scan-pack-and-location>
    <com-message ref="comMessageRef" />
    <win-scan-location ref="scanLocationCodeRef" 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 { getBasicCustomerList, deliverRecordSubmit } from '@/api/request2.js'
import { goHome, getPackingNumberAndBatchByList, deepCopyData } from '@/common/basic.js'

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

import { getPrecisionStrategyList } from '@/common/balance.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 recordComDetailCard from '@/mycomponents/record/recordComDetailCard.vue'
import { useCountStore } from '@/store'
// 获取自定义的store
const store = useCountStore()
const { proxy } = getCurrentInstance()
const id = ref('')
const subList = ref([]) // 接口返回的任务subList
const detailSource = ref([]) // 绑定在页面上的数据源
const fromLocationCode = ref('')
const toLocationCode = ref('')
const fromLocationAreaTypeList = ref([])
const toLocationAreaTypeList = ref([])
const businessType = ref({})
const customerList = ref([])
const customerText = ref('')
const customerCode = ref('')
const dataContent = ref({})
const managementList = ref([])
const deliverType = ref('') // 发货类型：寄售库CUST，三方库THIRD_PARTY
const scanPopup = ref()
const scanLocationCodeRef = ref()
const comMessageRef = ref()
onLoad((option) => {
  deliverType.value = option.deliverType
  const typeCode = 'Deliver'
  getBusinessType(typeCode, (res) => {
    if (res.success) {
      businessType.value = res.businessType
      fromLocationAreaTypeList.value = res.fromLocationAreaTypeList
      toLocationAreaTypeList.value = res.toLocationAreaTypeList
      showFromLocationPopup()
    } else {
      showErrorMessage(res.message)
    }
  })
  getBasicCustomerList()
    .then((res) => {
      if (res.data.length > 0) {
        const list = res.data
        list.forEach((item) => {
          item.text = item.name
          item.value = item.code
        })
        customerList.value = list
      }
    })
    .catch((error) => {
      showErrorMessage(error)
    })
})
onNavigationBarButtonTap((e) => {
  if (e.index === 0) {
    goHome()
  }
})
const getScanResult = (result) => {
  const { balance } = result
  const { label } = result
  const pack = result.package
  const labelQty = result.label.qty
  const balanceQty = result.balance.qty
  const item = detailSource.value.find((res) => {
    if (res.itemCode == balance.itemCode) {
      return res
    }
  })
  if (item == undefined) {
    const itemp = createItemInfo(balance, pack)
    const newDetail = createDetailInfo(balance, pack) //
    itemp.subList.push(newDetail)
    detailSource.value.push(itemp)
  } 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)
      item.subList.push(newDetail)
    } else if (detail.scaned == true) {
      showErrorMessage(`箱码[${balance.packingNumber}批次[${balance.batch}]已经在列表中`)
    }
  }
  handleCalcHandleQty()
}

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

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 (fromLocationCode.value == '') {
    showFromLocationPopup()
    return
  }
  scanPopup.value.openScanPopupForType(fromLocationCode.value, businessType.value)
}

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

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

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

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

const commit = () => {
  if (customerText.value == '') {
    showMessage('请先选择客户')
    return
  }
  if (toLocationCode.value == '') {
    showMessage('请先选择目标库位')
    return
  }
  if (detailSource.value.length > 0 && detailSource.value[0].subList.length > 0) {
    // 查询管理模式

    proxy.$modal.loading('提交中....')
    managementList.value = []
    const precisionStrategParams = setPrecisionStrategParams()

    getPrecisionStrategyList(precisionStrategParams, (res) => {
      if (res.success) {
        managementList.value = res.list
        const params = setParams()
        deliverRecordSubmit(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)
      }
    })
  } else {
    showErrorMessage('没有要提交的数据,请先扫描')
  }
}
const setPrecisionStrategParams = () => {
  const itemList = []
  detailSource.value.forEach((item) => {
    item.subList.forEach((detail) => {
      if (detail.scaned) {
        detail.toLocationCode = toLocationCode.value
        const filterResult = itemList.filter((res) => {
          if (res.itemCode == item.itemCode && detail.toLocationCode == res.locationCode) {
            return res
          }
        })
        // 去掉重复元素
        if (filterResult.length == 0) {
          const result = {
            itemCode: item.itemCode,
            locationCode: detail.toLocationCode
          }
          itemList.push(result)
        }
      }
    })
  })
  return itemList
}

const setParams = () => {
  const subList = []
  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.itemCode = detail.itemCode
        submitItem.itemName = detail.package.itemName
        submitItem.itemDesc1 = detail.package.itemDesc1
        submitItem.itemDesc2 = detail.package.itemDesc2

        submitItem.inventoryStatus = detail.inventoryStatus

        submitItem.fromPackingNumber = info.packingNumber
        submitItem.toPackingNumber = info.packingNumber

        submitItem.fromContainerNumber = detail.containerNumber
        submitItem.toContainerNumber = detail.containerNumber

        submitItem.fromBatch = info.batch
        submitItem.toBatch = info.batch

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

        submitItem.qty = detail.handleQty
        submitItem.package = ''

        subList.push(submitItem)
      }
    })
  })
  dataContent.value.subList = subList
  dataContent.value.creator = creator
  dataContent.value.customerCode = customerCode.value
  dataContent.value.fromWarehouseCode = detailSource.value[0].subList[0].warehouseCode
  dataContent.value.toWarehouseCode = toWarehouseCode.value
  dataContent.value.deliverType = deliverType.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) => {
  toLocationCode.value = code
}
const showCommitSuccessMessage = (hint) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    if (res) {
      clearData()
    }
  })
}
const clearData = () => {
  fromLocationCode.value = ''
  subList.value = []
  detailSource.value = []
  toLocationCode.value = ''
  dataContent.value = {}
  toWarehouseCode.value = ''
}
const updateData = () => {
  handleCalcHandleQty()
  for (let i = 0; i < detailSource.value.length; i++) {
    const item = detailSource.value[i]
    if (item.qty == 0) {
      detailSource.value.splice(i, 1)
    }
  }
}
const reasonChange = (e) => {
  if (e.detail.value.length == 0) {
    customerCode.value = ''
    customerText.value = ''
  } else {
    customerCode.value = e.detail.value[0].value
    customerText.value = e.detail.value[0].text
  }
}
</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>
