<template>
  <div class="page card h-100 flex-gap-10 overflow-hidden flex">
    <div class="order-status">
      <div
        class="order-status-item"
        :class="{ 'order-status-item-active': currentStatus === 'unprocessed' }"
        @click="handleOrderStatusClick('unprocessed')"
      >
        <span>待处理</span>
        <span>({{ orderStatus.NotInStock }})</span>
      </div>
      <div
        class="order-status-item"
        :class="{ 'order-status-item-active': currentStatus === 'processed' }"
        @click="handleOrderStatusClick('processed')"
      >
        <span>已处理</span>
        <span>({{ orderStatus.alreadyInStock }})</span>
      </div>
    </div>
    <div class="order-content flex-1 flex-column overflow-hidden">
      <div class="header">
        <div class="header-filter-form">
          <ElForm
            class="search-form"
            :model="searchForm"
            :inline="true"
            label-width="70px"
          >
            <ElFormItem label="平台">
              <ElSelect
                v-model="searchForm.platform"
                placeholder="请选择"
                clearable
                filterable
                popper-class="customize-select-style"
                style="width: 140px"
              >
                <ElOption
                  v-for="(item, index) in platformJson"
                  :key="index"
                  :label="item.type"
                  :value="item.type"
                  style="width: 160px"
                >
                  <img
                    :src="`/images/icon/${item.icon.split('/').pop()}`"
                    style="height: 20px; margin: 5px 10px 0 0"
                  />
                  <span :title="item.type">{{ item.type }}</span>
                </ElOption>
              </ElSelect>
            </ElFormItem>

            <ElFormItem label="工艺">
              <LogisticsWaySelect
                v-model="searchForm.craftCode"
                :company-list="craftList"
                :start-width="'150px'"
                search-placeholder="搜索工艺名称"
                start-placeholder="请选择工艺名称"
              ></LogisticsWaySelect>
            </ElFormItem>

            <ElFormItem label="库存SKU">
              <ElInput
                v-model.trim="searchForm.thirdSkuCode"
                placeholder="库存SKU"
                clearable
                style="width: 140px"
              />
            </ElFormItem>
            <ElFormItem label="店铺单号">
              <ElInput
                v-model.trim="searchForm.shopNumber"
                placeholder="店铺单号"
                clearable
                style="width: 150px"
              />
            </ElFormItem>
            <ElFormItem label="批次号">
              <ElInput
                v-model.trim="searchForm.batchArrangeNumber"
                placeholder="批次号"
                clearable
                style="width: 140px"
              />
            </ElFormItem>

            <ElFormItem label="操作单号">
              <ElInput
                v-model.trim="searchForm.operationNo"
                placeholder="操作单号"
                clearable
                style="width: 140px"
              />
            </ElFormItem>

            <ElFormItem label="商品类型">
              <ProductTypeFilter
                v-model="searchForm.productMarkList"
                :options="productTypeGroups"
                :multiple="true"
                placeholder="请选择商品类型"
                width="140px"
              />
            </ElFormItem>

            <ElFormItem label="数量">
              <el-radio-group v-model="searchForm.multi">
                <el-radio-button :value="false" @click="toggleMulti(false)"
                  >单件</el-radio-button
                >
                <el-radio-button :value="true" @click="toggleMulti(true)"
                  >多件</el-radio-button
                >
              </el-radio-group>
            </ElFormItem>

            <ElFormItem>
              <ElPopover placement="bottom" width="600" trigger="click">
                <ElForm
                  ref="searchFormPopoverRef"
                  :model="searchForm"
                  size="default"
                  inline
                  label-width="100px"
                >
                  <ElFormItem style="width: 100%; padding-right: 40px">
                    <div style="width: 100%; display: flex; flex-wrap: nowrap">
                      <el-select
                        v-model="searchForm.timeType"
                        clearable
                        :teleported="false"
                        placeholder="时间类型"
                        style="flex: 1; margin-right: 10px"
                      >
                        <el-option :value="1" label="创建时间"></el-option>
                        <el-option :value="2" label="确认时间"></el-option>
                        <el-option :value="3" label="完成时间"></el-option>
                      </el-select>
                      <el-date-picker
                        v-model="dateRange"
                        :teleported="false"
                        :default-time="[
                          new Date(0, 0, 0, 0, 0, 0),
                          new Date(0, 0, 0, 23, 59, 59),
                        ]"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        type="datetimerange"
                        style="width: 280px"
                        :shortcuts="pickerOptions.shortcuts"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        clearable
                      />
                    </div>
                  </ElFormItem>
                  <ElFormItem label="订单号">
                    <ElInput
                      v-model.trim="searchForm.factoryOrderNumber"
                      placeholder="订单号"
                      clearable
                      style="width: 150px"
                    />
                  </ElFormItem>
                  <ElFormItem label="客户">
                    <el-select
                      v-model="searchForm.userMark"
                      clearable
                      filterable
                      :teleported="false"
                      style="width: 150px"
                      placeholder="客户"
                    >
                      <el-option
                        v-for="item in userMarkList"
                        :key="item"
                        :value="item"
                        :label="item"
                      ></el-option>
                    </el-select>
                  </ElFormItem>
                  <ElFormItem label="Variant SKU">
                    <ElInput
                      v-model.trim="searchForm.sku"
                      placeholder="Variant SKU"
                      clearable
                      style="width: 150px"
                    />
                  </ElFormItem>
                  <ElFormItem label="款号">
                    <ElInput
                      v-model.trim="searchForm.supplierProductNo"
                      placeholder="款号"
                      clearable
                      style="width: 150px"
                    />
                  </ElFormItem>
                  <ElFormItem label="物流跟踪号">
                    <ElInput
                      v-model.trim="searchForm.trackingNumber"
                      placeholder="物流跟踪号"
                      clearable
                      style="width: 150px"
                    />
                  </ElFormItem>
                  <ElFormItem label="物流类型">
                    <ElSelect
                      v-model="searchForm.shipmentType"
                      placeholder="物流类型"
                      clearable
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(item, index) in [
                          '自有物流',
                          '九猫统筹物流',
                          '自提',
                        ]"
                        :key="index"
                        :value="index"
                        :label="item"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem label="客户标签">
                    <ElSelect
                      v-model="searchForm.tagsIdArr"
                      placeholder="请选择客户标签"
                      clearable
                      filterable
                      multiple
                      collapse-tags
                      collapse-tags-tooltip
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="item in customTagList"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem label="自有物流公司">
                    <ElSelect
                      v-model="searchForm.logisticsCompanyCode"
                      placeholder="请选择"
                      clearable
                      filterable
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(item, index) in allCodelist"
                        :key="index"
                        :value="item.code"
                        :label="item.basicsName"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem label="规范素材">
                    <ElSelect
                      v-model="searchForm.newStandard"
                      placeholder="请选择"
                      clearable
                      filterable
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(_, index) in ['否', '是']"
                        :key="index"
                        :value="index"
                        :label="index === 0 ? '否' : '是'"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                </ElForm>
                <template #reference>
                  <el-button
                    type="warning"
                    @click="searchVisible = !searchVisible"
                  >
                    <el-icon v-if="searchVisible">
                      <CaretTop />
                    </el-icon>
                    <el-icon v-else>
                      <CaretBottom />
                    </el-icon>
                  </el-button>
                </template>
              </ElPopover>
            </ElFormItem>

            <ElFormItem>
              <ElButton type="primary" @click="search"> 查询 </ElButton>
              <ElButton @click="reset"> 重置 </ElButton>
            </ElFormItem>
          </ElForm>
        </div>
      </div>
      <div class="operation-list">
        <span v-if="currentStatus === 'unprocessed'" class="item">
          <ElButton type="primary" @click="handleEmbryoInStock"
            >胚衣入库</ElButton
          >
        </span>
        <span v-if="currentStatus === 'unprocessed'" class="item">
          <ElButton type="success" @click="handleProductionCompleteInStock"
            >生产完成入库</ElButton
          >
        </span>
      </div>
      <div class="card-content">
        <CardLayout
          ref="cardLayoutRef"
          :query-payload="getQueryPayload()"
          :fetch-list="fetchCardList"
          @selection-change="handleCardSelectionChange"
          @view-detail="handleViewDetail"
        />
      </div>
    </div>
  </div>
  <FastProduction
    v-model:detail-visible="detailVisible"
    :dialog-title="dialogTitle"
    :is-new-order="true"
    :detail-data="detailData"
    :fast-key="fastKey"
    :default-auto-sure="true"
    :show-operation-no-row="true"
    not-found-message="操作单不存在"
    pending-order-label="操作单号"
    please-scan-tip="请扫码操作单号"
    search-input-audio-tip="请录入操作单号"
    :history-storage-key="fastHistoryStorageKey"
    tracking-placeholder="扫描枪输入操作单号"
    :query-api="getOperationByNo"
    :complete-api="completeOperationById"
    @on-success="handleFastProductionSuccess"
    @close="fastClose"
  />
  <ReceiptProductDialog
    ref="receiptProductDialogRef"
    v-model:visible="receiptDialogVisible"
    v-model:user-mark="receiptUserMark"
    v-model:select-sku="receiptSelectSku"
    title="创建入库单"
    :disable-warehouse="true"
    :show-user-mark-filter="false"
    :show-query-button="false"
    :show-batch-add-button="false"
    :show-import-button="false"
    :edit-form="receiptEditForm"
    :rules="receiptRules"
    :warehouse-list="warehouseList"
    :other-purchase-data="otherPurchaseData"
    :location-list="locationList"
    :user-mark-list="receiptUserMarkList"
    :sku-data="skuData"
    :filter-sku-data="filterSkuData"
    @warehouse-change="handleReceiptWarehouseChange"
    @selection-change="handleReceiptProductSelectionChange"
    @set-cost-price="setCostPrice"
    @location-change="handleReceiptLocationChange"
    @update:remark="updateReceiptRemark"
    @update:warehouse-id="updateReceiptWarehouseId"
    @delete="deleteReceiptProducts"
    @save="handleReceiptSave"
  />
  <!-- 快捷入库 -->
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue'
import CardLayout from '../factoryOrderNew/component/CardLayout.vue'
import platformJson from '../../../json/platform.json'
import { useOrderDictionaries } from '../factoryOrderNew/hooks/useOrderDictionaries'
import { operateOrderListData } from '@/types/api/factoryOrderNew'
import { getFactoryOrderNewOperateDetailApi } from '@/api/factoryOrderNew'
import {
  getCancelOrderProcessListApi,
  getCancelOrderProcessStateGroupMapApi,
  getOperationInfoByNoApi,
  completeDeliveryByCancelOrderProcessApi,
  getBySkuAndUserMarkAndInboundTypeApi,
} from '@/api/cancelOrderProcess'
import type { CardLayoutListFetcher } from '@/types/api/factoryOrderNew'
import LogisticsWaySelect from '@/views/logistics/components/LogisticsWaySelect'
import { SearchForm } from '@/types/api/order/factoryOrderNew'
import ProductTypeFilter from '../factoryOrderNew/component/ProductTypeFilter.vue'
import { CaretBottom, CaretTop } from '@element-plus/icons-vue'
import { normalizeProductMarkListForQuery } from '../factoryOrderNew/utils/productMarkQuery'
import FastProduction from '../components/FastProduction.vue'
import { ElButton } from 'element-plus'
import ReceiptProductDialog from '@/views/warehouse/components/ReceiptProductDialog.vue'
import { useValue } from '@/utils/hooks/useValue'
import {
  ILocation,
  InterProductList,
  InterskuList,
  InterWarehouseDetail,
} from '@/types/api/warehouse'
import { useReceiptProductDialog } from '@/views/warehouse/hooks/useReceiptProductDialog'
import {
  addInRecordApi,
  getBySkuAndUserMarkApi,
  getByWareHouseIdAndCodeApi,
  warehouseInfo,
  warehouseInfoGetAll,
} from '@/api/warehouse'
import type { CancelOrderProcessStateGroupMap } from '@/types/api/cancelOrderProcess'
import BigNumber from 'bignumber.js'

