import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getInventoryLogs } from "@/api/inventory";
import { getDeviceList } from "@/api/device";
import { getProductList } from "@/api/product";
import type { PaginationProps } from "@pureadmin/table";
import type { SearchFormProps } from "./types";
import { onMounted, reactive, ref, toRaw } from "vue";

export function useInventoryLogs() {
  const form = reactive<SearchFormProps>({
    deviceId: "",
    productId: undefined,
    changeType: ""
  });
  const loading = ref(true);
  const dataList = ref([]);
  const deviceOptions = ref<any[]>([]);
  const productOptions = ref<any[]>([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "设备ID",
      prop: "deviceId",
      minWidth: 120
    },
    {
      label: "设备名称",
      prop: "deviceName",
      minWidth: 120
    },
    {
      label: "商品编码",
      prop: "productCode",
      minWidth: 120
    },
    {
      label: "商品名称",
      prop: "productName",
      minWidth: 150
    },
    {
      label: "变动类型",
      prop: "changeType",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const typeMap = {
          1: { text: "上货增加", type: "success" },
          2: { text: "销售减少", type: "danger" },
          3: { text: "调整增加", type: "warning" },
          4: { text: "调整减少", type: "warning" },
          5: { text: "盘点调整", type: "info" }
        };
        const item = typeMap[row.changeType] || { text: row.changeType, type: "info" };
        return <el-tag type={item.type}>{item.text}</el-tag>;
      }
    },
    {
      label: "变动数量",
      prop: "changeQuantity",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <span class={row.changeQuantity > 0 ? "text-success" : "text-danger"}>
          {row.changeQuantity > 0 ? "+" : ""}{row.changeQuantity}
        </span>
      )
    },
    {
      label: "变动前库存",
      prop: "beforeStock",
      minWidth: 100
    },
    {
      label: "变动后库存",
      prop: "afterStock",
      minWidth: 100
    },
    {
      label: "操作人",
      prop: "operatorName",
      minWidth: 100
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 150,
      showOverflowTooltip: true
    },
    {
      label: "操作时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const { data } = await getInventoryLogs({
        ...toRaw(form) as any,
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      });
      if (data) {
        dataList.value = data.list || [];
        pagination.total = Number(data.total) || 0;
      }
    } finally {
      loading.value = false;
    }
  }

  function 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);
    }
  }

  async function fetchProductOptions() {
    try {
      const { data } = await getProductList({ page: 1, pageSize: 1000 });
      productOptions.value = data.list || [];
    } catch (error) {
      console.error("获取商品列表失败:", error);
    }
  }

  onMounted(async () => {
    await Promise.all([fetchDeviceOptions(), fetchProductOptions()]);
    onSearch();
  });

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