<template>
  <view class="p8">
    <navbar-back title="库位变更"></navbar-back>
    <uni-section type="line" title="库位信息修改" titleFontSize="15px"> </uni-section>
    <up-radio-group v-model="changeType" size="20px" @change="handleChangeType">
      <up-radio
        :customStyle="{ marginLeft: '8px' }"
        v-for="(item, index) in changeTypeOptions"
        :key="index"
        :label="item.label"
        :name="item.name"
      >
      </up-radio>
    </up-radio-group>
    <up-input
      v-model="changeCode"
      :placeholder="`请扫描${changeType == 'sample' ? '样品编号' : '（原）库位码'}`"
      prefixIcon="scan"
      fontSize="16"
      prefixIconStyle="font-size: 30px;"
      @confirm="getSampleList()"
    >
    </up-input>
    <up-input
      v-if="changeCode !== '' && sampleList.length > 0"
      class="mt20"
      v-model="targetLocation"
      placeholder="请扫描变更后库位码"
      prefixIcon="scan"
      fontSize="16"
      prefixIconStyle="font-size: 30px;"
    >
    </up-input>

    <uni-section v-if="sampleList.length > 0" type="line" title="样品及当前归库信息" titleFontSize="15px">
      <template #right> <up-text type="error" size="18" bold :text="sampleList.length"></up-text></template>
      <scroll-view style="height: 43vh" scroll-y scroll-with-animation>
        <uni-card v-for="item in sampleList">
          <view
            >样品名称：<text>{{ item.sampleName }}</text></view
          >
          <view class="mt4"
            >归库编码：<text>{{ item.sampleReturnCode }}</text></view
          >
          <view class="mt4"
            >归库时间：<text>{{ nx.$dayjs(item.returnTime).format('YYYY-MM-DD HH:mm:ss') }}</text></view
          >
          <view class="mt4"
            >样品库名称：<text>{{ item.warehouseName }}</text></view
          >
          <view class="mt4"
            >(原)库位码：<text>{{ item.warehouseLocationCode }}</text></view
          >
        </uni-card>
      </scroll-view>
    </uni-section>
    <up-button
      v-if="targetLocation"
      :loading="btnLoading"
      class="mt20"
      type="primary"
      style="width: 50%"
      text="提交"
      @click="handleSubmit"
    ></up-button>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, toRefs, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { debounce } from 'lodash'
import nx from '@/nx'

const changeType = ref('sample')
const changeTypeOptions = reactive([
  {
    name: 'sample',
    label: '按样品变更'
  },
  {
    name: 'warehouseLocation',
    label: '按库位变更'
  }
])
let targetLocation = ref('')
let changeCode = ref('')
let sampleList = ref([])

watch(changeCode, newVal => {
  if (newVal === '') {
    sampleList.value = []
    targetLocation.value = ''
    isFirstInput.value = true
  }
})
async function getSampleList() {
  if (changeCode.value === '') return
  let params = { pageSize: 999, pageNo: 1, returnStatus: 'completed' }
  if (changeType.value === 'sample') {
    params.sampleReturnCode = changeCode.value
  } else {
    params.warehouseLocationCode = changeCode.value
  }
  const { list } = await nx.$api.sampleWarehouse.queryReturnToStockSample(params)
  sampleList.value = list
  if (list.length === 0) {
    uni.showToast({ title: '未查询到该样品信息', icon: 'none' })
    isFirstInput.value = true
  } else {
    isFirstInput.value = false
  }
}
const btnLoading = ref(false)
async function handleSubmit() {
  let params = {
    actionWay: changeType.value,
    targetLocation: targetLocation.value
  }
  if (changeType.value === 'sample') {
    params.sampleReturnCode = changeCode.value
  } else {
    params.warehouseLocationCode = changeCode.value
  }
  btnLoading.value = true
  await nx.$api.sampleWarehouse.execChangeLocation(params).finally(() => {
    btnLoading.value = false
  })
  uni.showToast({ title: '变更成功', icon: 'none' })
  handleReset()
}
function handleChangeType(e) {
  handleReset()
}
let isFirstInput = ref(true)
const { scanQRInfo } = toRefs(nx.$store('biz'))
watch(scanQRInfo, newVal => {
  debouncedHandleScan(newVal)
})
const debouncedHandleScan = debounce(val => {
  if (!val) return
  scanQRInfo.value = ''
  if (nx.$router.getCurrentPage().route !== 'pages/sampleWarehouse/execChangeLocation/index') return
  try {
    const isJson = nx.$helper.isJsonString(val)
    if (isFirstInput.value) {
      handleFirstScan(val, isJson)
    } else {
      handleSecondScan(val, isJson)
    }
  } catch (error) {
    uni.showToast({ title: '扫码内容解析失败', icon: 'none' })
  }
}, 300)
function handleFirstScan(rawValue, isJson) {
  if (changeType.value === 'sample') {
    // 按样品变更：首扫应为纯字符串（样品编号）
    if (isJson) {
      isFirstInput.value = true
      uni.showToast({ title: '请先扫描样品编号', icon: 'none' })
      return
    } else {
      changeCode.value = rawValue
    }
  } else {
    // 按库位变更：首扫应为 JSON（原库位码）
    if (!isJson) {
      isFirstInput.value = true
      uni.showToast({ title: '请先扫描（原）库位码', icon: 'none' })
      return
    } else {
      const codeObj = JSON.parse(rawValue)
      changeCode.value = codeObj.code
    }
  }
  getSampleList()
}
function handleSecondScan(rawValue, isJson) {
  // 第二次扫描必须是 JSON（目标库位码）
  if (!isJson) {
    uni.showToast({ title: '请扫描变更后库位码', icon: 'none' })
    return
  }
  const codeObj = JSON.parse(rawValue)
  targetLocation.value = codeObj.code
}
onShow(() => {
  scanQRInfo.value = ''
})

function handleReset() {
  targetLocation.value = ''
  changeCode.value = ''
  sampleList.value = []
  btnLoading.value = false
  isFirstInput.value = true
}
</script>

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