import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getCheckinList, getCheckinDetail, getCheckinStats, exportCheckinRecords } from "@/api/checkin";
import type { PaginationProps } from "@pureadmin/table";
import type { SearchFormProps } from "./types";
import { onMounted, reactive, ref, toRaw } from "vue";

export function useCheckin() {
  const form = reactive<SearchFormProps>({
    type: "",
    userId: undefined,
    shopId: undefined,
    startDate: "",
    endDate: "",
    status: ""
  });
  const loading = ref(true);
  const dataList = ref([]);
  const statistics = ref({
    total: 0,
    today: 0,
    pending: 0,
    synced: 0
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const typeMap = {
    inventory_tally: "理货盘点签到",
    delivery_replenish: "补货确认签到"
  };

  const statusMap = {
    pending: { text: "待同步", type: "warning" },
    synced: { text: "已同步", type: "success" },
    failed: { text: "同步失败", type: "danger" }
  };

  const columns: TableColumnList = [
    {
      label: "签到ID",
      prop: "id",
      width: 80
    },
    {
      label: "签到类型",
      prop: "checkinType",
      minWidth: 130,
      formatter: ({ checkinType }) => typeMap[checkinType] || checkinType
    },
    {
      label: "签到人",
      prop: "userName",
      minWidth: 100
    },
    {
      label: "门店",
      prop: "shopName",
      minWidth: 120
    },
    {
      label: "设备ID",
      prop: "deviceId",
      minWidth: 120
    },
    {
      label: "签到地址",
      prop: "address",
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      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: "checkinTime",
      minWidth: 160,
      formatter: ({ checkinTime }) =>
        checkinTime ? dayjs(checkinTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      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.type) searchParams.type = form.type;
      if (form.userId !== undefined) searchParams.userId = form.userId;
      if (form.shopId !== undefined) searchParams.shopId = form.shopId;
      if (form.startDate) searchParams.startDate = form.startDate;
      if (form.endDate) searchParams.endDate = form.endDate;
      
      const { data } = await getCheckinList(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 handleViewDetail(row) {
    const { data } = await getCheckinDetail(row.id);
    console.log("详情：", data);
  }

  async function handleExport() {
    const { data } = await exportCheckinRecords(toRaw(form));
    if (data) {
      message("导出成功", { type: "success" });
    }
  }

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

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

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

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

  return {
    form,
    loading,
    columns,
    dataList,
    statistics,
    pagination,
    onSearch,
    resetForm,
    handleViewDetail,
    handleExport,
    handleSizeChange,
    handleCurrentChange
  };
}
