<template>
  <view class="page-wraper">
    <view class="">
      <com-blank-view @goScan="openScanPopup" v-if="currentPackage == null"></com-blank-view>
    </view>
    <view class="page-wraper" v-if="currentPackage != null">
      <view class="page-main">
        <uni-collapse>
          <uni-collapse-item :open="true">
            <template v-slot:title>
              <view class="card_itemName" style="padding: 3px 5px; font-size: 28rpx"> 变更信息 </view>
            </template>
            <view class="">
              <view class="uni-flex uni-row u-col-center padding_10">
                <text style="font-size: 28rpx">变更前物料</text>
                <view class="card_itemCode" style="margin-left: 20rpx">
                  {{ currentPackage.itemCode }}
                </view>
              </view>
              <view class="uni-flex uni-row u-col-center padding_10">
                <text style="font-size: 28rpx">变更后物料</text>
                <view class="uni-flex u-col-center uni-row" @click="showSelect">
                  <view class="card_itemCode" style="margin-left: 20rpx; color: blue">
                    {{ toItemCode }}
                  </view>
                  <view class="">
                    <image src="/static/icons/down.svg" mode="" style="width: 40rpx; height: 40rpx; margin-left: 20rpx"> </image>
                  </view>
                  <u-select v-model="show" mode="single-column" :list="toItemList" @confirm="confirmSelect"></u-select>
                </view>
              </view>
              <view class="uni-flex uni-row u-col-center padding_10"
                ><text style="font-size: 28rpx">变更原因</text>
                <view class="uni-flex uni-row">
                  <uni-easyinput style="margin-left: 20px" v-model="reason"></uni-easyinput>
                </view>
              </view>
            </view>
          </uni-collapse-item>
        </uni-collapse>

        <balance style="margin-top: 5px" :dataContent="currentPackage" :isShowFromLocation="false"></balance>
        <view style="margin-left: 30rpx; margin-top: 10rpx; margin-bottom: 10rpx" v-for="(item, index) in fgList" :key="index">
          <uni-swipe-action>
            <uni-swipe-action-item :right-options="options">
              <view :class="item.scaned == true ? 'scan_view' : 'auto-wrap'">
                <light :lightCode="item.remark"></light>
              </view>
            </uni-swipe-action-item>
          </uni-swipe-action>
        </view>
      </view>
      <view class="page-footer">
        <view class="uni-flex u-col-center space-between padding_10" style="background-color: ghostwhite; width: 100%">
          <view></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="openScanFgPopup"></win-scan-button>
    </view>

    <win-com-scan-balance ref="scanPopup" @getBalance="getPackScanResult" :bussinessCode="bussinessCode" :verifyCategory="true"> </win-com-scan-balance>

    <win-scan-fg-label ref="scanFgPopup" @getResult="getFgScanResult" title="灯码"></win-scan-fg-label>
    <!-- <win-scan-pack ref="scanPopup" @getResult='getScanResult' title="制品标签" headerType="HMQ"></win-scan-pack> -->
    <comMessage ref="comMessage"></comMessage>
  </view>
</template>

<script>
import { Decimal } from 'decimal.js' // 引入
import { getSpareitemcode, getProductreceiptDetailbByPackingNumber } from '@/api/request2.js'

import { getPrecisionStrategyList } from '@/common/balance.js'
import { goHome, getPackingNumberAndBatchByList, deepCopyData, getRemoveOption } from '@/common/basic.js'

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

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

import { getBusinessType } from '@/common/record.js'

import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import winScanPack from '@/mycomponents/scan/winScanPack.vue'
import comProductRecord from '@/pages/productReceipt/coms/comProductRecord.vue'
import comBlankView from '@/mycomponents/common/comBlankView.vue'
import PackageAndItemCard from '@/mycomponents/package/PackageAndItemCard.vue'
import winComScanBalance from '@/mycomponents/scan/winComScanBalance.vue'
import winScanFgLabel from '@/mycomponents/scan/winScanFgLabel.vue'
import balance from '@/mycomponents/balance/balance.vue'
import light from '@/mycomponents/balance/light.vue'

