<template>
  <navbar-back title="物资领用"></navbar-back>
  <view class="pl8 pr8 pt8">
    <view class="x-f">
      <text class="pl6">领用人：</text>
      <uni-data-select v-model="selectUserId" :localdata="range" placeholder="请选择领用人"></uni-data-select>
    </view>
    <view class="border-b p6 x-f"
      ><view class="pr16">库管员：</view><text>{{ userInfo.nickname }}</text></view
    >
    <up-input
      style="padding-top: 20px"
      border="bottom"
      v-model="materialCode"
      placeholder="请扫描需要领用的物料编号"
      prefixIcon="scan"
      fontSize="16"
      prefixIconStyle="font-size: 30px;"
      @confirm="getMaterialList"
    >
    </up-input>

    <uni-section v-if="materialList.length > 0" type="line" title="领用明细" titleFontSize="15px">
      <template #right> <up-text type="error" size="18" bold :text="materialList.length"></up-text></template>
      <scroll-view style="height: 55 vh" scroll-y scroll-with-animation>
        <uni-card margin="5px" v-for="item in materialList" class="sample-item">
          <template v-if="item.standardSolutionFlag !== 1">
            <view class="mt4">
              <view
                >物料编号：<text class="black">{{ item.code }}</text></view
              >
            </view>
            <view class="mt4">
              <view
                >物料名称：<text class="black">{{ item.name }}</text></view
              >
            </view>
            <view class="mt4"
              >规格型号：<text class="black">{{ item.modelNo }}</text></view
            >
            <view class="mt4"
              >单位：<text class="black">{{ item.unit }}</text></view
            >
          </template>
          <template v-else>
			  <view class="mt4">
			    <view
			      >溶液编号：<text class="black">{{ item.code }}</text></view
			    >
			  </view>
            <view class="mt4">
              <view
                >溶液名称：<text class="black">{{ item.name }}</text></view
              >
            </view>
            <view class="mt4">
              <view
                >规格：<text class="black">{{ item.modelNo }}</text></view
              >
            </view>
            <view class="mt4"
              >滴定系数：<text class="black">{{ item.titer }}</text></view
            >
            <view class="mt4"
              >配置人：<text class="black">{{ item.makeUser }}</text></view
            >
            <view class="mt4"
              >配置日期：<text class="black">{{ nx.$dayjs(item.makeDate).format('YYYY-MM-DD') }}</text></view
            >
            <view class="mt4"
              >有效期：<text class="black">{{ nx.$dayjs(item.dueDate).format('YYYY-MM-DD') }}</text></view
            >
            <view class="mt4"
              >备注：<text class="black">{{ item.solutionRemark }}</text></view
            >
          </template>
        </uni-card>
      </scroll-view>
      <up-button type="primary" :loading="btnLoading" style="width: 50%" text="提交" @click="handleSubmit"></up-button>
    </uni-section>
  </view>
</template>

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

const btnLoading = ref(false)
let materialCode = ref('')
let materialList = ref([])
const range = ref([])
const userInfo = computed(() => nx.$store('user').userInfo)
const selectUserId = ref('')
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/material/outbound/index') return
  try {
    materialCode.value = val
    getMaterialList()
  } catch (error) {
    uni.showToast({
      title: '请扫描正确的物料编码',
      icon: 'none'
    })
  }
}, 300)
onShow(() => {
  scanQRInfo.value = ''
})

async function getMaterialList() {
  if (materialCode.value === '') return
  let params = {
    code: materialCode.value
  }
  const data = await nx.$api.material.queryMaterialInfo(params)
  if (!data) return uni.showToast({ title: '未查询到该物料信息', icon: 'none' })
  const existingCodes = new Set(materialList.value.map(item => item.id))
  if (existingCodes.has(data.id)) {
    return uni.showToast({ title: '该物料已存在，无需重复添加', icon: 'none' })
  }

  materialList.value.push(data)
}
async function handleSubmit() {
  if (selectUserId.value === '') {
    return uni.showToast({
      title: '请选择领取人',
      icon: 'none'
    })
  }
  btnLoading.value = true
  const selectUser = range.value.find(item => item.value === selectUserId.value)
  console.log(selectUser)

  let params = {
    businessType: '领用出库',
    businessTypeCode: 'receiveOutbound',
    applyUserId: selectUser.value,
    infomationIds: materialList.value.map(item => item.id)
  }
  await nx.$api.material.execMaterialOut(params).finally(() => {
    btnLoading.value = false
  })
  uni.showToast({
    title: '领取成功',
    icon: 'none'
  })
  handleReset()
}
function handleReset() {
  materialCode.value = ''
  materialList.value = []
  selectUserId.value = ''
}
onMounted(async () => {
  const data = await nx.$api.user.getAssignUserList()
  range.value = data.map(item => ({ text: item.nickname, value: item.id }))
})
</script>

<style lang="scss" scoped>
.sample-item {
  position: relative;
  pointer-events: none;
}
:deep(.uni-select__input-placeholder) {
  font-size: 16px;
}
</style>
