<template>
  <view class="page-wraper" style="background-color: #fff">
    <view class="header">
      <view class="">
        <com-blank-view @goScan="openFg" v-if="!dataContent"></com-blank-view>
      </view>
      <view class="" v-if="dataContent">
        <view class="" style="font-size: 35rpx; padding: 10rpx; padding-left: 15rpx"> 生产计划:{{ dataContent.planNumber }} </view>
        <view class="split_line"></view>

        <view class="cell_box uni-flex uni-row">
          <view class="cell_info">
            <view class="text_lightblue">完工库位</view>
            <view style="font-size: 30rpx; margin-top: 13rpx">{{ dataContent.fgLocationCode }} </view>
          </view>
          <view class="cell_info">
            <view class="text_lightblue">计划数</view>
            <view>{{ dataContent.planQty }}{{ dataContent.uom }}</view>
          </view>
          <view class="cell_info">
            <view class="text_lightblue">已完工</view>
            <view>{{ dataContent.goodQty }}{{ dataContent.uom }}</view>
          </view>
          <view class="cell_info">
            <view class="text_lightblue">未完工</view>
            <view>{{ dataContent.noGoodQty }}{{ dataContent.uom }}</view>
          </view>
        </view>
        <view class="split_line"></view>

        <view class="" style="padding-top: 10rpx; padding-bottom: 10rpx; margin-left: 10rpx">
          <item :dataContent="dataContent"></item>
        </view>
        <view class="split_line"></view>
        <view class="uni-flex uni-row space-between" style="align-items: center">
          <view style="word-break: break-all">
            <batch :batch="dataContent.batch"></batch>
            <view class="card_view">
              <text style="color: #ffa500; padding: 5px; font-size: 30rpx">包装规格</text>
              <text class="card_content">{{ dataContent.packUnit }} </text>
            </view>
          </view>
          <view style="word-break: break-all; font-size: 35rpx; font-weight: bold">
            <text v-if="dataContent.handleQty > 0" style="color: #ffa500">{{ dataContent.handleQty }}/</text>
            {{ dataContent.packQtyHint }}
          </view>
        </view>
        <view class="split_line" v-if="dataContent"></view>
      </view>
    </view>

    <view style="margin-top: 480rpx; padding-bottom: 160rpx" v-if="dataContent">
      <scroll-view scroll-y="true" class="">
        <view class="scan_view" v-for="(item, index) in showList" :key="index">
          <uni-swipe-action>
            <uni-swipe-action-item :right-options="options" @click="swipeClick($event, item, index)">
              <view class="uni-flex uni-row" style="margin-left: 50rpx; padding-top: 10rpx; padding-bottom: 10rpx">
                <view class="auto-wrap" style="font-size: 35rpx; font-weight: bold; width: 100%">
                  <text style="font-size: 30rpx; color: #b66463">唯一码 </text>
                  {{ item.content }}
                </view>
              </view>
            </uni-swipe-action-item>
          </uni-swipe-action>
          <u-line color="#D8D8D8"></u-line>
        </view>
      </scroll-view>
      <uni-load-more :status="loadingType" v-if="showList.length > 0" />
    </view>
    <view class="page-footer" v-if="dataContent">
      <view class="uni-flex u-col-center space-between" style="background-color: ghostwhite; width: 100%">
        <view class="">
          <view class="uni-flex uni-row"> </view>
        </view>
        <view class="uni-flex uni-row">
          <button class="btn_single_clear" hover-class="btn_commit_after" style="margin-right: 50rpx" @click="clear">清空</button>
          <button class="btn_single_commit" hover-class="btn_commit_after" @click="submit">提交</button>
        </view>
      </view>
    </view>
    <comReceiptPopup ref="comReceiptPopupRef" @confirm="requestConfirm"></comReceiptPopup>
    <win-scan-button v-if="dataContent" @goScan="openScanPopup"></win-scan-button>
    <win-scan-fg-label ref=" " @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 { isCheckMesCode, planReceiptSubmit, createPutawayRequestByPlan, createInspectRequestByPlan, getPlanByNumber } from '@/api/request2.js'
import { calc } from '@/common/calc.js'