const cardLayoutRef = ref()

const fetchCardList: CardLayoutListFetcher = async (payload, current, size) => {
  const res = await getCancelOrderProcessListApi(
    payload,
    current,
    size,
    currentStatus.value === 'processed',
  )
  return res.data
}

const searchForm = ref<SearchForm>({})
const dateRange = ref<[string, string]>(['', ''])
const searchVisible = ref(false)
const pickerOptions = {
  shortcuts: [
    {
      text: '今日',
      value: () => {
        const start = new Date()
        start.setHours(0, 0, 0, 0)
        const end = new Date()
        end.setHours(23, 59, 59, 999)
        return [start, end]
      },
    },
    {
      text: '最近7天',
      value: () => {
        const end = new Date()
        end.setHours(23, 59, 59, 999)
        const start = new Date()
        start.setDate(start.getDate() - 6)
        start.setHours(0, 0, 0, 0)
        return [start, end]
      },
    },
    {
      text: '最近30天',
      value: () => {
        const end = new Date()
        end.setHours(23, 59, 59, 999)
        const start = new Date()
        start.setDate(start.getDate() - 29)
        start.setHours(0, 0, 0, 0)
        return [start, end]
      },
    },
  ],
}
const toggleMulti = (value: boolean) => {
  searchForm.value.multi = value
}
const getQueryPayload = () => {
  const { productMarkList, tagsIdArr, ...rest } = searchForm.value
  return {
    ...rest,
    ...normalizeProductMarkListForQuery(productMarkList),
    ...(Array.isArray(tagsIdArr) && tagsIdArr.length
      ? { tagsId: tagsIdArr.join(',') }
      : {}),
    startTime: dateRange.value?.[0] || null,
    endTime: dateRange.value?.[1] || null,
  }
}
const reset = () => {
  searchForm.value = {}
  dateRange.value = ['', '']
  searchVisible.value = false
  nextTick(() => {
    search()
  })
}
const loadOrderStatusCounts = async () => {
  try {
    const res = await getCancelOrderProcessStateGroupMapApi()
    if (res.code !== 200) return
    orderStatus.value = {
      alreadyInStock: res.data.alreadyInStock ?? 0,
      NotInStock: res.data.NotInStock ?? 0,
    }
  } catch (e) {
    console.error(e)
  }
}
const search = () => {
  cardLayoutRef.value?.clearSelection()

  nextTick(() => {
    cardLayoutRef.value?.refresh()
  })
}
const cardSelectList = ref<operateOrderListData[]>([])
const handleCardSelectionChange = (items: operateOrderListData[]) => {
  cardSelectList.value = items
}
const detailVisible = ref(false)
const fastKey = ref('')
const detailData = ref<Record<string, unknown>>({})
const handleViewDetail = async (item: operateOrderListData) => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await getFactoryOrderNewOperateDetailApi(item.id)
    if (res.code !== 200) return
    detailData.value = res.data
    fastKey.value = 'detail'
    detailVisible.value = true
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const getOperationByNo = (operationNo: string) =>
  getOperationInfoByNoApi(operationNo) as Promise<{ data?: unknown }>
