<template>
  <view class="page-wraper">
    <view class="page-header">
      <view class="header_job_top">
        <job-top :dataContent="jobContent"></job-top>
        <view class="card_view">
          <text class="card_packing_code">盘点计划</text>
          <text class="card_content">{{ jobContent.planNumber }}</text>
        </view>
        <view v-for="(range, index) in dataContent.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>
      </view>
    </view>

    <view class="page-main">
      <view class="">
        <com-blank-view @goScan="showFromLocationPopup" v-if="detailSource.length == 0"></com-blank-view>
      </view>
      <scroll-view scroll-y="true" class="page-main-scroll">
        <uni-swipe-action ref="swipeAction">
          <uni-swipe-action-item @click="swipeClick($event, item)" :right-options="editRemoveOption">
            <!-- 	{{editRemoveOption}} -->
            <view class="detail-list" v-for="(item, index) in detailSource" :key="item.id">
              <view class="">
                <package-and-item-card :dataContent="item"></package-and-item-card>
              </view>
              <view class="split_line"></view>
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </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=""> </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 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" :allowEditStatus="editInventoryStatus" :isShowBalance="jobContent.isOpenCount == 'TRUE'"> </count-qty-edit>
    <comMessage ref="comMessage"></comMessage>
  </view>
</template>

<script>
import { getCountJobDetail, takeCountJob, cancleTakeCountJob, countJobSubmit } from '@/api/request2.js'

import { getCountScopeType } from '@/common/directory.js'

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

import { goHome, navigateBack, getPackingNumberAndBatch } from '@/common/basic.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'

