<template>
  <view class="page-wraper">
    <view class="page-header">
      <view class="header_job_top">
        <view class="header-view">
          <job-top :dataContent="jobContent"></job-top>
          <u-collapse ref="collapse">
            <u-collapse-item :open="true">
              <template v-slot:title>
                <view class="card_itemName" style="padding: 3px 5px; font-size: 28rpx"> 盘点范围 </view>
              </template>
              <view v-for="(range, index) in jobContent.countRange" :key="index">
                <view class="card_view">
                  <text class="card_packing_code">{{ getCountScopeName(range.type) }}</text>
                  <text class="card_content">{{ range.value }}</text>
                </view>
              </view>
            </u-collapse-item>
          </u-collapse>
        </view>
      </view>
      <view class="card_view" v-if="fromLocationCode != ''">
        <text class="card_location">盘点库位</text>
        <text class="card_content">{{ fromLocationCode }}</text>
      </view>
    </view>
    <com-blank-view @goScan="showFromLocationPopup" v-if="detailSource.length == 0"></com-blank-view>
    <view class="page-main">
      <scroll-view scroll-y="true" class="page-main-scroll">
        <u-swipe-action ref="swipeAction"
                          v-for="(item, index) in detailSource" :key="item.id"
                          :options="editRemoveOption"
                          @click="(...event)=>swipeClick(event, item, index)">
          <view class="detail-list">
            <view class="">
              <package-and-item-card :dataContent="item"></package-and-item-card>
            </view>
            <view class="split_line"></view>
          </view>
        </u-swipe-action>
      </scroll-view>
    </view>

    <view class="page-footer" v-if="detailSource.length > 0">
      <view class="uni-flex u-col-center space-between padding_10" style="background-color: ghostwhite; width: 100%">
        <view class="uni-flex u-col-center space-between padding_10">
          <view> 已扫描: </view>
          <view class="card_packing_code" style="padding: 5px; font-weight: bold; font-size: 40rpx">
            {{ detailSource.length }}
          </view>
          <view> (箱) </view>
        </view>
        <view class="uni-flex uni-row space-between">
          <button class="btn_single_commit" hover-class="btn_commit_after" @click="commit">提交</button>
        </view>
      </view>
    </view>

    <win-scan-button v-if="fromLocationCode != ''" @goScan="openScanPopup"></win-scan-button>
    <win-scan-pack ref="scanPopup" @getResult="getScanResult"></win-scan-pack>
    <win-scan-location ref="scanLocationCode" title="盘点库位" @getLocation="getLocation"></win-scan-location>
    <count-qty-edit ref="countQtyEdit" @confirm="editConfirm" @close="editClose" :isShowStatus="true" :isShowDesc="false" :allowEditStatus="editInventoryStatus" :isShowBalance="jobContent.isOpenCount == 'TRUE'"> </count-qty-edit>
    <comMessage ref="comMessage"></comMessage>
  </view>
</template>

<script setup>
import { Decimal } from 'decimal.js' // 引入
import { getFuuzyCountJobDetail, takeCountJob, cancleTakeCountJob, countJobSubmit } from '@/api/request2.js'
import { calc } from '@/common/calc.js'

import { getEditRemoveOption } from '@/common/array.js'

import { goHome, navigateBack, getPackingNumberAndBatch } from '@/common/basic.js'

import { getCountScopeType } from '@/common/directory.js'
import {getManagementPrecisions,} from '@/common/balance.js';
import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import winScanPack from '@/mycomponents/scan/winScanPack.vue'
import comCountDetailCard from '@/pages/count/coms/comCountDetailCard.vue'
// import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"
import winScanLocation from '@/mycomponents/scan/winScanLocation.vue'
import countQtyEdit from '@/mycomponents/qty/countQtyEdit.vue'
import jobTop from '@/mycomponents/job/jobTop.vue'
import comBlankView from '@/mycomponents/common/comBlankView.vue'
import PackageAndItemCard from '@/mycomponents/package/PackageAndItemCard.vue'

import { ref, nextTick } from 'vue'
import { onLoad, onPullDownRefresh, onBackPress, onNavigationBarButtonTap } from '@dcloudio/uni-app'
import {useCountStore} from '@/store'
const store = useCountStore()
const id = ref(null)
const jobStatus = ref('')
const editRemoveOption = ref(getEditRemoveOption())
const jobContent = ref({})
const itemRangeValue = ref('')
const fromLocation = ref({})
const fromLocationCode = ref('')
const detailSource = ref([])
const managementList = ref([])
const managementType = ref('')
const currentEditItem = ref(null)
const showItem = ref(null)

const scanLocationCode = ref(null)
const scanPopup = ref(null)
const comMessage = ref(null)
const countQtyEdit = ref(null)
const detailInfoPopup = ref(null)

onLoad(option => {
  id.value = option.id
  if (id.value !== undefined) {
    if (option.status === '1') {
      receive(() => getDetail(() => showFromLocationPopup()))
    } else {
      getDetail(() => showFromLocationPopup())
    }
  }
  editRemoveOption.value = getEditRemoveOption()
})