const fastInboundType = ref(0)
const fastHistoryStorageKey = computed(() =>
  fastInboundType.value === 1
    ? 'historyCancelOrderProcessProductionCompleteInStock'
    : 'historyCancelOrderProcessEmbryoInStock',
)
const completeOperationById = (_: number[], detail: Record<string, unknown>) =>
  completeDeliveryByCancelOrderProcessApi({
    operationNo: detail.operationNo as string,
    warehouseId: detail.warehouseId as number,
    inboundType: fastInboundType.value,
  })
const handleFastProductionSuccess = () => {
  ElMessage.success('入库成功')
}
const fastClose = () => {
  detailVisible.value = false
  if (fastKey.value === 'detail') return
  search()
  loadOrderStatusCounts()
}
const {
  userMarkList,
  customTagList,
  allCodelist,
  craftList,
  productTypeGroups,
  loadAllDictionaries,
} = useOrderDictionaries()
const orderStatus = ref<CancelOrderProcessStateGroupMap>({
  alreadyInStock: 0,
  NotInStock: 0,
})
const currentStatus = ref<'processed' | 'unprocessed'>('unprocessed')
const handleOrderStatusClick = (status: 'processed' | 'unprocessed') => {
  currentStatus.value = status
  search()
}
const receiptDialogVisible = ref(false)
const receiptUserMark = ref(0)
const receiptSelectSku = ref('')
const otherPurchaseData = ref<InterProductList[]>([])
const [receiptEditForm, resetReceiptEditForm] = useValue<InterWarehouseDetail>({
  inNo: '',
  warehouseId: '',
  warehouseName: '',
  remark: '',
  factoryCode: '',
  factoryId: 0,
  productList: [],
})
const receiptRules = {
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
}
const batchUserMark = ref(0)
const importUserMark = ref(0)
const receiptUserMarkList = ref<
  { userId: number; userMark: string; userName: string }[]
