<template>
  <view class="page-wraper">
    <view class="page-header">
      <view class="header-view">
        <view class="header_job_top">
          <job-top :dataContent="jobContent"></job-top>
        </view>
        <view class="header_item"> 申请单号 : {{ jobContent.requestNumber }} </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="">
            <!--<com-receipt-detail-card :dataContent="item" :index="index" :settingParam="jobContent"
                                     @remove="updateData" @updateData="updateData"
                                     :locationAreaTypeList='toLocationAreaTypeList'>
            </com-receipt-detail-card>-->
            <comRecommendDetailCard :dataContent="item" :index="index" :settingParam="jobContent"
                                    @remove="updateData" @updateData="updateData" @openDetail="openDetail" :isShowFromLocation='false'>
            </comRecommendDetailCard>
          </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="">
          <locationCompare ref="comScanLocation" title="目标库位" :recommendLocationCode="jobToLocationCode" :locationCode="toLocationCode" @getLocation="scanLocationCode" :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>
    <win-scan-pack ref="scanPopup" @getResult="getScanResult" headerType="HPQ,HMQ"></win-scan-pack>

    <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 { getUnPlannedReceiptJobDetail, cancleTakeUnPlannedReceiptJob, takeUnPlannedReceiptJob, unPlannedReceiptJobSubmit } from '@/api/request2.js'
import { goHome, navigateBack, getPackingNumberAndBatch, getDirectoryItemArray } from '@/common/basic.js'
import { calc } from '@/common/calc.js';
import { getDataSource, createRecordInfo, calcHandleQty, getScanCount } from '@/common/detail.js'

import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import winScanPack from '@/mycomponents/scan/winScanPack.vue'
import LocationCompare from '@/mycomponents/location/locationCompare.vue'
import comReceiptDetailCard from '@/pages/unPlanned/coms/comReceiptDetailCard.vue'
import ComRecommendDetailCard from "@/mycomponents/detail/comRecommendDetailCard.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 toLocationAreaTypeList = ref([])
const toLocationCode = ref('')
const toLocationInfo = ref({})
const businessTypeInfo = ref({})
const managementList = ref([])
const managementType = ref('')
const jobStatus = ref('')
const jobToLocationCode = ref('')
const scanPopup = ref()
const comScanLocation = ref()
const comMessageRef = ref()
onLoad((option) => {
  uni.setNavigationBarTitle({
    title: `${option.title}详情`
  })
  id.value = option.id
  if (id.value != undefined) {
    // 新建的任务自动接收
    if (option.status == '1') {
      receive((callback) => {
        getDetail()
      })
    } else {
      getDetail()
    }
  }
})
// 返回首页
onNavigationBarButtonTap((e) => {
  if (e.index === 0) {
    goHome()
  }
})

// 返回首页
onNavigationBarButtonTap((e) => {
  if (e.index === 0) {
    goHome()
  }
})
// 拦截返回按钮事件
onBackPress((e) => {
  // 已经接收但是没提交任务
  if (e.from == 'backbutton') {
    if (jobStatus.value == '2') {
      // 取消承接任务
      cancleTakeUnPlannedReceiptJob(id.value)
        .then((res) => {
          uni.navigateBack()
        })
        .catch((error) => {
          uni.navigateBack()
        })
    } else {
      uni.navigateBack()
    }
    return true
  }
})

// 接收
const receive = (callback) => {
  if (id.value != null) {
    takeUnPlannedReceiptJob(id.value)
      .then((res) => {
        callback()
      })
      .catch((error) => {
        showErrorMessage(error)
      })
  }
}

