<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>
      <!-- <view class="header_item">
				申请单号 : {{jobContent.requestNumber}}
			</view> -->
    </view>
    <view class="page-main">
      <scroll-view scroll-y="true" class="page-main-scroll">
        <view v-for="(toLocation, index) in detailSource" :key="index">
          <view class="cen_card" style="margin: 20rpx; width: auto" v-if="subList.length > 0">
            <view class="cell_box uni-flex uni-row">
              <view class="cell_info">
                <view class="text_lightblue">翻包前包装规格</view>
                <view style="font-size: 26rpx">
                  <text style="font-weight: bold; font-size: 30rpx">{{ subList[0].fromPackQty }} ({{ handleGetUomInfo(subList[0].uom) }})/{{ handleGetPackUnitName(subList[0].fromPackUnit) }}</text>
                </view>
              </view>
              <view class="cell_info">
                <view class="text_lightblue">翻包后包装规格</view>
                <view style="font-size: 26rpx">
                  <text style="font-weight: bold; font-size: 30rpx">{{ subList[0].toPackQty }}({{ handleGetUomInfo(subList[0].uom) }})/{{ handleGetPackUnitName(subList[0].toPackUnit) }}</text>
                </view>
              </view>
            </view>
          </view>

          <comOverPackJobDetailCard ref="comOverPackJobDetailCardRef" :dataContent="toLocation" @updateData="updateData"> </comOverPackJobDetailCard>
        </view>
      </scroll-view>
    </view>

    <view class="page-footer">
      <view class="uni-flex u-col-center space-between padding_20" style="background-color: ghostwhite; width: 100%">
        <button class="btn_single_commit" style="flex: 1" hover-class="btn_commit_after" @click="submit()">提交</button>
      </view>
    </view>

    <win-scan-button @goScan="openScanDetailPopup"></win-scan-button>
    <comScanPackagePack ref="comScanPackagePackRef" @closeScan="closeScan" @updateData="updateData"> </comScanPackagePack>
    <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 { takeOverPageJob, cancleTakeOverPageJob, getOverPageJobDetail, overPageSubmit, getPackageLabel } from '@/api/request2.js'

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

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

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

import { calc } from '@/common/calc.js'
import { getUomInfo, getPackUnitName } from '@/common/directory.js'