import { getRemoveOption, deepCopyData, getCurrDateTime, compare } from '@/common/basic.js'
import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import comBlankView from '@/mycomponents/common/comBlankView.vue'
import comReceiptPopup from '@/pages/fg/coms/comReceiptPopup.vue'
import item from '@/mycomponents/item/item.vue'
import batch from '@/mycomponents/balance/batch.vue'
import pack from '@/mycomponents/balance/pack.vue'
import winScanFgLabel from '@/mycomponents/scan/winScanFgLabel.vue'
import comFgCard from '@/pages/productReceipt/coms/comFgCard.vue'

const dataContent = ref(null)
const options = ref([])
const showList = ref([])
const allList = ref([])
const index = ref(1)
const loadingType = ref('')
const loadingType = ref('')
const pageSize = ref(20)
const comReceiptPopupRef = ref()
const scanPopup = ref()
const comMessageRef = ref()

onLoad(() => {
  options.value = getRemoveOption()
  openFg()
})

onReachBottom(() => {
  console.log('onReachBottom')
  // 避免多次触发
  if (loadingType.value == 'nomore') {
    return
  }
  index.value++
  const list = getDataPage(index.value, pageSize.value)
  if (list.length > 0) {
    // this.showList=list
    showList.value = showList.value.concat(list)
  } else {
    // 没有更多了
    loadingType.value = 'nomore'
  }
})
const openFg = () => {
  setTimeout((res) => {
    if (comReceiptPopupRef.value) {
      comReceiptPopupRef.value.openRequestPopup()
    }
  }, 600)
}
const requestConfirm = (result) => {
  dataContent.value = {
    itemCode: result.itemCode,
    planNumber: result.planNumber, // 计划单号
    handleQty: 0,
    qty: 0,
    planQty: result.planQty,
    goodQty: result.goodQty,
    noGoodQty: calc.sub(result.planQty, result.goodQty),
    packQtyHint: result.packQtyHint,
    packQty: result.packQty,
    uom: result.uom,
    batch: result.batch,
    packUnit: result.packUnit,
    workStationCode: result.workStationCode,
    fgLocationCode: result.fgLocationCode,
    subList: []
  }
}
const initList = () => {
  index.value = 1
  showList.value = []
  loadingType.value = ''
  showList.value = getDataPage(index.value, pageSize.value)
}
const getDataPage = (pageNo, pageSize) => {
  // 计算总页数
  const totalPages = Math.ceil(allList.value.length / pageSize)
  // 当前页起始索引
  const start = (pageNo - 1) * pageSize
  const end = start + pageSize // 当前页结束索引
  return allList.value.slice(start, end)
}
const swipeClick = (e, dataContent, index) => {
  if (e.content.text == '移除') {
    comMessageRef.value.showQuestionMessage('是否要移除', (res) => {
      if (res) {
        allList.value.splice(index, 1)
        initList()
      }
    })
  }
}

const submit = () => {
  if (allList.value.length == 0) {
    showErrorMessage('请先扫描唯一码')
    return
  }

  if (allList.value.length < dataContent.value.packQty) {
    comMessageRef.value.showQuestionMessage('扫描数量小于包装规格数量,是否提交?', (res) => {
      if (res) {
        commit()
      }
    })
  } else {
    commit()
  }
}