const getDetail = () => {
  proxy.$modal.loading('加载中....')
  getUnPlannedReceiptJobDetail(id.value)
    .then(async (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
        subList.value.forEach(item=>{
          item.isRecommend = true
        })
        detailSource.value = getDataSource(subList.value)
        jobToLocationCode.value = subList.value[0].toLocationCode
        toLocationAreaTypeList.value = await getDirectoryItemArray(jobContent.value.toAreaTypes)
        //获取管理模式，封装参数
        let itemCodes = []
        detailSource.value.forEach(item => {
          itemCodes.push(item.itemCode)
          item.scaned = false
        })
        getManagementPrecisions(itemCodes, jobToLocationCode.value, res => {
          if (res.success) {
            managementList.value = res.list;
            managementType.value = managementList.value &&
                managementList.value[0] &&
                managementList.value[0].ManagementPrecision
          }
        })
      } else {
        showErrorMessage('列表数据为0')
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}

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

// 继续扫描
const continueScan = () => {
  scanCount.value = getScanCount(subList.value)
  if (scanCount.value == subList.value.length) {
    closeScanPopup()
  } else {
    scanPopupGetFocus()
  }
}

const updateData = () => {
  calcHandleQty(detailSource.value)
}
const getScanResult = (result)=> {
  if(import.meta.env.VITE_MANAGE_MODEL == 'BY_BATCH'){
    setDataBatch(result)
  }else{
    setData(result)
  }
}
const setDataBatch = (result)=>{
  try {
    const packingNumber = result.label.packingNumber;
    const batch = result.label.batch;
    const qty = result.label.qty;
    const itemCode = result.label.itemCode;
    const locationCode = result.package.toLocationCode;
    const detail = detailSource.value.find(r => r.itemCode == itemCode);
    if (detail == undefined) {
      showErrorMessage("物料号【" + itemCode + "】不在列表中")
    } else {
      const itemDetail = detail.subList.find(r => {
        return r.batch == batch &&
            r.fromLocationCode == result.fromLocationCode&&
            r.isRecommend==false
      })
      const itemDetail1 = detail.subList.find(r => {
        return r.batch == batch &&
            r.fromLocationCode == result.fromLocationCode&&
            r.isRecommend==true
      })
      if (itemDetail == undefined) {
        let newAdd = {
          ...itemDetail1,
          itemCode:itemCode,
          packingNumber:packingNumber,
          batch:batch,
          handleQty:Number(result.label.qty),
          qty:detail.qty,
          toLocationCode:locationCode,
          // inventoryStatus:inventoryStatus,
          // toInventoryStatus:inventoryStatus,
          // balance:result.balance,
          isRecommend:false,
          isNewAdd:"newAdd"
        }
        // newAdd.balance.balanceQty = Number(result.balance.qty);
        // newAdd.balance.packQty = Number(result.package.packQty)
        // newAdd.balance.packUnit = result.package.packUnit
        newAdd.scaned = true;
        detail.subList.push(newAdd)
      } else {
        if (itemDetail.scaned) {
          // this.showErrorMessage("箱码【" + packingNumber + "】,批次【" + batch + "】" + "已经扫描")
          itemDetail.handleQty = calc.add(itemDetail.handleQty ,Number(result.label.qty));
        } else {
          itemDetail.scaned = true;
          itemDetail.handleQty = Number(result.label.qty);
          itemDetail.toLocationCode = toLocationCode.value ? toLocationCode.value : itemDetail
              .toLocationCode;
          itemDetail.packQty = result.package.packQty
          itemDetail.labelQty = Number(result.label.qty);
          continueScan()
        }
      }
      calcHandleQty(detailSource.value);
    }

  } catch (e) {
    showErrorMessage(e.message)
  }
}
const setData = (result) => {
  try {
    const { packingNumber } = result.label
    const { batch } = result.label
    const { qty } = result.label
    const { itemCode } = result.label
    const detail = detailSource.value.find((r) => r.itemCode == itemCode)
    if (detail == undefined) {
      showErrorMessage(`物料号【${itemCode}】不在列表中`)
    } else {
      const itemDetail = detail.subList.find((r) => r.packingNumber == packingNumber && r.batch == batch)
      if (itemDetail == undefined) {
        showErrorMessage(`箱码【${packingNumber}】,批次【${batch}】` + '不在列表中')
      } else if (itemDetail.scaned) {
        showErrorMessage(`箱码【${packingNumber}】,批次【${batch}】` + '已经扫描')
      } else {
        itemDetail.scaned = true
        itemDetail.handleQty = Number(result.label.qty)
        itemDetail.toLocationCode = toLocationCode.value ? toLocationCode.value : itemDetail.toLocationCode
        itemDetail.packQty = result.package.packQty
        itemDetail.labelQty = Number(result.label.qty)
        calcHandleQty(detailSource.value)
        continueScan()
      }
    }
  } catch (e) {
    showErrorMessage(e.message)
  }
}

const commit = () => {
  if(managementType.value == 'BY_BATCH' || managementType.value == 'BY_QUANTITY' ){
    let scanCount = 0;
    detailSource.value.forEach((item) => {
      item.subList.forEach(cur => {
        if(cur.scaned){
          scanCount++;
        }
      })
    })
    if(scanCount==0){
      showErrorMessage("扫描数为0,请先扫描")
      return;
    }
    let str = ''
    let str1 = ''
    detailSource.value.forEach((item) => {
      item.subList.forEach(cur=>{
        if(cur.scaned){
          if(parseFloat(cur.qty)>parseFloat(cur.handleQty)){
            str += `物料号【${item.itemCode}】实际提交数量【${cur.handleQty}】不可以小于任务数量【${cur.qty}】`
          }
          if(parseFloat(cur.qty)<parseFloat(cur.handleQty)){
            str1 += `物料号【${item.itemCode}】实际提交数量【${cur.handleQty}】不可以大于任务数量【${cur.qty}】`
          }
        }
      })
    })
    if(jobContent.value.allowBiggerQty == "FALSE"){
      if(str1){
        comMessageRef.value.showErrorMessage(str1);
        return;
      }
    }
    if(jobContent.value.allowSmallerQty == "FALSE"){
      if(str){
        comMessageRef.value.showErrorMessage(str);
        return;
      }
    }
    if (scanCount < subList.value.length){
      if(jobContent.value.allowPartialComplete == "TRUE"){
        comMessageRef.value.showQuestionMessage1("任务明细未全部完成,是否提交?", 'red', res => {
          if (res) {
            submitJob()
          }
        });
      } else {
        //不允许部分提交，提示
        comMessageRef.value.showErrorMessage("任务明细未全部完成,不允许部分提交!", res => {
          if (res) {
            openScanPopup();
          }
        });
      }
    }else{
      submitJob()
    }
  }else {
    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') {
        // 提交
        comMessageRef.value.showErrorMessage1("任务明细未全部完成,是否提交?", 'red', res => {
          if (res) {
            submitJob()
          }
        })
        submitJob()
      } else {
        // 不允许部分提交，提示
        comMessageRef.value.showErrorMessage(`任务明细未全部完成,不允许部分提交!`, (res) => {
          if (res) {
            openScanPopup()
          }
        })
      }
    }
  }
}

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 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()
      unPlannedReceiptJobSubmit(params)
        .then((res) => {
          uni.hideLoading()
          if (res.data) {
            showCommitSuccessMessage(`提交成功\n生成计划外入库记录\n${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.packingNumber = info.packingNumber;
        detail.fromPackingNumber = info.packingNumber;
        detail.toBatch = info.batch
        detail.toLocationCode = toLocationCode.value
        detail.toContainerNumber = ''
        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) {
        scanPopupGetFocus()
      }
    })
  })
}

const showErrorMessage = (message) => {
  setTimeout((r) => {
    scanPopupLoseFocus()
    comMessageRef.value.showErrorMessage(message, (res) => {
      if (res) {
        scanPopupGetFocus()
      }
    })
  })
}

const openScanPopup = () => {
  scanPopup.value.openScanPopup()
}

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

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

const showCommitSuccessMessage = (hint) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    navigateBack(1)
  })
}
</script>

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