export default {
  components: {
    winScanButton,
    winScanPack,
    comProductRecord,
    comBlankView,
    PackageAndItemCard,
    winComScanBalance,
    winScanFgLabel,
    balance,
    light
  },
  data() {
    return {
      bussinessCode: 'Relegate',
      businessType: {},
      show: false,
      toItemCode: '请选择变更后物料',
      toItemList: [],
      fgList: [],
      currentPackage: null,
      reason: ''
    }
  },
  mounted() {},
  onLoad(option) {
    uni.setNavigationBarTitle({
      title: option.title
    })
    this.getBusinessType()
    this.options = getRemoveOption()
  },
  // 返回首页
  onNavigationBarButtonTap(e) {
    if (e.index === 0) {
      goHome()
    }
  },
  // 拦截返回按钮事件
  onBackPress(e) {},

  onPullDownRefresh() {},

  mounted() {},
  methods: {
    getBusinessType() {
      getBusinessType(this.bussinessCode, (res) => {
        if (res.success) {
          this.businessType = res.businessType
          this.fromInventoryStatuses = getDirectoryItemArray(res.fromInventoryStatuses)
          this.fromLocationAreaTypeList = res.fromLocationAreaTypeList
          this.openScanPopup()
        } else {
          this.showErrorMessage(res.message)
        }
      })
    },

    getPackScanResult(result) {
      const { label } = result
      const pack = result.package
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      const params = {
        available: 'TRUE',
        changeBeforeCode: pack.itemCode,
        pageSize: 20,
        pageNo: 1
      }

      getSpareitemcode(params)
        .then((res) => {
          uni.hideLoading()
          if (res.data.list.length == 0) {
            this.showErrorMessage('未查找到变更后的物料,请在《量产件备件关系中进行配置》')
          } else {
            this.closeScanPopup()

            res.data.list.forEach((r) => {
              r.value = r.code
              r.label = `${r.code}(${r.name})`
            })

            this.toItemList = res.data.list
            if (res.data.list.length == 1) {
              this.toItemCode = res.data.list[0].code
            } else {
              this.show = true
            }

            // 查询唯一码
            getProductreceiptDetailbByPackingNumber(pack.number)
              .then((res) => {
                if (res.data.length > 0) {
                  this.fgList = res.data

                  const pack = result.package
                  const { balance } = result
                  this.currentPackage = result.package
                  this.currentPackage.packingNumber = pack.number
                  this.currentPackage.locationCode = balance.locationCode
                  this.currentPackage.inventoryStatus = balance.inventoryStatus
                  // this.getDataSource(result);
                } else {
                  this.showErrorMessage(`箱码【${pack.number}】未查找到绑定的灯码信息`)
                }
              })
              .catch((res) => {
                this.showErrorMessage(res.message)
              })
          }
        })
        .catch((res) => {
          this.showErrorMessage(res.message)
        })
    },

    getFgScanResult(result) {
      const item = this.fgList.find((r) => r.remark == result.content)
      // 不存在
      if (item != undefined) {
        const index = this.fgList.findIndex((r) => r.remark == result.content)
        if (item.scaned == true) {
          this.$refs.comMessage.showQuestionMessage(`灯码【${result.content}】已经扫描，是否移除`, (res) => {
            if (res) {
              item.scaned = false
              this.fgList.splice(index, 1)
              this.fgList.push(item) // 置底();
            }
          })
        } else {
          item.scaned = true
          this.fgList.unshift(this.fgList.splice(index, 1)[0]) // 置顶();
        }
        this.calcHandleQty()
      } else {
        this.showErrorMessage('扫描的灯码不在灯码列表中')
      }
    },

    calcHandleQty() {
      if (this.fgList.length > 0) {
        this.currentPackage.handleQty = this.fgList.filter((r) => r.scaned == true).length
      }
    },

    openScanPopup() {
      setTimeout((r) => {
        this.$refs.scanPopup.openScanPopup(this.businessType)
        this.scanPopupGetFocus()
      })
    },

    openScanFgPopup() {
      setTimeout((r) => {
        this.$refs.scanFgPopup.openScanPopup(this.currentPackage.itemCode)
        this.scanFgPopupGetFocus()
      })
    },

    commit() {
      if (this.toItemCode == '请选择变更后物料') {
        this.showMessage('请选择变更后物料')
        return
      }
      if (this.currentPackage.handleQty == null) {
        this.$refs.comMessage.showQuestionMessage('是否要将全部灯码进行变更?', (res) => {
          if (res) {
            this.commitRecord()
          }
        })
      } else {
        this.$refs.comMessage.showQuestionMessage(`是否要将已扫描的【${this.currentPackage.handleQty}】个灯码进行变更?`, (res) => {
          if (res) {
            this.commitRecord()
          }
        })
      }
    },
    commitRecord() {
      // this.showCommitSuccessMessage('提交成功')
    },

    setParams() {
      let scanedList = this.fgList.filter((r) => r.scaned == true)
      if (this.currentPackage.handleQty > 0) {
        scanedList = this.fgList.filter((r) => r.scaned == true)
      }

      const creator = this.$store.state.user.id
    },

    showMessage(message) {
      setTimeout((r) => {
        this.scanPopupLoseFocus()
        this.$refs.comMessage.showMessage(message, (res) => {
          if (res) {
            this.scanPopupGetFocus()
          }
        })
      })
    },

    showErrorMessage(message) {
      setTimeout((r) => {
        this.scanPopupLoseFocus()
        this.$refs.comMessage.showErrorMessage(message, (res) => {
          if (res) {
            this.scanPopupGetFocus()
          }
        })
      })
    },

    closeScanPopup() {
      this.$refs.scanPopup.closeScanPopup()
    },

    scanPopupGetFocus() {
      if (this.$refs.scanPopup != undefined) {
        this.$refs.scanPopup.getfocus()
      }
    },

    scanFgPopupGetFocus() {
      if (this.$refs.scanFgPopup != undefined) {
        this.$refs.scanFgPopup.getfocus()
      }
    },

    scanPopupLoseFocus() {
      if (this.$refs.scanPopup != undefined) {
        this.$refs.scanPopup.losefocus()
      }
    },

    afterCloseMessage() {
      this.scanPopupGetFocus()
    },

    closeScanMessage() {
      this.scanPopupGetFocus()
    },

    showCommitSuccessMessage(hint) {
      this.$refs.comMessage.showSuccessMessage(hint, (res) => {
        this.clearData()
        this.openScanPopup()
      })
    },
    clearData() {
      this.toItemCode = '请选择变更后物料'
      this.toItemList = []
      this.fgList = []
      this.currentPackage = null
      this.reason = ''
    },

    showSelect() {
      this.show = !this.show
    },
    confirmSelect(e) {
      this.toItemCode = e[0].value
    }
  }
}
</script>

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