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 { onMounted, reactive, ref, toRaw } from "vue";

export function useSync() {
  const form = reactive<SearchFormProps>({
    syncType: "",
    status: undefined
  });
  const loading = ref(true);
  const syncing = ref(false);
  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 syncTypeMap = {
    device: "设备同步",
    product: "商品同步"
  };

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

  const columns: TableColumnList = [
    {
      label: "记录ID",
      prop: "id",
      width: 80
    },
    {
      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}>{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"
    }
  ];

  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 = data.total || 0;
      }
    } finally {
      loading.value = false;
    }
  }

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

  async function handleSyncDevices() {
    syncing.value = true;
    try {
      const { code, message: msg } = await syncDevices();
      if (code === 0) {
        message("设备同步成功", { type: "success" });
        onSearch();
        getStatistics();
      } else {
        message(msg || "同步失败", { type: "error" });
      }
    } finally {
      syncing.value = false;
    }
  }

  async function handleSyncProducts() {
    syncing.value = true;
    try {
      const { code, message: msg } = await syncProducts();
      if (code === 0) {
        message("商品同步成功", { type: "success" });
        onSearch();
        getStatistics();
      } else {
        message(msg || "同步失败", { type: "error" });
      }
    } finally {
      syncing.value = false;
    }
  }

  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,
    columns,
    dataList,
    statistics,
    pagination,
    onSearch,
    resetForm,
    handleSyncDevices,
    handleSyncProducts,
    handleViewLogs,
    handleSizeChange,
    handleCurrentChange
  };
}
