<template>
  <div class="waiting-restock">
    <div class="restock-filter">
      <ElForm :inline="true" :model="filterForm" size="default" class="search-form">
        <ElFormItem label="库存SKU">
          <ElInput
            v-model="filterForm.stockSku"
            placeholder="库存SKU"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="款号">
          <ElInput
            v-model="filterForm.styleNo"
            placeholder="款号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" @click="handleSearch">查询</ElButton>
          <ElButton @click="handleReset">重置</ElButton>
        </ElFormItem>
      </ElForm>
    </div>

    <div class="restock-table">
      <TableView
        v-loading="loading"
        :paginated-data="pageData"
        :columns="columns"
        serial-numberable
      >
        <template #skuImage="{ row }">
          <el-image
            v-if="row.skuImage"
            :src="row.skuImage"
            style="width: 50px; height: 50px"
            fit="contain"
            :preview-src-list="[row.skuImage]"
            preview-teleported
          />
        </template>
        <template #shortageQuantity="{ row }">
          <span style="color: #f56c6c; font-weight: bold">{{ row.shortageQuantity }}</span>
        </template>
        <template #availableQuantity="{ row }">
          <span :style="{ color: (row.availableQuantity || 0) < 0 ? '#f56c6c' : '' }">
            {{ row.availableQuantity }}
          </span>
        </template>
        <template #operation="{ row }">
          <ElButton type="primary" link size="small" @click="handleRestockCheck(row)">
            补货校验
          </ElButton>
        </template>
      </TableView>
    </div>

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

<script setup lang="ts">
import { computed, ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getRestockListApi, restockCheckApi } from '@/api/factoryOrderNew'
import type { RestockData } from '@/types/api/factoryOrderNew'
import type { CustomColumn } from '@/types/table'
import TableView from '@/components/TableView.vue'

const loading = ref(false)
const allData = ref<RestockData[]>([])
const currentPage = ref(1)
const pageSize = ref(50)
const total = ref(0)

const pageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return allData.value.slice(start, start + pageSize.value)
})

const columns: CustomColumn<RestockData>[] = [
  {
    key: 'warehouseName',
    prop: 'warehouseName',
    label: '仓库名称',
    minWidth: 100,
  },
  {
    key: 'skuImage',
    label: 'SKU图片',
    width: 100,
    align: 'center',
    slot: 'skuImage',
  },
  {
    key: 'productName',
    prop: 'productName',
    label: '商品名称',
    minWidth: 120,
    showOverflowTooltip: true,
  },
  { key: 'styleNo', prop: 'styleNo', label: '款号', minWidth: 80 },
  { key: 'stockSku', prop: 'stockSku', label: '库存SKU', minWidth: 120 },
  {
    key: 'shortageQuantity',
    prop: 'shortageQuantity',
    label: '缺货数量',
    minWidth: 90,
    align: 'center',
    slot: 'shortageQuantity',
  },
  {
    key: 'availableQuantity',
    prop: 'availableQuantity',
    label: '可用数量',
    minWidth: 90,
    align: 'center',
    slot: 'availableQuantity',
  },
  {
    key: 'stockQuantity',
    prop: 'stockQuantity',
    label: '库存数量',
    minWidth: 90,
    align: 'center',
  },
  {
    key: 'occupiedQuantity',
    prop: 'occupiedQuantity',
    label: '占用数量',
    minWidth: 90,
    align: 'center',
  },
  {
    key: 'operation',
    label: '操作',
    width: 120,
    align: 'center',
    fixed: 'right',
    slot: 'operation',
  },
]

const filterForm = reactive({
  stockSku: '',
  styleNo: '',
})

const loadData = async () => {
  loading.value = true
  try {
    const res = await getRestockListApi({
      stockSku: filterForm.stockSku || undefined,
      styleNo: filterForm.styleNo || undefined,
    })
    allData.value = res.data || []
    total.value = allData.value.length
  } catch (_e) {
    allData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const handleReset = () => {
  filterForm.stockSku = ''
  filterForm.styleNo = ''
  currentPage.value = 1
  loadData()
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentPageChange = (page: number) => {
  currentPage.value = page
}

const handleRestockCheck = async (row: RestockData) => {
  try {
    await restockCheckApi(row.id)
    ElMessage.success('补货校验成功')
    loadData()
  } catch (e) {
    const err = e as Error & { message?: string }
    ElMessage.error(err?.message || '补货校验失败')
  }
}

const refresh = () => {
  currentPage.value = 1
  loadData()
}

onMounted(() => {
  loadData()
})

defineExpose({ refresh })
</script>

<style scoped lang="scss">
.waiting-restock {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.restock-filter {
  flex-shrink: 0;
  padding-bottom: 10px;
}

.restock-table {
  flex: 1;
  overflow: auto;
}
.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>
