<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>
    <view class="page-main">
      <scroll-view scroll-y="true" class="page-main-scroll">
        <view class="detail-list u-p-t-20" v-for="(item, index) in detailSource" :key="item.id">
          <view class="cen_card" style="padding: 5rpx">
            <view class="cell_box uni-flex uni-row u-p-t-20">
              <view class="cell_info">
                <view class="text_lightblue">车间</view>
                <view>
                  {{ jobContent.workShopCode }}
                </view>
              </view>
              <view class="cell_info">
                <view class="text_lightblue">生产线</view>
                <view>
                  {{ item.subList[0].productionLineCode }}
                </view>
              </view>
              <view class="cell_info">
                <view class="text_lightblue">班组</view>
                <view>
                  {{ jobContent.team }}
                </view>
              </view>
              <view class="cell_info">
                <view class="text_lightblue">班次</view>
                <view>
                  {{ jobContent.shift }}
                </view>
              </view>
            </view>
          </view>
          <view class="">
            <com-product-detail-card :dataContent="item" :settingParam="jobContent" :isShowLocation="false" @remove="updateData" @updateData="updateData" :locationTypeList="toLocationTypeList"> </com-product-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="">
          <locationCompare ref="comScanLocation" title="收货库位" :isShowEdit="jobContent.allowModifyLocation == 'TRUE'" :recommendLocationCode="jobToLocationCode" :locationCode="toLocationCode" @getLocation="scanLocationCode" :locationTypeList="toLocationTypeList"> </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-fg-label ref="scanPopup" @getResult="getScanResult" title="制品标签"></win-scan-fg-label>
    <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 { Decimal } from 'decimal.js' // 引入
import { getManagementPrecisions } from '@/common/balance.js'
import { getCurrDateTime, goHome, navigateBack, getPackingNumberAndBatch, getSwitchInfoByCode } from '@/common/basic.js'

import { getProductReceiptJobDetail, takeProductReceiptJob, cancleTakeProductReceiptJob, productReceiptJobsubmit, getPrintProductReceiptList, getBalanceToPackage, batchPrintingLable } from '@/api/request2.js'

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

import { getDataSource, createRecordInfo, calcHandleQty, getScanCount } from '@/common/detail.js'

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