export default {
  name: 'receipt_detail',
  components: {
    winScanButton,
    winScanPack,
    comCountDetailCard,
    // winScanPackAndLocation,
    winScanLocation,
    countQtyEdit,
    jobTop,
    comBlankView,
    PackageAndItemCard
  },
  data() {
    return {
      id: '',
      scanCount: 0,
      jobContent: {}, // 任务内容
      subList: [], // 接口返回的任务subList
      detailSource: [], // 绑定在页面上的数据源
      balance: {}, // 库存余额
      editInventoryStatus: false,
      package: {}, // 包装
      label: {}, // 标签
      currentEditItem: {},
      jobStatus: '',
      fromLocation: {},
      fromLocationCode: '',
      editRemoveOption: []
    }
  },
  onLoad(option) {
    this.id = option.id
    if (this.id != undefined) {
      // 新建的任务自动接收
      if (option.status == '1') {
        this.receive((callback) => {
          this.getDetail()
        })
      } else {
        this.getDetail()
      }
    }
    this.showFromLocationPopup()
    this.editRemoveOption = getEditRemoveOption()
  },
  // 返回首页
  onNavigationBarButtonTap(e) {
    if (e.index === 0) {
      goHome()
    }
  },
  // 拦截返回按钮事件
  onBackPress(e) {
    // 已经接收但是没提交任务
    if (e.from === 'backbutton') {
      if (this.jobStatus == '2') {
        // 取消承接任务
        cancleTakeCountJob(this.id)
          .then((res) => {
            uni.navigateBack()
          })
          .catch((error) => {
            uni.navigateBack()
          })
      } else {
        uni.navigateBack()
      }
      return true
    }
  },

  onPullDownRefresh() {
    // uni.stopPullDownRefresh();
  },

  mounted() {},
  methods: {
    // 接收
    receive(callback) {
      if (this.id != null) {
        takeCountJob(this.id)
          .then((res) => {
            callback()
          })
          .catch((error) => {
            this.showErrorMessage(error)
          })
      }
    },

    getDetail() {
      const that = this
      uni.showLoading({
        title: '加载中....',
        mask: true
      })
      getCountJobDetail(that.id)
        .then((res) => {
          uni.hideLoading()
          that.jobContent = res.data
          that.jobStatus = res.data.status
        })
        .catch((error) => {
          uni.hideLoading()
          this.showErrorMessage(error)
        })
    },

    showFromLocationPopup() {
      this.$nextTick(() => {
        this.$refs.scanLocationCode.openScanPopup()
      })
    },

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

      let range = countRange.find((r) => r.type == 'LOCATION_CODE')
      if (range != undefined) {
        if (!rang.value.includes(location.code)) {
          this.showErrorMessage(`库位代码【${location.code}】,不在盘点库位范围【${rangeValue}】内`)
          return
        }
      } else {
        range = countRange.find((r) => r.type == 'LOCATIONGROUP_CODE')
        if (range != undefined) {
          if (!rang.value.includes(location.locationGroupCode)) {
            this.showErrorMessage(`库位组代码【${location.locationGroupCode}】,不在盘点库位组范围【${rangeValue}】内`)
            return
          }
        } else {
          range = countRange.find((r) => r.type == 'AREA_CODE')
          if (range != undefined) {
            if (!rang.value.includes(location.areaCode)) {
              this.showErrorMessage(`库区代码【${location.areaCode}】,不在盘点库区范围【${rangeValue}】内`)
              return
            }
          } else {
            range = countRange.find((r) => r.type == 'WAREHOUSE_CODE')
            if (range != undefined) {
              if (!rang.value.includes(location.warehouseCode)) {
                this.showErrorMessage(`仓库代码【${location.warehouseCode}】,不在盘点仓库范围【${rangeValue}】内`)
                return
              }
            }
          }
        }
      }
      this.getFromLocationCode(location, code)
    },

    getFromLocationCode(location, code) {
      this.fromLocation = location
      this.fromLocationCode = code
      this.openScanPopup()
    },

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

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

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

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

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

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

    // 明盘
    getScanResult(result) {
      const that = this
      const { package } = result
      let detail = this.detailSource.find((r) => r.itemCode == package.itemCode && r.packingNumber == package.packingNumber && r.batch == package.batch && r.inventoryStatus == 'OK')
      if (detail == undefined) {
        detail = this.createDetailInfo(package)
        this.detailSource.push(detail)
      } else {
        const { index } = detail
        list.unshift(list.splice(index, 1)[0]) // 置顶
        // 提交
        this.showQuestionMessage('该箱码已经扫描,是否要编辑盘点明细?', (res) => {
          if (res) {
            this.edit(detail)
          }
        })
      }
    },

    // 创建盘盈的明细
    createDetailInfo(packInfo) {
      const detail = {
        scaned: true,
        // countDetailNumber: "",
        number: this.jobContent.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,
        countQty: packInfo.qty,
        uom: packInfo.uom,
        remark: '',
        locationCode: this.fromLocationCode,
        creator: this.$store.state.user.id,
        warehouseCode: this.fromLocation.warehouseCode,
        areaCode: this.fromLocation.areaCode,
        locationGroupCode: this.fromLocation.locationGroupCode
      }
      return detail
    },

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

    // 编辑盘点结果
    edit(item) {
      const that = this
      this.currentEditItem = item
      this.$refs.countQtyEdit.openEditPopup(item)
    },

    editConfirm(qty, inventoryStatus, mode) {
      const that = this
      // 编辑
      if (mode == 'edit') {
        this.currentEditItem.countQty = qty
        this.currentEditItem.qty = qty
        this.currentEditItem.inventoryStatus = inventoryStatus
      }
      this.scanPopupGetFocus()
    },

    editClose() {
      this.scanPopupGetFocus()
    },

    remove(item, index) {
      this.showQuestionMessage('是否要移除扫描信息?', (res) => {
        if (res) {
          this.dataContent.subList.splice(index, 1)
        }
      })
    },

    commit() {
      // if(this.detailSource.length==0)
      // {

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

    setParams() {
      const subList = []
      const creator = this.$store.state.user.id
      this.jobContent.subList = this.detailSource
      // this.jobContent.creator = creator;
      return this.jobContent
    },

    showMessage(message) {
      this.$refs.comMessage.showMessage(message, (res) => {
        if (res) {
          this.afterCloseMessage()
        }
      })
    },

    showErrorMessage(message) {
      this.$refs.comMessage.showErrorMessage(message, (res) => {
        if (res) {
          this.afterCloseMessage()
        }
      })
    },

    showScanMessage(message) {
      this.$refs.comMessage.showScanMessage(message)
    },

    showQuestionMessage(message, callback) {
      this.$refs.comMessage.showQuestionMessage(message, (res) => {
        callback(res)
      })
    },

    afterCloseMessage() {
      this.scanPopupGetFocus()
    },

    closeScanMessage() {
      this.scanPopupGetFocus()
    },

    editItem(item) {
      this.currentEditItem = item
      const detail = this.detailSource.find((r) => r.itemCode == item.itemCode)
      this.$refs.countQtyEdit.openEditPopup(item, detail.subList)
    },

    showCommitSuccessMessage(hint) {
      this.$refs.comMessage.showSuccessMessage(hint, (res) => {
        navigateBack(1)
      })
    },

    getCountScopeName(value) {
      const item = getCountScopeType(value)
      return item.label
    }
  }
}
</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>
