<template>
  <div
    class="out-of-stock-statistics-page flex-column card h-100 overflow-hidden"
  >
    <div class="header-filter-form">
      <ElForm v-enter-submit="search" :inline="true">
        <ElFormItem label="缺货仓库">
          <ElSelect
            v-model="searchForm.warehouseId"
            style="width: 180px"
            placeholder="请选择仓库"
          >
            <ElOption
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="库存SKU">
          <ElInput
            v-model="searchForm.warehouseSku"
            clearable
            style="width: 180px"
            placeholder="请输入库存SKU"
          ></ElInput>
        </ElFormItem>
        <ElFormItem label="款号">
          <ElInput
            v-model="searchForm.productNo"
            clearable
            style="width: 180px"
            placeholder="请输入款号"
          ></ElInput>
        </ElFormItem>
        <ElFormItem label="商品名称">
          <ElInput
            v-model="searchForm.skuName"
            clearable
            style="width: 180px"
            placeholder="请输入商品名称"
          ></ElInput>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" @click="search"> 查询 </ElButton>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="success" @click="exportData"> 导出 </ElButton>
        </ElFormItem>
      </ElForm>
    </div>
    <div class="table-content flex-1 flex-column overflow-hidden">
      <div v-loading="loading" class="table-list flex-1 overflow-hidden">
        <TableView
          :selectionable="true"
          :serial-numberable="true"
          :paginated-data="tableData"
          :columns="tableColumns"
          @selection-change="handleSelectionChange"
        >
        </TableView>
      </div>
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[50, 100, 200, 300, 500]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 10px auto 0; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></ElPagination>
    </div>
  </div>
  <ElDialog
    v-model="exportVisible"
    title="导出选项"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="exportForm" label-width="80px">
      <el-form-item label="" prop="resource">
        <el-radio-group v-model="exportForm.resource">
          <el-radio label="currentPage">导出本页</el-radio>
          <el-radio label="selectedRows">导出选中</el-radio>
          <el-radio label="all">全部</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportVisible = false">取消</el-button>
        <el-button
          :loading="exportLoading"
          type="primary"
          @click="submitExportForm"
          >确认</el-button
        >
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="tsx">
import { computed, ref, onMounted } from 'vue'
import TableView from '@/components/TableView.vue'
import usePageList from '@/utils/hooks/usePageList'
import { loadWarehouseListApi } from '@/api/common'
import { WarehouseListData } from '@/types'
import { SearchForm, OutOfStockItem } from '@/types/api/supply/outOfStockStatistics'
import {
  getOutOfStockStatisticsListApi,
  exportOutOfStockStatisticsListApi,
} from '@/api/outOfStockStis'
import ImageView from '@/components/ImageView.vue'
import { filePath } from '@/api/axios'

const searchForm = ref<SearchForm>({
  warehouseId: '',
  warehouseSku: '',
  productNo: '',
  skuName: '',
})

const warehouseList = ref<WarehouseListData[]>([])
const exportVisible = ref(false)
const exportForm = ref({
  resource: null,
})
const exportLoading = ref(false)
// 表格列配置
const tableColumns = computed(() => {
  return [
    {
      label: '图片',
      prop: 'variantImage',
      width: 100,
      align: 'center',
      slot: 'image',
      render: (item: OutOfStockItem) => (
        <ImageView src={item.variantImage} width="40px" height="40px" />
      ),
    },
    {
      label: '缺货仓库',
      prop: 'warehouseName',
      width: 120,
      align: 'center',
    },
    {
      label: '库位',
      prop: 'locationCode',
      width: 120,
      align: 'center',
    },
    {
      label: '库存SKU',
      prop: 'warehouseSku',
      width: 150,
      align: 'center',
    },
    {
      label: '款号',
      prop: 'productNo',
      width: 120,
      align: 'center',
    },
    {
      label: '商品名称',
      prop: 'skuName',
      minWidth: 200,
      align: 'left',
    },
    {
      label: '币种',
      prop: 'currency',
      width: 80,
      align: 'center',
    },
    {
      label: '商品成本价',
      prop: 'costPrice',
      width: 120,
      align: 'right',
      render: (item: OutOfStockItem) => (
        <span>{item.costPrice ? item.costPrice.toFixed(2) : ''}</span>
      ),
    },
    {
      label: '缺货数量',
      prop: 'stockOutNum',
      width: 100,
      align: 'right',
    },
    {
      label: '销售数量',
      prop: 'salesNum',
      width: 100,
      align: 'right',
    },
    {
      label: '库存SPU',
      prop: 'warehouseSpu',
      width: 150,
      align: 'center',
    },
    {
      label: '最长缺货天数',
      prop: 'longestDelayDays',
      width: 120,
      align: 'right',
    },
    {
      label: '库存数量',
      prop: 'inventory',
      width: 100,
      align: 'right',
    },
    {
      label: '占用数量',
      prop: 'occupyInventory',
      width: 100,
      align: 'right',
    },
    {
      label: '冻结数量',
      prop: 'freezeInventory',
      width: 100,
      align: 'right',
    },
    {
      label: '采购未入数量',
      prop: 'purchaseNotInQuantity',
      width: 120,
      align: 'right',
    },
  ]
})

const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList<OutOfStockItem>({
  query: (page, pageSize) =>
    getOutOfStockStatisticsListApi(
      {
        ...searchForm.value,
      },
      page,
      pageSize,
    ).then((res) => res.data) as never,
  initLoad: false,
})

// 加载仓库列表
const loadWarehouseList = async () => {
  try {
    const res = await loadWarehouseListApi()
    if (res.code !== 200) return
    warehouseList.value = res.data || []
    searchForm.value.warehouseId = warehouseList.value[0].id
  } catch (e) {
    console.error(e)
  }
}
// 导出数据
const exportData = async () => {
  exportForm.value.resource = null
  exportVisible.value = true
}
const submitExportForm = async () => {
  if (!exportForm.value.resource) {
    return ElMessage.error('请选择导出类型')
  }
  const params: { exportAll: boolean; indexes?: number[] } = {
    exportAll: false,
    indexes: [],
  }
  if (exportForm.value.resource === 'currentPage') {
    params.exportAll = false
    params.indexes = undefined
  } else if (exportForm.value.resource === 'selectedRows') {
    if (!selectedRows.value.length) {
      return ElMessage.error('请选择要导出的数据')
    }
    params.exportAll = false
    params.indexes = selectedRows.value.map((el: OutOfStockItem) =>
      Number(el.sort),
    )
  } else if (exportForm.value.resource === 'all') {
    params.exportAll = true
    params.indexes = undefined
  }
  try {
    const res = await exportOutOfStockStatisticsListApi({
      ...searchForm.value,
      ...params,
    })
    window.open(filePath + res.message, '_blank')
    exportVisible.value = false
  } catch (e) {
    console.error(e)
  }
}

// 处理表格选择变化
const selectedRows = ref<OutOfStockItem[]>([])
const handleSelectionChange = (val: OutOfStockItem[]) => {
  selectedRows.value = val
}

onMounted(async () => {
  await loadWarehouseList()
  search()
})
</script>

<style lang="scss" scoped>
.out-of-stock-statistics-page {
  .header-filter-form {
    :deep(.el-form-item) {
      margin-right: 14px;
      margin-bottom: 10px;
    }
  }

  .table-content {
    .table-list {
      border: 1px solid #ebeef5;
      border-radius: 4px;
    }
  }
}
</style>
