import type { PaginationProps } from "@pureadmin/table";
import { getDeviceInventoryStats } from "@/api/inventory";
import { getDeviceList } from "@/api/device";
import { type Ref, ref, reactive, onMounted } from "vue";
import type { InventorySearchForm, DeviceInventoryStats } from "./types";

export function useInventory(tableRef: Ref) {
  const form = reactive<InventorySearchForm>({
    deviceId: "",
    shopName: "",
    deviceName: ""
  });
  const formRef = ref();
  const dataList = ref<DeviceInventoryStats[]>([]);
  const loading = ref(true);
  const deviceOptions = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "门店设备",
      prop: "device_name",
      minWidth: 150
    },
    {
      label: "设备ID",
      prop: "device_id",
      minWidth: 130
    },
    {
      label: "门店名称",
      prop: "shop_name",
      minWidth: 150
    },
    {
      label: "剩余库存",
      prop: "remaining_stock",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag
          type={
            row.stock_status === "缺货"
              ? "danger"
              : row.stock_status === "低库存"
                ? "warning"
                : "success"
          }
        >
          {row.remaining_stock}
        </el-tag>
      )
    },
    {
      label: "标准库存",
      prop: "standard_stock",
      minWidth: 100
    },
    {
      label: "库存状态",
      prop: "stock_status",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag
          type={
            row.stock_status === "缺货"
              ? "danger"
              : row.stock_status === "低库存"
                ? "warning"
                : "success"
          }
        >
          {row.stock_status}
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 100,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };

      if (form.deviceId) searchParams.deviceId = form.deviceId;
      if (form.shopName) searchParams.shopName = form.shopName;
      if (form.deviceName) searchParams.deviceName = form.deviceName;

      const { data } = await getDeviceInventoryStats(searchParams);
      if (data) {
        dataList.value = (data.list || []) as DeviceInventoryStats[];
        pagination.total = Number(data.total) || 0;
      }
    } catch (error) {
      console.error("获取库存列表失败:", error);
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    pagination.currentPage = 1;
    onSearch();
  };

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function fetchDeviceOptions() {
    try {
      const { data } = await getDeviceList({ page: 1, pageSize: 1000 });
      deviceOptions.value = data.list || [];
    } catch (error) {
      console.error("获取设备列表失败:", error);
    }
  }

  onMounted(async () => {
    await fetchDeviceOptions();
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    deviceOptions,
    onSearch,
    resetForm,
    handleSizeChange,
    handleCurrentChange
  };
}
