<template>
  <view class="page-wraper">
    <view class="header">
      <view class="">
        <job-top :dataContent="jobContent"></job-top>
      </view>
      <view class="cen_card" style="padding-top: 10rpx; padding-bottom: 10rpx">
        <view class="cell_box uni-flex uni-row" style="font-weight: bold">
          <view class="cell_info" style="color: #000">
            <view class="text_lightblue" style="color: #000">阶段</view>
            <view style="color: #000">{{ getCountStageNameValue(jobContent.stage) }}</view>
          </view>
          <view class="cell_info">
            <view class="text_lightblue" style="color: #000">策略</view>
            <view style="color: #000">{{ isOpenCount(jobContent.isOpenCount) }}</view>
          </view>
          <view class="cell_info">
            <view class="text_lightblue" style="color: #000">库位</view>
            <view style="color: #000">{{ fromLocationCode }}</view>
          </view>
          <view class="cell_info">
            <view class="text_lightblue" style="color: #000">总数</view>
            <view style="color: #000"> {{ allCount }}</view>
          </view>
          <view class="cell_info">
            <view class="text_lightblue" style="color: #000">已扫描</view>
            <view style="color: #000">{{ scanCount }}</view>
          </view>
        </view>
      </view>
    </view>
    <u-line color="#D8D8D8" style="margin-bottom: 10rpx"></u-line>
    <view style="margin-top: 160rpx; padding-bottom: 130rpx">
      <u-line color="#D8D8D8" style="margin-bottom: 15rpx"></u-line>
      <scroll-view scroll-y="true" class="" style="margin-bottom: 0px">
        <view class="detail-list" v-for="(item, index) in showList" :key="item.id">
          <uni-swipe-action ref="swipeAction">
            <uni-swipe-action-item @click="swipeClick($event, item)" :right-options="item.scaned ? scanOptions : detailOptions">
              <view class="uni-flex uni-row" style="align-items: center" :class="item.scaned ? 'scan_view' : 'item'">
                <view class="" style="font-size: 30rpx; font-weight: bold"> {{ index + 1 }}. </view>
                <comCountDetailcards :ref="'countDetail_' + index" :dataContent="item" :index="index" @editItem="editItem" :settingParam="jobContent" @remove="updateData" @updateData="updateData"> </comCountDetailcards>
              </view>
              <view class="split_line"></view>
            </uni-swipe-action-item>
          </uni-swipe-action>
        </view>
      </scroll-view>
      <uni-load-more :status="loadingType" v-if="showList.length > 0" />
    </view>

    <view class="page-footer">
      <view class="uni-flex u-col-center space-between padding_10" style="background-color: ghostwhite; width: 100%">
        <view class=""> </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-and-location :allowModifyLocation="false" ref="scanPopup" :noShowBalanceMessage="true" @getCountScanResult="getScanResult"> </win-scan-pack-and-location>
    <count-qty-edit ref="countQtyEditRef" @confirm="editConfirm" @close="editClose" :isShowStatus="true" :allowEditStatus="editInventoryStatus" :isShowBalance="jobContent.isOpenCount == 'TRUE'"> </count-qty-edit>
    <detail-info-popup ref="detailInfoPopupRef"></detail-info-popup>
    <com-message ref="comMessageRef" />
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, nextTick, watch } from 'vue'
import { onShow, onNavigationBarButtonTap, onReady, onReachBottom, onPullDownRefresh, onLoad, onBackPress } from '@dcloudio/uni-app'
import { getCountJobDetail, takeCountJob, cancleTakeCountJob, countJobSubmit } from '@/api/request2.js'

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

import { getDetailOption, getDetailEditRemoveOption } from '@/common/array.js'
import { getCountStageName } from '@/common/directory.js'

import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import comCountDetailcards from '@/pages/count/coms/comCountDetailcards.vue'
import winScanPackAndLocation from '@/mycomponents/scan/winScanPackAndLocation.vue'
import countQtyEdit from '@/mycomponents/qty/countQtyEdit.vue'
import jobTop from '@/mycomponents/job/jobTop.vue'
import detailInfoPopup from '@/pages/count/coms/detailInfoPopup.vue'
import { useCountStore } from '@/store'
// 获取自定义的store
const store = useCountStore()

const { proxy } = getCurrentInstance()

const id = ref('')
const fromLocationCode = ref('')
const jobContent = ref({}) // 任务内容
const editInventoryStatus = ref(false)
const currentEditItem = ref({})
const jobStatus = ref('')
const allCount = ref(0)
const scanCount = ref(0)
const index = ref(0)
const pageSize = ref(20)
const showList = ref([])
const loadingType = ref('')
const allDetails = ref([])
const scanOptions = ref([])
const detailOptions = ref([])
const detailInfoPopupRef = ref()
const showItem = ref()
const comMessageRef = ref()
const scanPopup = ref()
const countQtyEditRef = ref()

