<template>
  <ElDialog
    v-model="visible"
    title="订单库存明细"
    width="1500px"
    :close-on-click-modal="false"
  >
    <div class="inventory-dialog-content">
      <div class="search-bar">
        <ElForm
          :inline="true"
          :model="filterForm"
          size="default"
          class="search-form"
        >
          <ElFormItem label="仓库">
            <ElSelect
              v-model="filterForm.warehouseId"
              placeholder="请选择仓库"
              clearable
              style="width: 150px"
            >
              <ElOption
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="库存SKU">
            <ElInput
              v-model="filterForm.warehouseSku"
              placeholder="请输入库存SKU"
              clearable
              style="width: 160px"
            />
          </ElFormItem>
          <ElFormItem label="款号">
            <ElInput
              v-model="filterForm.productNo"
              placeholder="请输入款号"
              clearable
              style="width: 150px"
            />
          </ElFormItem>
          <ElFormItem label="库存状况">
            <ElSelect
              v-model="filterForm.inventoryStatus"
              placeholder="请选择库存状况"
              clearable
              style="width: 160px"
            >
              <ElOption
                v-for="item in stockStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" @click="handleSearch">查询</ElButton>
            <ElButton type="success" @click="handleExport"> 导出 </ElButton>
          </ElFormItem>
        </ElForm>
      </div>

      <div v-loading="loading" class="inventory-table">
        <TableView
          :paginated-data="data"
          :columns="columns"
          serial-numberable
          selectionable
        />
      </div>

      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 50, 100, 200]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 10px auto 0"
        @size-change="onPageSizeChange"
        @current-change="onCurrentPageChange"
      />
    </div>
  </ElDialog>
</template>

<script setup lang="tsx">
import { ElMessage } from 'element-plus'
import type { WarehouseListData } from '@/types'
import type {
  FactoryOrderNewListData,
  OrderInventoryData,
} from '@/types/api/factoryOrderNew'
import TableView from '@/components/TableView.vue'
import usePageList from '@/utils/hooks/usePageList'
import {
  getOrderInventoryListApi,
  exportOrderInventoryApi,
} from '@/api/factoryOrderNew'
import BigNumber from 'bignumber.js'
const props = defineProps<{
  visible: boolean
  selectedRows: FactoryOrderNewListData[]
  warehouseList: WarehouseListData[]
}>()
const stockStatusOptions = [
  { label: '缺货商品', value: 1 },
  { label: '不缺货商品', value: 2 },
  { label: '未入过库的商品', value: 3 },
]

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
}>()

const visible = computed({
  get() {
    return props.visible
  },
  set(value: boolean) {
    emit('update:visible', value)
  },
})
watch(visible, (newVal) => {
  if (newVal) {
    filterForm.value = {
      warehouseId: undefined,
      warehouseSku: '',
      productNo: '',
      inventoryStatus: undefined,
    }
    refresh()
  }
})
const filterForm = ref({
  warehouseId: undefined as number | undefined,
  warehouseSku: '',
  productNo: '',
  inventoryStatus: undefined as string | undefined,
})

const buildQueryParams = () => ({
  orderIds: props.selectedRows.map((row) => row.id),
  warehouseId: filterForm.value.warehouseId || undefined,
  warehouseSku: filterForm.value.warehouseSku || undefined,
  productNo: filterForm.value.productNo || undefined,
  inventoryStatus: filterForm.value.inventoryStatus || undefined,
})

const {
  loading,
  currentPage,
  pageSize,
  total,
  data,
  onCurrentPageChange,
  onPageSizeChange,
  refresh,
} = usePageList<OrderInventoryData>({
  initPageSize: 20,
  initLoad: false,
  query: async (current, size) => {
    const res = await getOrderInventoryListApi(
      buildQueryParams(),
      current,
      size,
    )
    return res.data
  },
})

/** 可用数量 = 库存数量 - 占用数量 - 冻结数量 */
function getAvailableQuantity(row: OrderInventoryData): number {
  return new BigNumber(row.inventory ?? 0)
    .minus(row.occupyInventory ?? 0)
    .minus(row.freezeInventory ?? 0)
    .toNumber()
}
function getShortageQuantity(row: OrderInventoryData): number {
  const shortage = new BigNumber(row.salesNum ?? 0)
    .minus(getAvailableQuantity(row))
    .toNumber()
  return Math.max(0, shortage)
}

const columns = [
  {
    label: '图片',
    width: 70,
    align: 'center',
    render: (row: OrderInventoryData) => (
      <el-image
        src={row.variantImage ?? ''}
        style={{ width: '40px', height: '40px' }}
        preview-src-list={row.variantImage ? [row.variantImage] : []}
        preview-teleported
        fit="cover"
      />
    ),
  },
  {
    prop: 'warehouseName',
    label: '仓库名称',
    minWidth: 120,
  },
  {
    prop: 'locationCode',
    label: '库位',
    width: 100,
    align: 'center',
  },
  {
    prop: 'warehouseSku',
    label: '库存SKU',
    minWidth: 180,
    align: 'center',
  },
  {
    prop: 'productNo',
    label: '款号',
    width: 100,
    align: 'center',
  },
  {
    prop: 'skuName',
    label: '商品名称',
    minWidth: 140,
    showOverflowTooltip: true,
  },
  {
    label: '缺货数量',
    width: 100,
    align: 'right',
    render: (row: OrderInventoryData) => {
      const v = getShortageQuantity(row)
      if (v > 0) {
        return <span style="color: #f56c6c; font-weight: bold">{v}</span>
      }
      return <span>{v}</span>
    },
  },
  {
    prop: 'salesNum',
    label: '需求数量',
    width: 100,
    align: 'right',
    render: (row: OrderInventoryData) => {
      return (
        <span
          style={{
            color: row.inventoryStatus === 3 ? '#E6A23C' : '',
            fontWeight: row.inventoryStatus === 3 ? 'bold' : '',
          }}
        >
          {row.salesNum || 0}
        </span>
      )
    },
  },
  {
    prop: 'usableQuantity',
    label: '可用数量',
    width: 100,
    align: 'right',
    render: (row: OrderInventoryData) => {
      return <span>{getAvailableQuantity(row)}</span>
    },
  },
  {
    prop: 'inventory',
    label: '库存数量',
    width: 100,
    align: 'right',
  },
  {
    prop: 'occupyInventory',
    label: '占用数量',
    width: 100,
    align: 'right',
    render: (row: OrderInventoryData) => {
      return <span>{row.occupyInventory || 0}</span>
    },
  },
  {
    prop: 'freezeInventory',
    label: '冻结数量',
    width: 100,
    align: 'right',
  },
]

const handleSearch = () => {
  refresh()
}

const handleExport = async () => {
  try {
    await exportOrderInventoryApi(buildQueryParams())
    ElMessage.success('请求成功，请稍后到右上角[我的下载]中查看')
  } catch (e) {
    console.error(e)
  }
}
</script>

<style scoped lang="scss">
.inventory-dialog-content {
  display: flex;
  flex-direction: column;
  height: 68vh;
}

.search-bar {
  flex-shrink: 0;
  padding-bottom: 10px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0;

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

.inventory-table {
  flex: 1;
  overflow: hidden;
}
</style>