onNavigationBarButtonTap(e => {
  if (e.index === 0) {
    goHome()
  }
})

onBackPress(e => {
  if (e.from === 'backbutton') {
    if (jobStatus.value === '2') {
      cancleTakeCountJob(id.value)
        .then(() => uni.navigateBack())
        .catch(() => uni.navigateBack())
    } else {
      uni.navigateBack()
    }
    return true
  }
})

onPullDownRefresh(() => {
  // uni.stopPullDownRefresh();
})

const receive = (callback) => {
  if (id.value !== null) {
    takeCountJob(id.value)
      .then(callback)
      .catch(error => showErrorMessage(error))
  }
}

const getDetail = (callback) => {
  uni.showLoading({ title: '加载中....', mask: true })
  getFuuzyCountJobDetail(id.value)
    .then(res => {
      uni.hideLoading()
      jobContent.value = res.data
      jobStatus.value = res.data.status
      const range = jobContent.value.countRange.find(r => r.type === 'ITEM_CODE')
      if (range !== undefined) {
        itemRangeValue.value = range.value
      }
      callback()
    })
    .catch(error => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}

const showFromLocationPopup = () => {
  // this.$refs.scanLocationCode.openScanPopup();
  nextTick(() => {
    scanLocationCode.value.openScanPopup()
  })
}

const getLocation = (location, code) => {
  const { countRange } = jobContent.value

  if (countRange !== null) {
    let range = countRange.find(r => r.type === 'LOCATION_CODE')
    if (range !== undefined) {
      const rangeValue = range.value
      const index = rangeValue.indexOf(location.code)
      if (index < 0) {
        afterScanLocation(`库位代码【${location.code}】,不在盘点库位范围【${rangeValue}】内`)
        return
      }
    } else {
      range = countRange.find(r => r.type === 'LOCATIONGROUP_CODE')
      if (range !== undefined) {
        const rangeValue = range.value
        const index = rangeValue.indexOf(location.locationGroupCode)
        if (index < 0) {
          afterScanLocation(`库位组代码【${location.locationGroupCode}】,不在盘点库位组范围【${rangeValue}】内`)
          return
        }
      } else {
        range = countRange.find(r => r.type === 'AREABASIC_CODE')
        if (range !== undefined) {
          const rangeValue = range.value
          const index = rangeValue.indexOf(location.areaCode)
          if (index < 0) {
            afterScanLocation(`库区代码【${location.areaCode}】,不在盘点库区范围【${rangeValue}】内`)
            return
          }
        } else {
          range = countRange.find(r => r.type === 'WAREHOUSE_CODE')
          if (range !== undefined) {
            const rangeValue = range.value
            const index = rangeValue.indexOf(location.warehouseCode)
            if (index < 0) {
              afterScanLocation(`仓库代码【${location.warehouseCode}】,不在盘点仓库范围【${rangeValue}】内`)
              return
            }
          }
        }
      }
    }
  }
  getFromLocationCode(location, code)
}

const afterScanLocation = (message) => {
  showErrorMessage(message)
  showFromLocationPopup()
}

const getFromLocationCode = (location, code) => {
  fromLocation.value = location
  fromLocationCode.value = code
  openScanPopup()
}

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

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

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

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

const getScanResult = (result) => {
  const packInfo = result.package
  if (itemRangeValue.value !== '') {
    const index = itemRangeValue.value.indexOf(packInfo.itemCode)
    if (index < 0) {
      showErrorMessage(`物料代码【${packInfo.itemCode}】,不在盘点范围【${itemRangeValue.value}】内`)
    } else {
      onScan(packInfo)
    }
  } else {
    onScan(packInfo)
  }
}

const onScan = async (packInfo) => {
  console.log(packInfo)
  // 获取管理模式，封装参数
  await getManagementPrecisions([packInfo.itemCode], packInfo.toLocationCode, res => {
    if (res.success) {
      managementList.value = res.list
      managementType.value = managementList.value.some(item => item.ManagementPrecision === 'BY_BATCH') ? 'BY_BATCH' : ''
      if (managementType.value === 'BY_BATCH') {
        let detail = detailSource.value.find(r => r.itemCode === packInfo.itemCode && r.batch === packInfo.batch && r.inventoryStatus === 'OK')
        if (detail === undefined) {
          detail = createDetailInfo(packInfo)
          detail.packingNumber = ''
          detail.packUnit = ''
          detailSource.value.unshift(detail)
          scanPopupGetFocus()
        } else {
          let index = detailSource.value.findIndex(r => r.itemCode === packInfo.itemCode && r.batch === packInfo.batch && r.inventoryStatus === 'OK')
          if (index >= 0) {
            detailSource.value.unshift(detailSource.value.splice(index, 1)[0]) // 置顶
            detailSource.value[0].qty = calc.add(detailSource.value[0].qty, packInfo.qty)
          }
        }
      } else {
        let detail = detailSource.value.find(r => r.itemCode === packInfo.itemCode && r.packingNumber === packInfo.number && r.batch === packInfo.batch && r.inventoryStatus === 'OK')
        if (detail === undefined) {
          detail = createDetailInfo(packInfo)
          detailSource.value.unshift(detail)
          scanPopupGetFocus()
        } else {
          let index = detailSource.value.findIndex(r => r.itemCode === packInfo.itemCode && r.packingNumber === packInfo.number && r.batch === packInfo.batch && r.inventoryStatus === 'OK')
          if (index >= 0) {
            detailSource.value.unshift(detailSource.value.splice(index, 1)[0]) // 置顶
            // 提交
            comMessage.value.showQuestionMessage('该箱码已经扫描,是否要编辑盘点明细?', res => {
              if (res) {
                closeScanPopup()
                edit(detail)
              } else {
                scanPopupGetFocus()
              }
            })
          }
        }
      }
    }
  })
}

const createDetailInfo = (packInfo) => {
  return {
    scaned: true,
    number: jobContent.value.number,
    packingNumber: packInfo.number,
    batch: packInfo.batch,
    inventoryStatus: 'OK',
    itemCode: packInfo.itemCode,
    itemName: packInfo.itemName,
    itemDesc1: packInfo.itemDesc1,
    itemDesc2: packInfo.itemDesc2,
    projectCode: '',
    qty: packInfo.qty,
    packUnit: packInfo.packUnit,
    packQty: packInfo.packQty,
    packUom: packInfo.packUom,
    uom: packInfo.uom,
    remark: '',
    locationCode: fromLocationCode.value,
    creator: store.id,
    warehouseCode: fromLocation.value.warehouseCode,
    areaCode: fromLocation.value.areaCode,
    locationGroupCode: fromLocation.value.locationGroupCode,
    createTime: new Date().getTime(),
    countTime: new Date().getTime(),
    countUser: store.id,
    countDescription: '',
    countQty: packInfo.qty
  }
}

const swipeClick = (e, item, index) => {
  if (e.content.text === '编辑') {
    edit(item)
  } else if (e.content.text === '移除') {
    remove(item, index)
  }
}

const edit = (item) => {
  currentEditItem.value = item
  item.handleQty = item.qty
  countQtyEdit.value.openEditPopup(item, null)
}

const editConfirm = (qty, inventoryStatus, mode) => {
  currentEditItem.value.countQty = qty
  currentEditItem.value.qty = qty
  currentEditItem.value.inventoryStatus = inventoryStatus
  openScanPopup()
}

const editClose = () => {
  scanPopupGetFocus()
}

const remove = (item, index) => {
  scanPopupLoseFocus()
  comMessage.value.showQuestionMessage('是否要移除扫描信息?', res => {
    if (res) {
      detailSource.value.splice(index, 1)
    }
    scanPopupGetFocus()
  })
}

const detail = (item) => {
  showItem.value = item
  detailInfoPopup.value.openPopup(item)
}

const commit = () => {
  if (detailSource.value.length === 0) {
    comMessage.value.showMessage('还未扫描,是否要继续提交', res => {
      if (res) {
        commitJob()
      }
    })
  } else {
    commitJob()
  }
}

const commitJob = () => {
  uni.showLoading({ title: '提交中....', mask: true })
  const params = setParams()
  console.log('提交参数', JSON.stringify(params))
  countJobSubmit(params)
    .then(res => {
      uni.hideLoading()
      if (res.data === null) {
        showCommitSuccessMessage('提交成功')
      } else {
        showErrorMessage(`提交失败[${res.msg}]`)
      }
    })
    .catch(error => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}

const setParams = () => {
  const creator = store.id
  jobContent.value.subList = detailSource.value
  // jobContent.value.creator = creator;
  return jobContent.value
}

const showMessage = (message) => {
  scanPopupLoseFocus()
  comMessage.value.showMessage(message, res => {
    if (res) {
      afterCloseMessage()
    }
  })
}

const showErrorMessage = (message) => {
  scanPopupLoseFocus()
  comMessage.value.showErrorMessage(message, res => {
    if (res) {
      afterCloseMessage()
    }
  })
}

const showScanMessage = (message) => {
  comMessage.value.showScanMessage(message)
}

const afterCloseMessage = () => {
  scanPopupGetFocus()
}

const closeScanMessage = () => {
  scanPopupGetFocus()
}

const showCommitSuccessMessage = (hint) => {
  comMessage.value.showSuccessMessage(hint, res => {
    fromLocationCode.value = ''
    fromLocation.value = {}
    detailSource.value = []
    showFromLocationPopup()
  })
}

const getCountStageName = (value) => {
  return getCountStageName(value)
}

const isOpenCount = (value) => {
  return value === 'TRUE' ? '明盘' : '盲盘'
}

const getCountScopeName = (value) => {
  const item = getCountScopeType(value)
  return item.label
}

const showQuestionMessage = (message, callback) => {
  comMessage.value.showQuestionMessage(message, res => {
    callback(res)
  })
}
</script>

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

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

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

// }
</style>
