import dayjs from "dayjs";
import { message } from "@/utils/message";
import {
  getOrderList,
  deleteOrder,
  submitOrder,
  syncToErp,
  completeOrder,
  cancelOrder
} from "@/api/replenishmentOrder";
import type { PaginationProps } from "@pureadmin/table";
import { onMounted, reactive, ref } from "vue";

export function useReplenishmentOrder() {
  const form = reactive<{
    orderNo?: string;
    deviceId?: string;
    shopId?: string;
    status?: number | "";
    startTime?: string;
    endTime?: string;
  }>({
    orderNo: "",
    deviceId: "",
    shopId: undefined,
    status: "",
    startTime: "",
    endTime: ""
  });
  const loading = ref(true);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const statusMap: Record<number, { text: string; type: string }> = {
    0: { text: "草稿", type: "info" },
    1: { text: "已提交", type: "warning" },
    2: { text: "已同步ERP", type: "primary" },
    3: { text: "已完成", type: "success" },
    4: { text: "已取消", type: "danger" }
  };

  const columns: TableColumnList = [
    {
      label: "补货单号",
      prop: "orderNo",
      minWidth: 160
    },
    {
      label: "设备ID",
      prop: "deviceId",
      minWidth: 120
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 110,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" };
        return <el-tag type={item.type}>{item.text}</el-tag>;
      }
    },
    {
      label: "总数量",
      prop: "totalQuantity",
      width: 90
    },
    {
      label: "总金额",
      prop: "totalAmount",
      minWidth: 100,
      formatter: ({ totalAmount }) =>
        totalAmount != null ? `¥${Number(totalAmount).toFixed(2)}` : "-"
    },
    {
      label: "供应商",
      prop: "supplierName",
      minWidth: 110,
      formatter: ({ supplierName }) => supplierName || "-"
    },
    {
      label: "仓库",
      prop: "warehouseName",
      minWidth: 110,
      formatter: ({ warehouseName }) => warehouseName || "-"
    },
    {
      label: "ERP单号",
      prop: "erpOrderNo",
      minWidth: 140,
      formatter: ({ erpOrderNo }) => erpOrderNo || "-"
    },
    {
      label: "创建人",
      prop: "creatorName",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "操作",
      fixed: "right",
      width: 280,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const params: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      if (form.orderNo) params.orderNo = form.orderNo;
      if (form.deviceId) params.deviceId = form.deviceId;
      if (form.shopId) params.shopId = form.shopId;
      if (form.status !== "" && form.status !== undefined)
        params.status = form.status;
      if (form.startTime) params.startTime = form.startTime;
      if (form.endTime) params.endTime = form.endTime;

      const { data } = await getOrderList(params);
      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 handleDelete(row) {
    try {
      const { code } = await deleteOrder(row.id);
      if (code === 200) {
        message("删除成功", { type: "success" });
        onSearch();
      }
    } catch (e) {
      // error handled by interceptor
    }
  }

  async function handleSubmit(row) {
    try {
      const { code } = await submitOrder(row.id);
      if (code === 200) {
        message("提交成功", { type: "success" });
        onSearch();
      }
    } catch (e) {
      // error handled by interceptor
    }
  }

  async function handleSyncErp(row) {
    try {
      const { code } = await syncToErp(row.id);
      if (code === 200) {
        message("同步ERP成功", { type: "success" });
        onSearch();
      }
    } catch (e) {
      // error handled by interceptor
    }
  }

  async function handleComplete(row) {
    try {
      const { code } = await completeOrder(row.id);
      if (code === 200) {
        message("完成补货单", { type: "success" });
        onSearch();
      }
    } catch (e) {
      // error handled by interceptor
    }
  }

  async function handleCancel(row) {
    try {
      const { code } = await cancelOrder(row.id);
      if (code === 200) {
        message("取消成功", { type: "success" });
        onSearch();
      }
    } catch (e) {
      // error handled by interceptor
    }
  }

  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,
    onSearch,
    resetForm,
    handleDelete,
    handleSubmit,
    handleSyncErp,
    handleComplete,
    handleCancel,
    handleSizeChange,
    handleCurrentChange
  };
}