const commit = async () => {
  try {
    uni.showLoading({
      title: '提交中...',
      mask: true
    })
    const params = setParams()
    console.log(JSON.stringify(params))

    const list = []
    const planData = await planReceiptSubmit(params)
    if (planData.data) {
      planData.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: '',
          requestNumber: item.requestNumber
        })
      })
    } else {
      throw new Error('提交失败')
    }

    createPutawayRequestByPlan(list[0].requestNumber).then((res) => {
      createInspectRequestByPlan(list[0].requestNumber)
    })

    const queryParams = {
      filters: [
        {
          column: 'plan_type',
          action: '==',
          value: 'assemble'
        },
        {
          column: 'number',
          action: '==',
          value: dataContent.value.planNumber
        }
      ],
      pageNo: 1,
      pageSize: 100
    }

    const planeInfo = await getPlanByNumber(queryParams)
    if (planeInfo.data && planeInfo.data.list.length > 0) {
      if (planeInfo.data.list[0].goodQty >= planeInfo.data.list[0].planQty) {
        clear()
      } else {
        dataContent.value.planNumber = planeInfo.data.list[0].number
        dataContent.value.handleQty = 0
        dataContent.value.planQty = planeInfo.data.list[0].planQty
        dataContent.value.goodQty = planeInfo.data.list[0].goodQty
        ;(dataContent.value.noGoodQty = calc.sub(planeInfo.data.list[0].planQty, planeInfo.data.list[0].goodQty)), (dataContent.value.subList = [])
        showList.value = []
        allList.value = []
        index.value = 1
      }
    } else {
      throw new Error('未查找到单据信息')
    }
    uni.hideLoading()
    showCommitSuccessMessage('提交成功<br>生成装配收货记录<br>', list)
  } catch (error) {
    uni.hideLoading()
    const hint = error.message ? error.message : error
    showErrorMessage(hint)
  }
}
const setParams = () => {
  allList.value.forEach((res) => {
    res.outsideItemCode = res.itemCode
    res.outsideProduceDate = null
    res.outsideSerialNumber = res.order
  })
  dataContent.value.subList = allList.value

  return dataContent.value
}
const clear = () => {
  comMessageRef.value.showQuestionMessage('是否要清空?', (res) => {
    if (res) {
      clearData()
      openFg()
    }
  })
}
const clearData = () => {
  dataContent.value = null
  showList.value = []
  allList.value = []
  index.value = 1
}
const openScanPopup = () => {
  const { itemCode } = dataContent.value
  console.log('物料', itemCode)
  scanPopup.value.openScanPopup(itemCode)
}
const getScanResult = (result) => {
  // TODO缺少零件号的对应关系
  // 查询mes码是否完工
  isCheckMesCode(result.content)
    .then((res) => {
      if (res.data) {
        if (that.dataContent) {
          const itemIndex = allList.value.findIndex((r) => r.itemCode == result.itemCode && r.order == result.order)
          // 不存在
          if (itemIndex == -1) {
            // if (this.allList.length > this.dataContent.packQty) {
            // 	this.showErrorMessage("唯一码数量不能大于计划数量")
            // 	return;
            // }
            result.countTime = new Date()
            allList.value.push(result)
            allList.value.sort(compare('countTime')) // 按扫描信息排序
            initList()
            scanPopupGetFocus()
            calcFgQty()
          } else {
            comMessageRef.value.showQuestionMessage(`唯一码【${result.content}】已经扫描,是否移除`, (res) => {
              if (res) {
                allList.value.splice(itemIndex, 1)
                allList.value.sort(compare('countTime')) // 按扫描信息排序
                initList()
                calcFgQty()
              }
            })
          }
        }
      }
    })
    .catch((error) => {
      showErrorMessage(error)
    })
}
const calcFgQty = () => {
  dataContent.value.handleQty = allList.value.length
  if (dataContent.value.handleQty == dataContent.value.packQty) {
    if (scanPopup.value) {
      scanPopup.value.closeScanPopup()
    }
    commit()
  }
}
const scanPopupGetFocus = () => {
  if (scanPopup.value) {
    scanPopup.value.getfocus()
  }
}
const scanPopupLoseFocus = () => {
  if (scanPopup.value) {
    scanPopup.value.losefocus()
  }
}
const showCommitSuccessMessage = (hint, pointData) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    if (pointData.length > 0) {
      uni.navigateTo({
        url: `/pages/point/index?points=${JSON.stringify(pointData)}`
      })
    }
  })
}
const showErrorMessage = (message) => {
  comMessageRef.value.showErrorMessage(message, (res) => {
    if (res) {
      scanPopupGetFocus()
    }
  })
}
</script>

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

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

.header {
  position: fixed;
  /* #ifdef H5 */
  top: 88rpx;
  /* #endif */
  left: 0;
  width: 100%;
  background-color: #fff;
  z-index: 10;
  padding: 10rpx;
  /* 确保头部在内容之上 */
}

.page-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.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;
}

.item {
  background-color: #fff;
}

.item_scaned {
  background-color: antiquewhite;
}

.auto-wrap {
  white-space: normal;
  word-break: break-all;
  overflow-wrap: break-word;
  /* 对于兼容性更好的情况 */
}
</style>