import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import locationCompare from '@/mycomponents/location/locationCompare.vue'
import winScanFgLabel from '@/mycomponents/scan/winScanFgLabel.vue'
import comDetailCard from '@/mycomponents/detail/comDetailCard.vue'
import jobTop from '@/mycomponents/job/jobTop.vue'
import comProductDetailCard from '@/pages/productReceipt/coms/comProductDetailCard.vue'
import storage from '@/common/utils/storage.js'
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 toLocationTypeList = ref([])
const managementList = ref([])
const fromLocationCode = ref('')
const toLocationCode = ref('')
const isShowPackingCode = ref(true)
const jobStatus = ref('')
const jobToLocationCode = ref('')
const fgList = ref([])
const itemCode = ref('')
const scanedPackingNumber = ref('')
// const isCheckLocation = ref(false)
const scanPopup = ref()
const comScanIssuePackRef = ref()
const detailInfoPopupRef = ref()
const comMessageRef = ref()
const comScanLocation = ref()
onLoad((option) => {
  id.value = option.id
  scanedPackingNumber.value = option.scaned || ''
  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') {
      // 取消承接任务
      cancleTakeProductReceiptJob(id.value)
        .then((res) => {
          uni.navigateBack()
        })
        .catch((error) => {
          uni.navigateBack()
        })
    } else {
      uni.navigateBack()
    }
    return true
  }
})
onPullDownRefresh(() => {
  getDetail()
  uni.stopPullDownRefresh()
})
// 接收
const receive = (callback) => {
  if (id.value != null) {
    takeProductReceiptJob(id.value)
      .then((res) => {
        callback()
      })
      .catch((error) => {
        showErrorMessage(error)
      })
  }
}
const getDetail = () => {
  proxy.$modal.loading('加载中....')
  getProductReceiptJobDetail(id.value)
    .then((res) => {
      uni.hideLoading()
      if (res.data == null) {
        showMessage('未获取到详情')
      } else if (res.data.subList.length > 0) {
        jobContent.value = res.data
        subList.value = res.data.subList
        jobStatus.value = res.data.status
        jobToLocationCode.value = subList.value[0].toLocationCode
        if (jobContent.value.allowModifyLocation == 'FALSE') {
          toLocationCode.value = subList.value[0].toLocationCode
        }
        toLocationTypeList.value = getDirectoryItemArray(jobContent.value.toLocationTypes)
        detailSource.value = getDataSource(subList.value)
        detailSource.value.forEach((r) => {
          r.subList.forEach((s) => {
            if (scanedPackingNumber.value && scanedPackingNumber.value == s.packingNumber) {
              s.scaned = true
              // 模拟扫描功能
              scanPopup.value.simulateScan(s)
            }
          })
        })
      } else {
        showMessage('列表数据为0')
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}

const getScanResult = (result) => {
  // TODO缺少零件号的对应关系
  if (detailSource.value.length > 0) {
    const item = detailSource.value[0] // 应该按零件号查找
    result.uom = item.uom
    if (item.subList.length > 0) {
      const subItem = item.subList[0]
      subItem.scaned = true
      if (subItem.fgList == undefined) {
        subItem.fgList = []
      }

      if (subItem.fgList.length == 0) {
        subItem.fgList.push(result)
        calcFgQty(detailSource.value)
      } else {
        const itemIndex = subItem.fgList.findIndex((r) => r.itemCode == result.itemCode && r.productDate == result.productDate && r.order == result.order)
        if (itemIndex == -1) {
          subItem.fgList.push(result)
          calcFgQty(detailSource.value)
        } else {
          showQuestionMessage(`标签【${result.content}】已经扫描，是否移除`, (confirm) => {
            subItem.fgList.splice(itemIndex, 1)
            calcFgQty(detailSource.value)
          })
        }
      }

      setTimeout((r) => {
        scanPopupGetFocus()
      }, 500)
    }
  }
}

const calcFgQty = () => {
  detailSource.value.forEach((item) => {
    item.subList.forEach((pack) => {
      pack.handleQty = new Decimal(0).toNumber()
      pack.fgList.forEach((fg) => {
        if (fg != null) {
          fg.qty = new Decimal(fg.qty).toNumber()
          pack.handleQty = calc.add(pack.handleQty, fg.qty)
          // item.qty = calc.add(item.qty, detail.qty);
        }
      })
      // 扫满箱后应该自动提交
      if (pack.scaned && pack.qty == pack.fgList.length) {
        commit()
      }
    })
  })
}

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

const openScanPopup = () => {
  const { itemCode } = detailSource.value[0].subList[0]

  // itemCode = "015553147"
  console.log('物料', itemCode)
  scanPopup.value.openScanPopup(itemCode)
}

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

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

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) => {
    callback()
  })
}
// 打印功能
const print = () => {
  const packingNumber = []
  detailSource.value.forEach((item) => {
    item.subList.forEach((detail) => {
      if (detail.scaned) {
        // var info = getPackingNumberAndBatch(this.managementList, detail.itemCode,
        // 	detail.packingNumber, detail.batch);
        // detail.toPackingNumber = info.packingNumber;
        packingNumber.push(detail.packingNumber)
      }
    })
  })
  // #ifdef APP
  getPrintProductReceiptList({
    packingNumber: packingNumber.join(','),
    type: 'MakeLabel'
  })
    .then((res) => {
      const pointData = []
      res.data.forEach((item) => {
        pointData.push({
          barcodeString: item.barcodeString, // 标签
          itemCode: item.itemCode || '', // 物品代码
          itemName: item.itemName || '', // 物品名称
          packName: item.packName || '', // 包装名称
          itemType: item.itemType || '', // 物料类型
          itemDesc1: item.itemDesc1 || '', // 物品描述
          relateNumber: item.relateNumber || '', // relateNumber包装号
          batch: item.batch || '', // 批次
          productionLineCode: item.productionLineCode || '', // 生产线
          shiftCode: item.shiftCode || '', // 班次
          qty: item.qty || '', // 数量
          printTimes: getCurrDateTime() // 打印时间
        })
      })
      uni.navigateTo({
        url: `/pages/pointProductReceipt/index?points=${JSON.stringify(pointData)}`
      })
    })
    .catch((error) => {
      showErrorMessage(error)
    })
  // #endif
  // #ifdef H5
  getBalanceToPackage({
    packingNumber: packingNumber.join(',')
  })
    .then((res) => {
      console.log('PC打印', res)
      getH5BatchPrintingLable(res.data.number)
    })
    .catch((error) => {
      showErrorMessage(error)
    })
  // #endif
}
const getH5BatchPrintingLable = (number) => {
  batchPrintingLable(number).then((resLable) => {
    const webUrl = `${import.meta.env.VITE_JMREPORT_BASE_URL}/jmreport/view/922734157577715712`
    const webData = {
      token: storage.getStorage(storage.constant.token),
      asn_number: resLable.data
    }
    uni.navigateTo({
      url: `/pages/pointProductReceipt/webview?url=${webUrl}&webData=${JSON.stringify(webData)}`
    })
  })
}
const commit = () => {
  // this.scanCount = getScanCount(this.subList);
  // if (this.scanCount == 0) {
  // 	this.showErrorMessage("扫描数为0,请先扫描")
  // 	return;
  // }
  // 校验库位、
  if (!checkLocation()) {
    return
  }
  const valiDate = getSwitchInfoByCode('fgProductReceipCommitValidate')
  detailSource.value.forEach((item) => {
    item.subList.forEach((subitem) => {
      if (valiDate) {
        if (subitem.handleQty == undefined) {
          showMessage('还没扫码成品不能提交')
        } else if (subitem.handleQty != subitem.packQty) {
          showQuestionMessage('制品数量不等于包装数量,是否继续提交?', (res) => {
            if (res) {
              submitJob()
            }
          })
        } else {
          submitJob()
        }
      } else {
        subitem.handleQty = subitem.qty
        subitem.scaned = true
        submitJob()
      }
    })
  })
}

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()
      productReceiptJobsubmit(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 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.toBatch = info.batch
        detail.toContainerNumber = ''
        detail.toInventoryStatus = detail.inventoryStatus
        detail.toLocationCode = toLocationCode.value
        detail.available = 'TRUE'
        if (detail.fgList) {
          detail.fgList.forEach((res) => {
            res.outsideItemCode = res.itemCode
            res.outsideProduceDate = res.productDate
            res.outsideSerialNumber = res.order
            res.lowerLim = res.content
          })
        }
        subList.push(detail)
      }
    })
  })
  jobContent.value.available = 'TRUE'
  jobContent.value.subList = subList
  jobContent.value.creator = creator
  return jobContent.value
}

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

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

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

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

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

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