onLoad((option) => {
  id.value = option.id
  if (id.value != undefined) {
    // 新建的任务自动接收
    if (option.status == '1') {
      receive((callback) => {
        getDetail()
      })
    } else {
      getDetail()
    }
  }
  detailOptions.value = getDetailOption()
  scanOptions.value = getDetailEditRemoveOption()
})
// 返回首页
onNavigationBarButtonTap((e) => {
  if (e.index === 0) {
    goHome()
  }
})
// 拦截返回按钮事件
onBackPress((e) => {
  // 已经接收但是没提交任务
  if (e.from === 'backbutton') {
    if (jobStatus.value == '2') {
      // 取消承接任务
      cancleTakeCountJob(id.value)
        .then((res) => {
          uni.navigateBack()
        })
        .catch((error) => {
          uni.navigateBack()
        })
    } else {
      uni.navigateBack()
    }
    return true
  }
})

onPullDownRefresh(() => {
  initList()
  uni.stopPullDownRefresh()
})

onReachBottom(() => {
  console.log('onReachBottom')
  // 避免多次触发
  if (loadingType.value == 'nomore') {
    return
  }
  index.value++
  const list = getDataPage(index.value, pageSize.value)
  if (list.length > 0) {
    showList.value = showList.value.concat(list)
  } else {
    // 没有更多了
    loadingType.value = 'nomore'
  }
})

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

