"use client";
import {
    getInfoDayApi,
    InfoDayListRequest,
    InfoDayRequest,
    UserLevelToDayResp,
} from "@/api/summary";
import Table from "@/components/Table";
import { getToken } from "@/utils/Cookies";
import { phoneConvert } from "@/utils/methods";
import { Button, CalendarPickerView, CalendarPickerViewRef, Popup } from "antd-mobile";
import dayjs from "dayjs";
import { useTranslations } from "next-intl";
import { FC, useRef, useState } from "react";
import "./page.scss";
interface Props {}

const App: FC<Props> = (props) => {
    const t = useTranslations("ReferralsPage");
    const [visible, setVisible] = useState(false);

    const [hasMore, setHasMore] = useState(true);

    const calendarPickerRef = useRef<CalendarPickerViewRef>(null);

    const [dataSource, setDataSource] = useState<{
        list: UserLevelToDayResp[];
        page: InfoDayListRequest;
    }>({
        list: [],
        page: {},
    });
    const params = useRef<InfoDayRequest>({
        day: dayjs().startOf("date").unix(),
        current_page: 0,
        page_size: 40,
    });

    const token = getToken();

    const currentTime = params.current.day * 1000; // 13位时间戳

    // check后的时间
    const checkDate = useRef<Date | null>(new Date());
    const dateChange = (date: Date | null) => {
        checkDate.current = date;
    };
    const confirmHandler = () => {
        params.current.day = dayjs(checkDate.current).startOf("date").unix();
        setVisible(false);
        setDataSource((val) => ({ ...val, list: [] }));
        setHasMore(true);
        params.current.current_page = 0;
    };
    const loadMore = async () => {
        params.current.current_page += 1;
        await getData({
            ...params.current,
        });
    };
    const getData = async (params: InfoDayRequest) => {
        if (!token) {
            setHasMore(false);
            return;
        }
        try {
            const res = await getInfoDayApi(params);
            setDataSource((val) => ({ ...val, list: [...val.list, ...res.data] }));
            setHasMore(!res.page.is_end!);
        } catch (error) {
            setHasMore(false);
            return Promise.reject();
        }
    };
    const min = new Date();
    min.setMonth(min.getMonth() - 20);

    const max = new Date();
    max.setMonth(max.getMonth());

    const columns = [
        {
            title: "#",
            type: "index",
            dataIndex: "name",
            width: "0.2rem",
        },
        {
            title: t("Conta"),
            dataIndex: "phone",
            width: "0.6rem",
            render: (item: UserLevelToDayResp) => {
                return <span>{phoneConvert(item.phone!)}</span>;
            },
        },
        {
            title: `${t("Apostas")}(${t("R$")})`,
            dataIndex: "score",
            width: "0.8rem",
        },
        {
            title: `${t("ApostaEquipe")}(${t("R$")})`,
            dataIndex: "score_num",
            render: (item: UserLevelToDayResp) => {
                return (
                    <span>
                        {item.score_num}[{item.score}]
                    </span>
                );
            },
        },
        {
            title: t("Comissão"),
            dataIndex: "commissar",
            width: "0.7rem",
        },
    ];

    return (
        <div className="content">
            <div className="referral referral-router-view">
                <div className="search">
                    <div
                        className="time"
                        onClick={() => {
                            setVisible(true);
                        }}
                    >
                        <span className="dateTime text-[#333]">
                            {dayjs(currentTime).format("YYYY-MM-DD")}
                        </span>
                        <div>
                            <span className="iconfont icon-rili"></span>
                            <span className="iconfont icon-guanbi"></span>
                        </div>
                    </div>
                </div>

                <Table
                    columns={columns}
                    dataSource={dataSource.list}
                    loadMore={loadMore}
                    hasMore={hasMore}
                    maxHeight={"65dvh"}
                ></Table>

                <div className="total">
                    <div>
                        <span className="num">{t("R$")} 0</span>
                        <span>{t("Aposta")}</span>
                    </div>
                    <div>
                        <span className="num">{t("R$")} 0</span>
                        <span>{t("Comissão")}</span>
                    </div>
                </div>
                {/* 日历 */}
            </div>

            <Popup
                visible={visible}
                bodyStyle={{
                    background: "#fff",
                    color: "#666",
                    borderTopLeftRadius: "0.1389rem",
                    borderTopRightRadius: "0.1389rem",
                    paddingBottom: "20px",
                }}
                showCloseButton
                afterShow={() => {
                    calendarPickerRef.current!.jumpTo((page) => ({
                        year: dayjs(currentTime).get("year"),
                        month: dayjs(currentTime).get("month") + 1,
                    }));
                }}
                getContainer={null}
                onClose={() => setVisible(false)}
                onMaskClick={() => setVisible(false)}
            >
                <CalendarPickerView
                    selectionMode={"single"}
                    ref={calendarPickerRef}
                    defaultValue={dayjs(currentTime).toDate()}
                    onChange={dateChange}
                    allowClear={false}
                    min={min}
                    max={max}
                    title={<div className={"text-[0.14rem]"}>Calendar</div>}
                />
                <div className={"flex justify-center"}>
                    <Button color={"primary"} onClick={confirmHandler}>
                        Confirm
                    </Button>
                </div>
            </Popup>
        </div>
    );
};
export default App;