>([{ userId: 0, userMark: '', userName: '' }])
const warehouseList = ref<warehouseInfo[]>([])
const locationList = ref<ILocation[]>([])
const otherReceiptSelection = ref<InterProductList[]>([])
const receiptProductDialogRef = ref()
const { skuData, setCostPrice, filterSkuData } = useReceiptProductDialog({
  editForm: receiptEditForm,
  otherPurchaseData,
  userMark: receiptUserMark,
  batchUserMark,
  importUserMark,
  selectSku: receiptSelectSku,
  userMarkList: receiptUserMarkList,
})
function mapInterskuToProduct(
  val: InterskuList,
  type: 'completeProduction' | 'embryoInStock',
): InterProductList {
  const warehouseSku = val.warehouseSku || val.sku || ''
  const skuNameVal = val.skuName || val.productName || ''
  let customerId: number | null = null
  if (val.customerId != null && val.customerId !== '') {
    const n = Number(val.customerId)
    if (!Number.isNaN(n)) customerId = n
  }
  if (type === 'embryoInStock') {
    const operationList = cardSelectList.value.filter(
      (r) => r.thirdSkuCode === val.warehouseSku,
    )
    val.buyStored = operationList ? operationList.length : 0
  }
  const amount = new BigNumber(val.buyStored ?? 0)
    .multipliedBy(val.costPrice ?? 0)
    .toFixed(2)
  val.totalPrice = Number(amount) as number
  return {
    skuImage: val.skuImage || val.image || '',
    warehouseSku,
    skuName: skuNameVal,
    productNo: val.productNo ?? null,
    locationCode: val.locationCode ?? '',
    locationId: val.locationId ?? null,
    costPrice: val.costPrice ?? null,
    buyStored: val.buyStored ?? null,
    totalPrice: val.totalPrice ?? null,
    currencyName: val.currencyName ?? null,
    currencyCode: val.currencyCode ?? null,
    customerId,
    customerName: val.customerName ?? null,
    userMark: val.userMark ?? null,
  }
}
const handleEmbryoInStock = async () => {
  if (cardSelectList.value.length !== 0) {
    handleEmbryoInStockByCard('embryoInStock')
  } else {
    handleEmbryoInFastStock(0)
  }
}
const dialogTitle = computed(() => {
  return fastKey.value === 'fastReceipt'
    ? fastInboundType.value === 1
      ? '生产完成-快捷入库'
      : '胚衣-快捷入库'
    : '查看详情'
})
const handleEmbryoInFastStock = (inboundType: number) => {
  fastInboundType.value = inboundType
  fastKey.value = 'fastReceipt'
  detailVisible.value = true
  detailData.value = {}
}
const handleEmbryoInStockByCard = async (
  type: 'completeProduction' | 'embryoInStock',
) => {
  let operationList
  if (type === 'completeProduction') {
    operationList = cardSelectList.value.filter((r) => r.inboundType !== 2)
    if (operationList.length === 0) {
      ElMessage.error('客户定制商品，不能入库!')
      return
    }
  } else {
    operationList = cardSelectList.value
  }
  fastInboundType.value = type === 'completeProduction' ? 1 : 0
  const firstWid = operationList[0].warehouseId
  if (operationList.some((r) => r.warehouseId !== firstWid)) {
    return ElMessage.error('请选择相同仓库的库存SKU！')
  }
  resetReceiptEditForm()
  otherPurchaseData.value = []
  receiptUserMark.value = 0
  receiptSelectSku.value = ''
  skuData.value = []
  otherReceiptSelection.value = []
  const userJson = localStorage.getItem('user')
  if (userJson) {
    try {
      const userData = JSON.parse(userJson)
      receiptEditForm.value.factoryCode = userData.factoryCode || ''
      receiptEditForm.value.factoryId = userData.factoryId || 0
    } catch {
      // ignore
    }
  }
  receiptEditForm.value.warehouseId = firstWid
  receiptEditForm.value.warehouseName = operationList[0].warehouseName as string
  const wh = warehouseList.value.find((w) => w.id == firstWid)
  if (wh) {
    receiptEditForm.value.warehouseName = wh.name
  }
  const loading = ElLoading.service({
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const skus = operationList.map((r) => r.thirdSkuCode as string)
    const res =
      type === 'embryoInStock'
        ? await getBySkuAndUserMarkApi(firstWid, skus.join(','), null)
        : await getBySkuAndUserMarkAndInboundTypeApi(
            operationList.map((r) => r.operationNo as string),
          )
    if (res.code !== 200) return
    otherPurchaseData.value = res.data.map((item: InterskuList) =>
      mapInterskuToProduct(item, type),
    )
    await fetchReceiptLocationList('')
    const listRes = await warehouseInfoGetAll()
    warehouseList.value = listRes.data || []
    receiptDialogVisible.value = true
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const fetchReceiptLocationList = async (query: string) => {
  if (!receiptEditForm.value.warehouseId) return
  try {
    const res = await getByWareHouseIdAndCodeApi(
      receiptEditForm.value.warehouseId,
      query,
    )
    const result = res.data || []
    locationList.value = result.map((item: ILocation) => ({
      locationId: item.id,
      locationCode: item.locationCode,
    }))
  } catch (e) {
    console.error(e)
  }
}
const handleReceiptWarehouseChange = (val: number | string | undefined) => {
  const found = warehouseList.value.find(
    (item: warehouseInfo) => item.id === val,
  )
  receiptEditForm.value.warehouseName = found ? found.name : ''
}

const handleReceiptProductSelectionChange = (v: InterProductList[]) => {
  otherReceiptSelection.value = v
}

const handleReceiptLocationChange = (
  val: number | null | undefined,
  row: InterProductList,
) => {
  const found = locationList.value.find(
    (item: ILocation) => item.locationId === val,
  )
  row.locationCode = found ? found.locationCode : ''
}
const updateReceiptRemark = (value: string) => {
  receiptEditForm.value.remark = value
}

const updateReceiptWarehouseId = (value: number | string | undefined) => {
  receiptEditForm.value.warehouseId = value
}
const deleteReceiptProducts = () => {
  const arr = otherReceiptSelection.value
  if (arr.length === 0) return
  const idList = arr.map((v: InterProductList) => v.warehouseSku)
  otherPurchaseData.value = otherPurchaseData.value.filter(
    (item: InterProductList) => !idList.includes(item.warehouseSku),
  )
}
const handleReceiptSave = async () => {
  try {
    await receiptProductDialogRef.value?.validateForm()
  } catch {
    return
  }
  const arr = otherPurchaseData.value.map((item) => {
    const operationForReclaimList = cardSelectList.value.filter((r) =>
      fastInboundType.value === 1
        ? `${r.userMark}${r.variantSku}` === item.warehouseSku
        : r.thirdSkuCode === item.warehouseSku,
    )
    return {
      ...item,
      operationForReclaimList: operationForReclaimList,
    }
  })
  if (arr.length === 0) {
    ElMessage.error('请至少选择一条数据')
    return
  }
  for (let i = 0; i < arr.length; i++) {
    if (!arr[i].buyStored) {
      ElMessage.error('请输入入库数量')
      return
    }
    if (!arr[i].locationId) {
      ElMessage.error('请选择库位')
      return
    }
    const found = locationList.value.find(
      (item: ILocation) => item.locationId === arr[i].locationId,
    )
    if (!arr[i].locationCode) {
      arr[i].locationCode = found ? found?.locationCode : ''
    }
  }
  const params = {
    forNewProduct: fastInboundType.value === 1,
    ...receiptEditForm.value,
    productList: arr,
  }
  const loading = ElLoading.service({
    text: '保存中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await addInRecordApi(params)
    if (res.code !== 200) return
    if (res.data && Array.isArray(res.data) && res.data.length > 0) {
      ElMessageBox.alert(
        `操作单号: ${res.data.map((e: number) => e).join(',')}入库失败`,
        '提示',
        {
          type: 'error',
        },
      )
    } else {
      ElMessage.success('保存成功')
    }
    receiptDialogVisible.value = false
    search()
    loadOrderStatusCounts()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const handleProductionCompleteInStock = () => {
  // 客户定制的单子不能操作生产完成入库，提示：客户定制商品，不能入库!
  if (cardSelectList.value.length !== 0) {
    handleEmbryoInStockByCard('completeProduction')
  } else {
    handleEmbryoInFastStock(1)
  }
}

onMounted(() => {
  void loadAllDictionaries()
  void loadOrderStatusCounts()
  search()
})
</script>
<style scoped lang="scss">
.order-status {
  width: 180px;
}
.order-status-item {
  font-size: 14px;
  cursor: pointer;
  padding-left: 10px;
  height: 30px;
  line-height: 30px;
  color: #333;
  font-weight: 500;
  &:hover {
    background-color: #f5f7fa;
  }
  &.order-status-item-active {
    background-color: #f5f7fa;
    color: #409eff;
  }
}
.card-content {
  flex: 1;
  margin-top: 10px;
  overflow: hidden;
}
.header-filter-form {
  width: 100%;
  min-width: 0;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0;
  min-width: 0;

  :deep(.el-form-item) {
    margin-right: 10px;
    margin-bottom: 10px;
  }

  :deep(.el-form-item__content) {
    min-width: 0;
  }
}
</style>
