import dayjs from "dayjs";
import { message } from "@/utils/message";
import {
  syncDevices,
  syncProducts,
  getSyncRecords,
  getSyncLogs,
  getSyncStatistics
} from "@/api/sync";
import type { PaginationProps } from "@pureadmin/table";
import type { SyncModuleItem, SearchFormProps } from "./types";
import { onMounted, reactive, ref } from "vue";

export function useSync() {
  const form = reactive<SearchFormProps>({
    syncType: "",
    status: undefined
  });
  const loading = ref(true);
  const syncing = ref(false);
  const currentSyncKey = ref<string>("");
  const dataList = ref([]);
  const statistics = ref({
    totalSync: 0,
    todaySync: 0,
    successRate: 0,
    lastSyncTime: ""
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // ========== 同步模块配置 ==========
  const syncModules = ref<SyncModuleItem[]>([
    {
      key: "device",
      title: "设备同步",
      description: "从哈哈平台拉取设备列表，同步设备基本信息与状态",
      icon: "ri:computer-line",
      color: "#4f46e5",
      bgColor: "#eef2ff",
      active: true,
      lastSyncTime: "",
      lastSyncStatus: undefined,
      lastSyncCount: undefined,
      lastSuccessTime: ""
    },
    {
      key: "product",
      title: "商品同步",
      description: "从哈哈平台商家商品库拉取商品列表，同步商品信息与价格",
      icon: "ri:shopping-bag-3-line",
      color: "#059669",
      bgColor: "#ecfdf5",
      active: true,
      lastSyncTime: "",
      lastSyncStatus: undefined,
      lastSyncCount: undefined,
      lastSuccessTime: ""
    },
    // ========== 预留未来同步模块 ==========
    {
      key: "order",
      title: "订单同步",
      description: "从哈哈平台同步历史订单与交易流水数据",
      icon: "ri:file-list-3-line",
      color: "#d97706",
      bgColor: "#fffbeb",
      active: false,
      upcomingText: "即将上线"
    },
    {
      key: "shop",
      title: "门店同步",
      description: "从哈哈平台同步门店信息、营业时间与地理位置",
      icon: "ri:store-2-line",
      color: "#dc2626",
      bgColor: "#fef2f2",
      active: false,
      upcomingText: "即将上线"
    },
    {
      key: "coupon",
      title: "优惠券同步",
      description: "从哈哈平台同步优惠券模板与活动发放规则",
      icon: "ri:ticket-2-line",
      color: "#7c3aed",
      bgColor: "#f5f3ff",
      active: false,
      upcomingText: "规划中"
    },
    {
      key: "inventory",
      title: "库存同步",
      description: "从哈哈平台同步各设备实时库存与补货记录",
      icon: "ri:archive-2-line",
      color: "#0891b2",
      bgColor: "#ecfeff",
      active: false,
      upcomingText: "规划中"
    }
  ]);

  const syncTypeMap: Record<string, string> = {
    device: "设备同步",
    product: "商品同步",
    order: "订单同步",
    shop: "门店同步",
    coupon: "优惠券同步",
    inventory: "库存同步"
  };

  const statusMap: Record<number, { text: string; type: string }> = {
    1: { text: "进行中", type: "primary" },
    2: { text: "成功", type: "success" },
    3: { text: "失败", type: "danger" }
  };

  const columns: TableColumnList = [
    {
      label: "记录ID",
      prop: "id",
      width: 180
    },
    {
      label: "同步类型",
      prop: "syncType",
      minWidth: 100,
      formatter: ({ syncType }) => syncTypeMap[syncType] || syncType
    },
    {
      label: "总数量",
      prop: "totalCount",
      minWidth: 90
    },
    {
      label: "成功数",
      prop: "successCount",
      minWidth: 90
    },
    {
      label: "失败数",
      prop: "failedCount",
      minWidth: 90
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" };
        return <el-tag type={item.type as any}>{item.text}</el-tag>;
      }
    },
    {
      label: "操作人",
      prop: "operatorName",
      minWidth: 100
    },
    {
      label: "开始时间",
      prop: "startTime",
      minWidth: 160,
      formatter: ({ startTime }) =>
        startTime ? dayjs(startTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "耗时(s)",
      prop: "duration",
      minWidth: 90,
      formatter: ({ duration }) =>
        duration ? (duration / 1000).toFixed(2) : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 100,
      slot: "operation"
    }
  ];

  // ========== 同步执行映射 ==========
  const syncActionMap: Record<string, () => Promise<any>> = {
    device: syncDevices,
    product: syncProducts
  };

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

      if (form.syncType) searchParams.syncType = form.syncType;
      if (form.status !== undefined) searchParams.status = form.status;

      const { data } = await getSyncRecords(searchParams);
      if (data) {
        dataList.value = data.list || [];
        pagination.total = Number(data.total) || 0;
        // 更新模块卡片的最近同步信息
        updateModuleLastSync(data.list);
      }
    } finally {
      loading.value = false;
    }
  }

  /** 从记录列表更新模块卡片的最新状态 */
  function updateModuleLastSync(records: any[]) {
    if (!records || records.length === 0) return;
    for (const mod of syncModules.value) {
      if (!mod.active) continue;
      // 找到该模块最近一条成功记录的时间
      const successRecord = records.find((r: any) => r.syncType === mod.key && r.status === 2);
      if (successRecord) {
        mod.lastSuccessTime = successRecord.startTime;
      }
      const latestRecord = records.find((r: any) => r.syncType === mod.key);
      if (latestRecord) {
        mod.lastSyncTime = latestRecord.startTime;
        mod.lastSyncStatus = latestRecord.status;
        mod.lastSyncCount = latestRecord.totalCount;
      }
    }
  }

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

  /** 通用同步执行：根据模块 key 调用对应 API */
  async function handleSync(mod: SyncModuleItem) {
    if (!mod.active) return;
    const action = syncActionMap[mod.key];
    if (!action) {
      message(`同步功能「${mod.title}」暂未实现`, { type: "warning" });
      return;
    }

    currentSyncKey.value = mod.key;
    syncing.value = true;
    try {
      const { code, message: msg } = await action();
      if (code === 0 || code === 200) {
        message(`${mod.title}成功`, { type: "success" });
        onSearch();
        getStatistics();
      } else {
        message(msg || "同步失败", { type: "error" });
      }
    } finally {
      syncing.value = false;
      currentSyncKey.value = "";
    }
  }

  async function handleViewLogs(row) {
    const { data } = await getSyncLogs(row.id, { page: 1, pageSize: 100 });
    console.log("同步日志：", data);
  }

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

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

  async function getStatistics() {
    const { data } = await getSyncStatistics();
    if (data) {
      statistics.value = data;
    }
  }

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

  return {
    form,
    loading,
    syncing,
    currentSyncKey,
    columns,
    dataList,
    statistics,
    syncModules,
    syncTypeMap,
    statusMap,
    pagination,
    onSearch,
    resetForm,
    handleSync,
    handleViewLogs,
    handleSizeChange,
    handleCurrentChange
  };
}
