<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 === 'processed' }"
        @click="handleOrderStatusClick('processed')"
      >
        <span>已处理</span>
        <span>({{ orderStatus.processed }})</span>
      </div>
      <div
        class="order-status-item"
        :class="{ 'order-status-item-active': currentStatus === 'unprocessed' }"
        @click="handleOrderStatusClick('unprocessed')"
      >
        <span>未处理</span>
        <span>({{ orderStatus.unprocessed }})</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 === 'processed'" class="item">
          <ElButton type="primary" @click="handleEmbryoInStock"
            >胚衣入库</ElButton
          >
        </span>
        <span v-if="currentStatus === 'processed'" 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"
    :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="historyFactoryNewOrderFastReceipt"
    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 { 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 {
  completeDeliveryApi,
  getByOperationNoLogApi,
  getFactoryOrderNewOperateDetailApi,
} from '@/api/factoryOrderNew'
import { getCancelOrderProcessListApi } 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 { ResultInfoDataItem } from '@/types/api/order/common'
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'

const cardLayoutRef = ref()

const fetchCardList: CardLayoutListFetcher = async (payload, current, size) => {
  const res = await getCancelOrderProcessListApi(payload, current, size)
  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 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) =>
  getByOperationNoLogApi(operationNo) as Promise<{ data?: unknown }>
const completeOperationById = (ids: number[]) => completeDeliveryApi(ids)
const handleFastProductionSuccess = (data: ResultInfoDataItem[]) => {
  const result = data[0]
  if (!result.status) {
    ElMessageBox.alert(
      `操作单号 ${result.factoryOrderNumber} ${result.message}`,
      '提示',
      {
        type: 'error',
      },
    )
    return
  }
}
const fastClose = () => {
  detailVisible.value = false
  if (fastKey.value === 'detail') return
  search()
}
const {
  userMarkList,
  customTagList,
  allCodelist,
  craftList,
  productTypeGroups,
  loadAllDictionaries,
} = useOrderDictionaries()
const orderStatus = ref<{
  processed: number
  unprocessed: number
}>({
  processed: 0,
  unprocessed: 0,
})
const currentStatus = ref<'processed' | 'unprocessed'>('processed')
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): 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
  }
  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: null,
    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()
  } else {
    handleEmbryoInFastStock()
  }
}
const handleEmbryoInFastStock = async () => {
  fastKey.value = 'fastReceipt'
  detailVisible.value = true
  detailData.value = {}
}
const handleEmbryoInStockByCard = async () => {
  const firstWid = cardSelectList.value[0].warehouseId
  if (cardSelectList.value.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 = cardSelectList.value[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 = cardSelectList.value.map((r) => r.thirdSkuCode as string)
    const res = await getBySkuAndUserMarkApi(firstWid, skus.join(','), null)
    if (res.code !== 200) return
    otherPurchaseData.value = res.data.map((item: InterskuList) =>
      mapInterskuToProduct(item),
    )
    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
  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 = {
    ...receiptEditForm.value,
    productList: otherPurchaseData.value,
  }
  const loading = ElLoading.service({
    text: '保存中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    await addInRecordApi(params)
    ElMessage.success('保存成功')
    receiptDialogVisible.value = false
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const handleProductionCompleteInStock = () => {
  // 客户定制的单子不能操作生产完成入库，提示：客户定制商品，不能入库!
  if (cardSelectList.value.length !== 0) {
    handleEmbryoInStockByCard()
  } else {
    handleEmbryoInFastStock()
  }
}

onMounted(() => {
  void loadAllDictionaries()
  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>