import jobDetailPopup from '@/mycomponents/job/jobDetailPopup.vue'
import comOverPackJobDetailCard from '@/pages/package/coms/comOverPackJobDetailCard.vue'
import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import comScanPackagePack from '@/pages/package/coms/comScanPackagePack.vue'
import jobTop from '@/mycomponents/job/jobTop.vue'
import workStation from '@/mycomponents/workStation/workStation.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 jobStatus = ref('')
const scanPopup = ref()
const comScanPackagePackRef = ref()
const comMessageRef = ref()
const comOverPackJobDetailCardRef = ref()
const managementList = ref([])
onLoad((option) => {
  id.value = option.id
  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') {
      // 取消承接任务
      cancleTakeOverPageJob(id.value)
        .then((res) => {
          uni.navigateBack()
        })
        .catch((error) => {
          uni.navigateBack()
        })
    } else {
      uni.navigateBack()
    }
    return true
  }
})
const resizeCollapse = () => {
  nextTick((r) => {
    comOverPackJobDetailCardRef.value.forEach((r) => {
      r.resizeCollapse()
    })
  })
}
const receive = (callback) => {
  if (id.value != null) {
    takeOverPageJob(id.value)
      .then((res) => {
        callback()
      })
      .catch((error) => {
        showErrorMessage(error)
      })
  }
}
const getDetail = () => {
  proxy.$modal.loading('加载中....')
  getOverPageJobDetail(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 = getDataSource(detailSource.value, subList.value)

        setTimeout((r) => {
          resizeCollapse()
        }, 100)

        uni.hideLoading()
      } else {
        showMessage('列表数据为0')
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}
const closeScan = () => {
  resizeCollapse()
}
const submit = () => {
  // 目前任务只到一个库位
  const itemCodes = []
  const locationCode = detailSource.value[0].toLocationCode
  detailSource.value.forEach((toLocation) => {
    toLocation.Items.forEach((item) => {
      itemCodes.push(item.itemCode)
    })
  })
  checkSubmit()
  // // 使用在途库，不查询管理模式
  // if (jobContent.value.useOnTheWayLocation == 'TRUE') {
  //   checkSubmit()
  // } else {
  //   // 获取管理模式，封装参数
  //   getManagementPrecisions(itemCodes, locationCode, (res) => {
  //     if (res.success) {
  //       managementList.value = res.list
  //       checkSubmit()
  //     } else {
  //       uni.hideLoading()
  //       showErrorMessage(res.message)
  //     }
  //   })
  // }
}
const checkSubmit = () => {
  const tempHandleQty = detailSource.value[0].Items[0].Locations[0].Batchs[0].handleQty
  const tempQty = detailSource.value[0].Items[0].Locations[0].Batchs[0].qty
  const { toPackQty } = detailSource.value[0].Items[0].Locations[0].Batchs[0]
  if (tempHandleQty > tempQty) {
    // 大于需求数量
    showCommitMessage(`实际数量【${tempHandleQty}】大于需求数量` + `【${tempQty}】, 是否提交?`, tempHandleQty, toPackQty)
  } else if (tempHandleQty < tempQty) {
    showCommitMessage(`实际数量【${tempHandleQty}】小于需求数量` + `【${tempQty}】, 是否提交?`, tempHandleQty, toPackQty)
  } else {
    packageHint(tempHandleQty, toPackQty)
  }
}
const packageHint = (tempHandleQty, toPackQty) => {
  // 包装提示
  if (tempHandleQty % toPackQty > 0) {
    comMessageRef.value.showQuestionMessage(`扫描数量【${tempHandleQty}】,将有1个非整包,是否提交?`, (res) => {
      if (res) {
        submitJob()
      }
    })
  } else {
    submitJob()
  }
}
const submitJob = () => {
  proxy.$modal.loading('提交中....')
  const params = setParams()

  overPageSubmit(params)
    .then((res) => {
      uni.hideLoading()
      if (res.data) {
        const list = []
        res.data.forEach((item) => {
          list.push({
            itemCode: item.itemCode, // 物品代码
            itemName: item.itemName, // 物品名称
            packName: item.packName, // 包装名称
            packageCode: item.number, // 包装号
            batch: item.batch, // 批次
            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 createTime = getCurrDateTime()
  const creator = store.id
  detailSource.value.forEach((toLocationCode) => {
    toLocationCode.Items.forEach((item) => {
      item.Locations.forEach((fromLocation) => {
        fromLocation.Batchs.forEach((batch) => {
          const subItem = batch.detail
          if (subItem != undefined) {
            subItem.recordList = []
            if (batch.Records.length > 0) {
              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 = subItem.toLocationCode
                record.supplierCode = r.supplierCode

                const single_price = r.balance.singlePrice == null ? 0 : r.balance.singlePrice

                record.singlePrice = single_price
                record.amount = single_price * r.qty

                // 使用在途库不改变管理模式
                if (jobContent.value.useOnTheWayLocation == 'TRUE') {
                  record.toPackingNumber = r.packingNumber
                  record.toBatch = r.batch
                } else {
                  const info = getPackingNumberAndBatch(managementList.value, r.itemCode, r.packingNumber, r.batch)
                  record.toPackingNumber = info.packingNumber
                  record.toBatch = info.batch
                }
                subItem.recordList.push(record)
              })
              subList.push(subItem)
            }
          }
        })
      })
    })
  })

  jobContent.value.subList = subList
  jobContent.value.createTime = createTime
  jobContent.value.creator = creator
  return jobContent.value
}
const cancel = () => {
  comMessageRef.value.showQuestionMessage('是否要清空已扫描的物料和目标库位信息?', (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)
      }
    })
  }
  resizeCollapse()
  item.handleQty = itemHandleQty
}
const scanPopupGetFocus = () => {
  if (!scanPopup.value) {
    scanPopup.value.getfocus()
  }
}
const showMessage = (message) => {
  comMessageRef.value.showMessage(message, (res) => {
    afterCloseMessage()
  })
}
const showErrorMessage = (message) => {
  comMessageRef.value.showErrorMessage(message, (res) => {
    if (res) {
      afterCloseMessage()
    }
  })
}
const showCommitMessage = (message, tempHandleQty, toPackQty) => {
  comMessageRef.value.showQuestionMessage(message, (res) => {
    if (res) {
      packageHint(tempHandleQty, toPackQty)
    }
  })
}
const showScanMessage = (message) => {
  comMessageRef.value.showScanMessage(message)
}
const showCommitSuccess = () => {
  comMessageRef.value.showCommitSuccess()
}

const showCommitSuccessMessage = (hint, pointData) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    if (pointData.length > 0) {
      uni.redirectTo({
        url: `/pages/point/index?points=${JSON.stringify(pointData)}`
      })
    } else {
      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);
  comScanPackagePackRef.value.openScanPopup(detailSource.value, jobContent.value)
}
const closeScanPopup = () => {
  updateCommitBtn()
}
const handleGetUomInfo = (uom) => {
  const item = getUomInfo(uom)
  if (item == '') {
    return uom
  }
  return item.label
}
const handleGetPackUnitName = (packUnit) => {
  const unit = getPackUnitName(packUnit)
  return unit
}
</script>

<style scoped lang="scss">
.uni-numbox__value {
  width: 40px;
}

button[disabled] {
  background-color: #3c9cff;
  color: #fff;
  opacity: 0.7;
}

// /deep/ .input-value {
// 	font-size: 16px;
// }

// /deep/ .uni-collapse-item__title-text {
// 	font-size: 16px;
// }

// /deep/ .uni-collapse-item--border {
// 	border-bottom-width: 0px;
// 	border-bottom-color: #ebeef5;
// }

// /deep/ .uni-collapse-item--border {
// 	border-bottom-width: 1px;
// 	border-bottom-color: #ebeef5;
// }
</style>
