<template>
  <ElDialog
    v-model="visible"
    title="等待补货统计"
    width="1500px"
    :close-on-click-modal="false"
  >
    <div class="waiting-restock">
      <div class="restock-filter">
        <ElForm
          :inline="true"
          :model="filterForm"
          size="default"
          class="search-form"
        >
          <ElFormItem label="仓库">
            <ElSelect
              v-model="filterForm.warehouseId"
              placeholder="请选择仓库"
              style="width: 180px"
              filterable
              clearable
            >
              <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: 150px"
            />
          </ElFormItem>
          <ElFormItem label="款号">
            <ElInput
              v-model="filterForm.productNo"
              placeholder="请输入款号"
              clearable
              style="width: 150px"
            />
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" @click="handleSearch">查询</ElButton>
            <ElButton @click="handleReset">重置</ElButton>
            <ElButton type="success" @click="handleExport">导出</ElButton>
          </ElFormItem>
        </ElForm>
      </div>

      <div v-loading="loading" class="restock-table">
        <TableView :paginated-data="data" :columns="columns" serial-numberable>
          <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="onPageSizeChange"
        @current-change="onCurrentPageChange"
      />
    </div>
  </ElDialog>
</template>

<script setup lang="tsx">
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { loadWarehouseListApi } from '@/api/common'
import {
  getRestockListApi,
  restockCheckApi,
  exportPodOrderOutOfStockApi,
} from '@/api/factoryOrderNew'
import { filePath } from '@/api/axios'
import type { WarehouseListData } from '@/types'
import type { RestockData } from '@/types/api/factoryOrderNew'
import TableView from '@/components/TableView.vue'
import usePageList from '@/utils/hooks/usePageList'

const props = defineProps<{
  visible: boolean
}>()

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

const visible = computed({
  get() {
    return props.visible
  },
  set(value: boolean) {
    emit('update:visible', value)
  },
})

const warehouseList = ref<WarehouseListData[]>([])
const filterForm = reactive({
  warehouseId: undefined as number | undefined,
  warehouseSku: '',
  productNo: '',
})

const loadWarehouseList = async () => {
  try {
    const res = await loadWarehouseListApi()
    if (res.code !== 200) return
    warehouseList.value = res.data || []
  } catch (e) {
    console.error(e)
  }
}

const buildQueryParams = () => ({
  warehouseId: filterForm.warehouseId || undefined,
  warehouseSku: filterForm.warehouseSku || undefined,
  productNo: filterForm.productNo || undefined,
})

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

watch(visible, async (newVal) => {
  if (newVal) {
    filterForm.warehouseId = undefined
    filterForm.warehouseSku = ''
    filterForm.productNo = ''
    await loadWarehouseList()
    refresh()
  }
})

const columns = [
  {
    label: '图片',
    width: 100,
    align: 'center',
    render: (row: RestockData) => {
      return (
        <el-image
          src={row.image ?? ''}
          style={{ width: '50px', height: '50px' }}
          previewSrcList={[row.image ?? '']}
          previewTeleported
        />
      )
    },
  },
  {
    prop: 'warehouseName',
    label: '仓库名称',
    width: 160,
    align: 'center',
  },
  {
    prop: 'locationCode',
    label: '库位',
    width: 160,
    align: 'center',
  },
  {
    prop: 'warehouseSku',
    label: '库存SKU',
    width: 200,
    align: 'center',
  },
  { prop: 'productNo', label: '款号', width: 130, align: 'center' },

  {
    prop: 'skuName',
    label: '商品名称',
    minWidth: 180,
    showOverflowTooltip: true,
  },

  {
    prop: 'usableInventory',
    label: '缺货数量',
    width: 90,
    align: 'right',
    render: (row: RestockData) => {
      const v = row.usableInventory ?? 0
      return (
        <span style="color: #f56c6c; font-weight: bold">{Math.abs(v)}</span>
      )
    },
  },
  {
    label: '可用数量',
    prop: 'usableInventory',
    width: 90,
    align: 'right',
  },
  {
    prop: 'inventory',
    label: '库存数量',
    width: 90,
    align: 'right',
  },
  {
    prop: 'occupyInventory',
    label: '占用数量',
    width: 90,
    align: 'right',
  },
  {
    key: 'operation',
    label: '操作',
    width: 120,
    align: 'center',
    fixed: 'right',
    slot: 'operation',
  },
]

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

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

const handleRestockCheck = async (row: RestockData) => {
  try {
    await ElMessageBox.confirm('确定补货校验吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await restockCheckApi(
      row.factoryId,
      row.warehouseSku ?? '',
      row.warehouseId,
    )
    if (res.code !== 200) return
    ElMessage.success('补货校验成功')
    refresh()
  } catch (e) {
    console.error(e)
  }
}

const handleReset = () => {
  filterForm.warehouseId = undefined
  filterForm.warehouseSku = ''
  filterForm.productNo = ''
  refresh()
}
</script>

<style scoped lang="scss">
.waiting-restock {
  display: flex;
  flex-direction: column;
  height: 68vh;
  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>
