import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getStockRecords, getStockRecordDetail, cancelStockRecord } from "@/api/inventory";
import type { PaginationProps } from "@pureadmin/table";
import type { SearchFormProps } from "./types";
import { onMounted, reactive, ref } from "vue";

export function useStockRecords() {
  const form = reactive<SearchFormProps>({
    deviceId: "",
    stockerId: undefined,
    status: undefined
  });
  const loading = ref(true);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const detailVisible = ref(false);
  const detailLoading = ref(false);
  const detailRecord = ref<any>({});
  const detailItems = ref<any[]>([]);

  const statusMap = {
    1: { text: "进行中", type: "primary" },
    2: { text: "已完成", type: "success" },
    3: { text: "已取消", type: "info" }
  };

  const stockTypeMap = {
    1: "普通上货",
    2: "补货上货",
    3: "调拨上货"
  };

  const columns: TableColumnList = [
    {
      label: "记录ID",
      prop: "id",
      width: 80
    },
    {
      label: "设备ID",
      prop: "deviceId",
      width: 120
    },
    {
      label: "设备名称",
      prop: "deviceName",
      minWidth: 130
    },
    {
      label: "上货类型",
      prop: "stockType",
      width: 90,
      formatter: ({ stockType }) => stockTypeMap[stockType] || "未知"
    },
    {
      label: "上货员",
      prop: "stockerName",
      width: 90
    },
    {
      label: "电话",
      prop: "stockerPhone",
      width: 120
    },
    {
      label: "种类",
      prop: "totalItems",
      width: 60
    },
    {
      label: "数量",
      prop: "totalQuantity",
      width: 60
    },
    {
      label: "状态",
      prop: "status",
      width: 80,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" };
        return <el-tag type={item.type} size="small">{item.text}</el-tag>;
      }
    },
    {
      label: "创建时间",
      prop: "createTime",
      width: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "完成时间",
      prop: "endTime",
      width: 160,
      formatter: ({ endTime }) =>
        endTime ? dayjs(endTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      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.stockerId !== undefined) searchParams.stockerId = form.stockerId;
      if (form.status !== undefined) searchParams.status = form.status;

      const { data } = await getStockRecords(searchParams);
      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();
  }

  async function handleCancel(row) {
    const { code } = await cancelStockRecord(row.id);
    if (code === 200) {
      message("取消成功", { type: "success" });
      onSearch();
    }
  }

  async function handleViewDetail(row) {
    detailVisible.value = true;
    detailLoading.value = true;
    detailRecord.value = row;
    detailItems.value = [];
    try {
      const { data } = await getStockRecordDetail(row.id);
      if (data) {
        detailRecord.value = data;
        detailItems.value = data.items || [];
      }
    } catch {
      message("加载详情失败", { type: "error" });
    } finally {
      detailLoading.value = false;
    }
  }

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

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

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    statusMap,
    stockTypeMap,
    detailVisible,
    detailLoading,
    detailRecord,
    detailItems,
    onSearch,
    resetForm,
    handleCancel,
    handleViewDetail,
    handleSizeChange,
    handleCurrentChange
  };
}