const getDetail = () => {
  uni.showLoading({
    title: '加载中....',
    mask: true
  })
  getCountJobDetail(id.value)
    .then((res) => {
      uni.hideLoading()
      if (res.data == null) {
        showMessage('未获取到详情')
      } else {
        jobContent.value = res.data
        jobStatus.value = res.data.status
        fromLocationCode.value = jobContent.value.countSplitCode
        res.data.subList.forEach((item) => {
          item.recommendQty = item.qty
          item.handleQty = 0
          item.countTime = new Date()
          item.fromLocationCode = fromLocationCode.value
        })
        allDetails.value = res.data.subList
        allCount.value = res.data.subList.length
        initList()
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}

const initList = () => {
  index.value = 1
  showList.value = []
  loadingType.value = ''
  showList.value = getDataPage(index.value, pageSize.value)
}

const getDataPage = (pageNo, pageSize) => {
  // 计算总页数
  const totalPages = Math.ceil(allCount.value / pageSize)
  // 当前页起始索引
  const start = (pageNo - 1) * pageSize
  const end = start + pageSize // 当前页结束索引
  return allDetails.value.slice(start, end)
}

const swipeClick = (e, item) => {
  if (e.content.text == '详情') {
    detail(item)
  } else if (e.content.text == '编辑') {
    editItem(item)
  } else if (e.content.text == '移除') {
    remove(item)
  }
}
const detail = (item) => {
  showItem.value = item
  detailInfoPopupRef.value.openPopup(item)
}

const remove = (item, index) => {
  comMessageRef.value.showQuestionMessage('确定移除扫描信息?', (res) => {
    if (res) {
      item.scaned = false
      item.handleQty = 0
      emit('removePack')
    }
  })
}

const openScanPopup = () => {
  const fromlocationList = []
  fromlocationList.push(fromLocationCode.value)
  scanPopup.value.openScanPopupForJob(fromLocationCode.value, fromlocationList, jobContent.value)
}

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

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

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

// 明盘
const getScanResult = (result) => {
  const { itemCode } = result.label
  const { packingNumber } = result.label
  const pack = result.package
  const { batch } = result.label
  const inventoryStatus = result.balance ? result.balance.inventoryStatus : 'OK'
  const qty = result.balance ? result.balance.qty : 0

  // 按物料、箱码、批次、状态匹配
  const items = allDetails.value.filter((r) => r.itemCode === itemCode && r.packingNumber === packingNumber && r.batch === batch && r.inventoryStatus === inventoryStatus)
  // 不在任务列表中,是否添加库存
  if (items.length == 0) {
    comMessageRef.value.showQuestionMessage(`包装【${result.label.packingNumber}】不在任务列表中,是否要添加到列表中?`, (res) => {
      // 创建盘点信息，标记为已经扫描
      if (res) {
        const detail = createAddDetailInfo(pack, qty)
        detail.countTime = new Date()
        allDetails.value.push(detail)
        updateList()
        countQtyEditRef.value.openEditPopupShowSeconds(detail, null)
      } else {
        scanPopupGetFocus()
      }
    })
  } else {
    const selectItem = items[0]
    // 已经扫描
    if (selectItem.scaned) {
      comMessageRef.value.showQuestionMessage(`包装【${result.label.packingNumber}】已经完成盘点,是否要编辑盘点结果?`, (res) => {
        if (res) {
          currentEditItem.value = selectItem
          countQtyEditRef.value.openEditPopup(selectItem, null)
        } else {
          scanPopupGetFocus()
        }
      })
    } else {
      // 未扫描，赋值
      selectItem.scaned = true
      selectItem.balanceQty = Number(qty)
      selectItem.handleQty = Number(qty)
      selectItem.packQty = pack.packQty
      selectItem.packUnit = pack.packUnit

      countQtyEditRef.value.openEditPopupShowSeconds(selectItem, null)
      selectItem.countTime = new Date()
      updateList()
    }
  }
}

const editConfirm = (qty, inventoryStatus, mode) => {
  // 编辑
  if (mode == 'edit') {
    currentEditItem.value.handleQty = qty
    currentEditItem.value.inventoryStatus = inventoryStatus
  }
  // 重新排序
  currentEditItem.value.countTime = new Date()
  updateList()
  scanPopupGetFocus()
}

const updateList = () => {
  allDetails.value.sort(compare('countTime')) // 按扫描信息排序
  initList()
  scanPopupLoseFocus()
  calcAllCount()
  calcScanCount()
}

const calcAllCount = () => {
  allCount.value = allDetails.value.length
}

const calcScanCount = () => {
  scanCount.value = allDetails.value.filter((r) => r.scaned === true).length
}

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

// 创建盘盈的明细
const createAddDetailInfo = (pack, qty) => {
  const detail = {
    id: jobContent.value.id, // 新增的明细
    scaned: true,
    countDetailNumber: '',
    ownerCode: '',
    packingNumber: pack.number,
    containerNumber: '',
    batch: pack.batch,
    inventoryStatus: 'OK',
    itemCode: pack.itemCode,
    itemName: pack.itemName,
    itemDesc1: pack.itemDesc1,
    itemDesc2: pack.itemDesc2,
    packQty: pack.packQty,
    packUnit: pack.packUnit,
    projectCode: '',
    recommendQty: Number(qty),
    qty: Number(qty),
    handleQty: Number(qty),
    uom: pack.uom,
    number: pack.number,
    remark: '',
    countQty: 0,
    balanceQty: Number(qty),
    fromLocationCode: fromLocationCode.value,
    creator: store.id,
    countTime: new Date()
  }
  return detail
}

const commit = () => {
  calcAllCount()
  calcScanCount()

  if (scanCount.value == allCount.value) {
    submitJob()
  } else if (scanCount.value < allCount.value) {
    // 扫描数量小于任务数量，判断是否允许部分提交
    if (jobContent.value.allowPartialComplete == 'TRUE') {
      // 提交
      comMessageRef.value.showQuestionMessage(`已经扫描[${scanCount.value}]总共[${allCount.value}],是否把未扫描的盘点数量设置为0?`, (res) => {
        if (res) {
          allDetails.value.forEach((item) => {
            if (!item.scaned) {
              item.scaned = true
              item.handleQty = 0
            }
          })
          submitJob()
        }
      })
    } else {
      // 不允许部分提交，提示
      comMessageRef.value.showErrorMessage('请完成扫描后,再进行提交<br>' + `已经扫描[${scanCount.value}]总共[${getTotalCount()}]`, (res) => {
        if (res) {
          openScanPopup()
        }
      })
    }
  }
}

const submitJob = () => {
  uni.showLoading({
    title: '提交中....',
    mask: true
  })
  const params = setParams()
  countJobSubmit(params)
    .then((res) => {
      uni.hideLoading()
      if (res.data) {
        showCommitSuccessMessage(`提交成功<br>生成盘点记录<br>${res.data}`)
      } else {
        showErrorMessage(`提交失败[${res.msg}]`)
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}

const setParams = () => {
  const subList = []
  const creator = store.id

  allDetails.value.forEach((item) => {
    if (item.scaned) {
      item.countQty = item.handleQty
    }
    subList.push(item)
  })

  jobContent.value.subList = subList
  jobContent.value.creator = creator
  return jobContent.value
}

const showMessage = (message) => {
  comMessageRef.value.showMessage(message, (res) => {
    if (res) {
      afterCloseMessage()
    }
  })
}
const showErrorMessage = (message) => {
  comMessageRef.value.showErrorMessage(message, (res) => {
    if (res) {
      afterCloseMessage()
    }
  })
}

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

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

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

const editItem = (item) => {
  currentEditItem.value = item
  countQtyEditRef.value.openEditPopup(this.currentEditItem, null)
}

const showCommitSuccessMessage = (hint) => {
  comMessageRef.value.showSuccessMessage(hint, (res) => {
    navigateBack(1)
  })
}
const getCountStageNameValue = (value) => {
  return getCountStageName(value)
}
const isOpenCount = (value) => {
  return value == 'TRUE' ? '明盘' : '盲盘'
}
</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;
}
</style>
