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

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 shopOptions = ref<any[]>([]);
  const selectedRows = ref<any[]>([]);
  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: "已提交ERP", type: "warning" },
    2: { text: "已同步ERP", type: "primary" },
    3: { text: "已完成", type: "success" },
    4: { text: "已取消", type: "danger" }
  };

  const columns: TableColumnList = [
    { type: "selection", width: 45, fixed: "left" },
    { label: "补货单号", prop: "orderNo", minWidth: 160 },
    { label: "门店名称", prop: "shopName", minWidth: 120, formatter: ({ shopName }: any) => shopName || "-" },
    { label: "设备ID", prop: "deviceId", minWidth: 120 },
    { label: "设备名称", prop: "deviceName", minWidth: 120, formatter: ({ deviceName }: any) => deviceName || "-" },
    {
      label: "状态", prop: "status", minWidth: 110,
      cellRenderer: ({ row }: any) => {
        const s = statusMap[row.status] || { text: "未知", type: "info" };
        return <el-tag type={s.type}>{s.text}</el-tag>;
      }
    },
    { label: "总数量", prop: "totalQuantity", width: 90 },
    {
      label: "总金额", prop: "totalAmount", minWidth: 100,
      formatter: ({ totalAmount }: any) => totalAmount != null ? `¥${Number(totalAmount).toFixed(2)}` : "-"
    },
    { label: "供应商", prop: "supplierName", minWidth: 110, formatter: ({ supplierName }: any) => supplierName || "-" },
    { label: "仓库", prop: "warehouseName", minWidth: 110, formatter: ({ warehouseName }: any) => warehouseName || "-" },
    { label: "ERP单号", prop: "erpOrderNo", minWidth: 140, formatter: ({ erpOrderNo }: any) => erpOrderNo || "-" },
    { label: "创建人", prop: "creatorName", minWidth: 100 },
    {
      label: "创建时间", prop: "createTime", minWidth: 160,
      formatter: ({ createTime }: any) => createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    { label: "操作", fixed: "right", width: 300, 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;
      }
      selectedRows.value = [];
    } finally {
      loading.value = false;
    }
  }

  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    (form as any).shopId = undefined;
    pagination.currentPage = 1;
    onSearch();
  }

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

  async function fetchShopOptions() {
    try {
      const { data } = await getShopList({ page: 1, pageSize: 1000 });
      shopOptions.value = data?.list || [];
    } catch (e) { console.error("加载门店失败:", e); }
  }

  function handleSelectionChange(selection: any[]) {
    selectedRows.value = selection;
  }

  // ==================== 辅助函数 ====================

  /** 从 API 响应或异常中提取错误消息 */
  function getErrorMessage(err: any): string {
    if (err?.response?.data?.message) return err.response.data.message;
    if (err?.message) return err.message;
    return "操作失败";
  }

  // ==================== 单行操作 ====================

  async function handleDelete(row: any) {
    try {
      const { code, message: msg } = await deleteOrder(row.id);
      if (code === 200) { message("删除成功", { type: "success" }); onSearch(); }
      else { message(msg || "删除失败", { type: "error" }); }
    } catch (err) { message(getErrorMessage(err), { type: "error" }); }
  }

  async function handleSubmitToErp(row: any) {
    try {
      const submitRes = await submitOrder(row.id);
      if (submitRes.code !== 200) {
        message(submitRes.message || "提交失败", { type: "error" });
        return;
      }
      try {
        const syncRes = await syncToErp(row.id);
        if (syncRes.code !== 200) {
          message(syncRes.message || "ERP同步失败", { type: "error" });
        } else {
          message("已提交并同步ERP", { type: "success" });
        }
      } catch (err) {
        message("已提交，但ERP同步失败: " + getErrorMessage(err), { type: "warning" });
      }
      onSearch();
    } catch (err) { message(getErrorMessage(err), { type: "error" }); }
  }

  async function handleRetrySync(row: any) {
    try {
      const syncRes = await syncToErp(row.id);
      if (syncRes.code !== 200) {
        message(syncRes.message || "ERP同步失败", { type: "error" });
      } else {
        message("ERP同步成功", { type: "success" });
        onSearch();
      }
    } catch (err) { message(getErrorMessage(err), { type: "error" }); }
  }

  async function handleComplete(row: any) {
    try {
      const { code, message: msg } = await completeOrder(row.id);
      if (code === 200) { message("完成补货单", { type: "success" }); onSearch(); }
      else { message(msg || "完成失败", { type: "error" }); }
    } catch (err) { message(getErrorMessage(err), { type: "error" }); }
  }

  async function handleCancel(row: any) {
    try {
      const { code, message: msg } = await cancelOrder(row.id);
      if (code === 200) { message("取消成功", { type: "success" }); onSearch(); }
      else { message(msg || "取消失败", { type: "error" }); }
    } catch (err) { message(getErrorMessage(err), { type: "error" }); }
  }

  // ==================== 批量操作 ====================

  async function batchSubmitToErp() {
    const drafts = selectedRows.value.filter((r: any) => r.status === 0);
    if (drafts.length === 0) { message("请选择草稿状态的补货单", { type: "warning" }); return; }
    try {
      await ElMessageBox.confirm(`确认批量提交 ${drafts.length} 个补货单并同步ERP？`, "批量提交", {
        confirmButtonText: "确定", cancelButtonText: "取消", type: "warning"
      });
    } catch { return; }

    let ok = 0, fail = 0;
    const errors: string[] = [];
    for (const row of drafts) {
      try {
        const submitRes = await submitOrder(row.id);
        if (submitRes.code !== 200) {
          fail++;
          errors.push(`${row.orderNo || row.id}: ${submitRes.message || "提交失败"}`);
          continue;
        }
        try {
          const syncRes = await syncToErp(row.id);
          if (syncRes.code !== 200) {
            ok++;
            errors.push(`${row.orderNo || row.id}: ERP - ${syncRes.message || "失败"}`);
          } else { ok++; }
        } catch (syncErr) {
          ok++;
          errors.push(`${row.orderNo || row.id}: ERP - ${getErrorMessage(syncErr)}`);
        }
      } catch (err) {
        fail++;
        errors.push(`${row.orderNo || row.id}: ${getErrorMessage(err)}`);
      }
    }
    const resultMsg = `批量提交完成：${ok} 成功, ${fail} 失败`;
    if (errors.length > 0) {
      message(resultMsg + "\n" + errors.slice(0, 5).join("\n"), { type: fail > 0 ? "error" : "warning", duration: 5000 });
    } else {
      message(resultMsg, { type: "success" });
    }
    onSearch();
  }

  async function batchCancel() {
    const cancelable = selectedRows.value.filter((r: any) => r.status === 0 || r.status === 1);
    if (cancelable.length === 0) { message("请选择草稿或已提交状态的补货单", { type: "warning" }); return; }
    try {
      await ElMessageBox.confirm(`确认批量取消 ${cancelable.length} 个补货单？`, "批量取消", {
        confirmButtonText: "确定", cancelButtonText: "取消", type: "error"
      });
    } catch { return; }

    let ok = 0, fail = 0;
    const cancelErrors: string[] = [];
    for (const row of cancelable) {
      try {
        const { code, message: msg } = await cancelOrder(row.id);
        if (code === 200) { ok++; }
        else { fail++; cancelErrors.push(`${row.orderNo || row.id}: ${msg || "取消失败"}`); }
      } catch (err) { fail++; cancelErrors.push(`${row.orderNo || row.id}: ${getErrorMessage(err)}`); }
    }
    const cancelMsg = `批量取消完成：${ok} 成功, ${fail} 失败`;
    if (cancelErrors.length > 0) {
      message(cancelMsg + "\n" + cancelErrors.slice(0, 5).join("\n"), { type: fail > 0 ? "error" : "warning", duration: 5000 });
    } else {
      message(cancelMsg, { type: "success" });
    }
    onSearch();
  }

  async function batchDelete() {
    const drafts = selectedRows.value.filter((r: any) => r.status === 0);
    if (drafts.length === 0) { message("只能删除草稿状态的补货单", { type: "warning" }); return; }
    try {
      await ElMessageBox.confirm(`确认删除 ${drafts.length} 个草稿补货单？删除后不可恢复。`, "批量删除", {
        confirmButtonText: "确定", cancelButtonText: "取消", type: "error"
      });
    } catch { return; }

    let ok = 0, fail = 0;
    const delErrors: string[] = [];
    for (const row of drafts) {
      try {
        const { code, message: msg } = await deleteOrder(row.id);
        if (code === 200) { ok++; }
        else { fail++; delErrors.push(`${row.orderNo || row.id}: ${msg || "删除失败"}`); }
      } catch (err) { fail++; delErrors.push(`${row.orderNo || row.id}: ${getErrorMessage(err)}`); }
    }
    const delMsg = `批量删除完成：${ok} 成功, ${fail} 失败`;
    if (delErrors.length > 0) {
      message(delMsg + "\n" + delErrors.slice(0, 5).join("\n"), { type: fail > 0 ? "error" : "warning", duration: 5000 });
    } else {
      message(delMsg, { type: "success" });
    }
    onSearch();
  }

  // ==================== 初始化 ====================

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

  return {
    form, loading, columns, dataList, pagination, shopOptions, selectedRows, statusMap,
    onSearch, resetForm, handleSizeChange, handleCurrentChange,
    handleDelete, handleSubmitToErp, handleRetrySync, handleComplete, handleCancel,
    handleSelectionChange,
    batchSubmitToErp, batchCancel, batchDelete
  };
}
