import { ref, reactive, onMounted } from "vue";
import { getUserCouponList } from "@/api/user-coupon";
import dayjs from "dayjs";
import { ElTag } from "element-plus";

interface SearchFormProps {
  userId: string;
  couponCode: string;
  status: number | undefined;
}

interface PaginationProps {
  total: number;
  pageSize: number;
  currentPage: number;
  layout: string;
}

export function useUserCoupon() {
  const form = reactive<SearchFormProps>({
    userId: "",
    couponCode: "",
    status: undefined
  });

  const loading = ref(false);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    layout: "total, sizes, prev, pager, next, jumper"
  });

  type TagType = "success" | "primary" | "warning" | "info" | "danger";

  const statusMap: Record<number, { text: string; type: TagType }> = {
    0: { text: "未使用", type: "success" },
    1: { text: "已使用", type: "info" },
    2: { text: "已过期", type: "danger" }
  };

  const typeMap: Record<number, { text: string; type: TagType }> = {
    1: { text: "满减券", type: "primary" },
    2: { text: "折扣券", type: "success" },
    3: { text: "立减券", type: "warning" },
    4: { text: "商品券", type: "info" }
  };

  const columns = ref([
    {
      label: "优惠券码",
      prop: "couponCode",
      minWidth: 180
    },
    {
      label: "用户ID",
      prop: "userId",
      minWidth: 120
    },
    {
      label: "优惠券名称",
      prop: "couponName",
      minWidth: 150
    },
    {
      label: "类型",
      prop: "couponType",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const item = typeMap[row.couponType] || { text: "未知", type: "info" };
        return <ElTag type={item.type}>{item.text}</ElTag>;
      }
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" };
        return <ElTag type={item.type}>{item.text}</ElTag>;
      }
    },
    {
      label: "领取时间",
      prop: "receiveTime",
      minWidth: 160,
      formatter: ({ receiveTime }) => receiveTime ? dayjs(receiveTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "有效期",
      minWidth: 200,
      cellRenderer: ({ row }) => {
        const start = row.validStartTime ? dayjs(row.validStartTime).format("YYYY-MM-DD") : "";
        const end = row.validEndTime ? dayjs(row.validEndTime).format("YYYY-MM-DD") : "";
        return `${start} ~ ${end}`;
      }
    },
    {
      label: "使用时间",
      prop: "useTime",
      minWidth: 160,
      formatter: ({ useTime }) => useTime ? dayjs(useTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    }
  ]);

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

      if (form.userId) params.userId = Number(form.userId);
      if (form.couponCode) params.couponCode = form.couponCode;
      if (form.status !== undefined) params.status = form.status;

      const { data } = await getUserCouponList(params);
      if (data) {
        dataList.value = data.list || [];
        pagination.total = Number(data.total) || 0;
      }
    } catch (error) {
      console.error("查询用户优惠券失败:", error);
    } finally {
      loading.value = false;
    }
  }

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

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

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

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

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