File size: 9,974 Bytes
4c2a557
 
 
a572854
4c2a557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"use client";

import { useState, useEffect } from "react";
import dayjs from "@/lib/dayjs";
import { Button } from "@/components/ui/button";
import { useTranslation } from "react-i18next";
import { motion, AnimatePresence } from "framer-motion";
import {
  Calendar as CalendarIcon,
  Clock,
  Sun,
  CalendarDays,
  CalendarRange,
  CalendarClock,
  CalendarCheck,
} from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { format } from "date-fns";
import { zhCN } from "date-fns/locale";

export type TimeRangeType =
  | "today"
  | "week"
  | "month"
  | "30days"
  | "all"
  | "custom";

interface TimeRangeSelectorProps {
  timeRange: [Date, Date];
  timeRangeType: TimeRangeType;
  availableTimeRange: {
    minTime: Date;
    maxTime: Date;
  };
  onTimeRangeChange: (range: [Date, Date], type: TimeRangeType) => void;
}

const checkTimeRangeType = (
  startTime: dayjs.Dayjs,
  endTime: dayjs.Dayjs,
  availableTimeRange: { minTime: Date; maxTime: Date }
): TimeRangeType => {
  if (
    dayjs(startTime).isSame(availableTimeRange.minTime, "hour") &&
    dayjs(endTime).isSame(availableTimeRange.maxTime, "hour")
  ) {
    return "all";
  }

  const now = dayjs();
  const isToday = startTime.isSame(now.startOf("day")) && endTime.isSame(now);
  const isWeek = startTime.isSame(now.startOf("week")) && endTime.isSame(now);
  const isMonth = startTime.isSame(now.startOf("month")) && endTime.isSame(now);
  const is30Days =
    startTime.isSame(now.subtract(30, "day"), "hour") && endTime.isSame(now);

  if (isToday) return "today";
  if (isWeek) return "week";
  if (isMonth) return "month";
  if (is30Days) return "30days";

  return "custom";
};

export default function TimeRangeSelector({
  timeRange,
  timeRangeType,
  availableTimeRange,
  onTimeRangeChange,
}: TimeRangeSelectorProps) {
  const { t, i18n } = useTranslation("common");
  const [isCustomOpen, setIsCustomOpen] = useState(false);
  const [startOpen, setStartOpen] = useState(false);
  const [endOpen, setEndOpen] = useState(false);

  const [startDate, setStartDate] = useState<Date>(timeRange[0]);
  const [endDate, setEndDate] = useState<Date>(timeRange[1]);

  useEffect(() => {
    setStartDate(timeRange[0]);
    setEndDate(timeRange[1]);
  }, [timeRange]);

  const timeOptions = [
    {
      id: "today",
      type: "today" as TimeRangeType,
      label: t("panel.timeRange.timeOptions.day"),
      icon: Sun,
      getRange: () =>
        [dayjs().startOf("day").toDate(), dayjs().endOf("day").toDate()] as [
          Date,
          Date
        ],
    },
    {
      id: "week",
      type: "week" as TimeRangeType,
      label: t("panel.timeRange.timeOptions.week"),
      icon: CalendarDays,
      getRange: () =>
        [dayjs().startOf("week").toDate(), dayjs().endOf("week").toDate()] as [
          Date,
          Date
        ],
    },
    {
      id: "month",
      type: "month" as TimeRangeType,
      label: t("panel.timeRange.timeOptions.month"),
      icon: CalendarRange,
      getRange: () =>
        [
          dayjs().startOf("month").toDate(),
          dayjs().endOf("month").toDate(),
        ] as [Date, Date],
    },
    {
      id: "30days",
      type: "30days" as TimeRangeType,
      label: t("panel.timeRange.timeOptions.30Days"),
      icon: CalendarClock,
      getRange: () =>
        [
          dayjs().subtract(29, "days").startOf("day").toDate(),
          dayjs().endOf("day").toDate(),
        ] as [Date, Date],
    },
    {
      id: "all",
      type: "all" as TimeRangeType,
      label: t("panel.timeRange.timeOptions.all"),
      icon: CalendarCheck,
      getRange: () =>
        [
          dayjs(availableTimeRange.minTime).startOf("day").toDate(),
          dayjs(availableTimeRange.maxTime).endOf("day").toDate(),
        ] as [Date, Date],
    },
  ];

  const handleTimeOptionClick = (type: TimeRangeType) => {
    const option = timeOptions.find((opt) => opt.type === type);
    if (!option) return;

    const range = option.getRange();
    setStartDate(range[0]);
    setEndDate(range[1]);
    setIsCustomOpen(false);
    onTimeRangeChange(range, type);
  };

  const handleCustomButtonClick = () => {
    const isOpening = !isCustomOpen;
    setIsCustomOpen(isOpening);

    if (isOpening) {
      onTimeRangeChange([startDate, endDate], "custom");
    }
  };

  const handleDateChange = (start?: Date, end?: Date) => {
    if (!start || !end) return;

    const newStart = dayjs(start).startOf("day").toDate();
    const newEnd = dayjs(end).endOf("day").toDate();

    setStartDate(newStart);
    setEndDate(newEnd);
    onTimeRangeChange([newStart, newEnd], "custom");
  };

  const formatDate = (date?: Date) => {
    if (!date) return t("panel.timeRange.selectDate");
    return format(date, "yyyy-MM-dd", {
      locale: i18n.language === "zh" ? zhCN : undefined,
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-2 text-lg font-medium">
        <Clock className="w-5 h-5 text-primary" />
        <h3>{t("panel.timeRange.title")}</h3>
      </div>

      <div className="space-y-4">
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-3">
          {timeOptions.map(({ id, type, label, icon: Icon }) => (
            <motion.div
              key={id}
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
            >
              <Button
                variant={timeRangeType === type ? "default" : "outline"}
                className="w-full h-full min-h-[52px] flex flex-col gap-1.5 items-center justify-center"
                onClick={() => handleTimeOptionClick(type)}
              >
                <Icon className="w-4 h-4" />
                <span className="text-sm">{label}</span>
              </Button>
            </motion.div>
          ))}

          <motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }}>
            <Button
              variant={timeRangeType === "custom" ? "default" : "outline"}
              className="w-full h-full min-h-[52px] flex flex-col gap-1.5 items-center justify-center"
              onClick={handleCustomButtonClick}
            >
              <CalendarIcon className="w-4 h-4" />
              <span className="text-sm">
                {t("panel.timeRange.timeOptions.custom")}
              </span>
            </Button>
          </motion.div>
        </div>

        <AnimatePresence>
          {isCustomOpen && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
              className="space-y-3"
            >
              <div className="text-sm text-muted-foreground">
                {t("panel.timeRange.customRange")}
              </div>
              <div className="flex flex-col sm:flex-row gap-3">
                <Popover open={startOpen} onOpenChange={setStartOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="secondary"
                      className={cn(
                        "justify-start text-left font-normal w-full sm:w-[240px]",
                        !startDate && "text-muted-foreground"
                      )}
                    >
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {formatDate(startDate)}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                      mode="single"
                      selected={startDate}
                      defaultMonth={startDate}
                      onSelect={(date) => {
                        if (date) {
                          handleDateChange(date, endDate);
                          setStartOpen(false);
                        }
                      }}
                      disabled={(date) =>
                        endDate ? dayjs(date).isAfter(endDate, "day") : false
                      }
                      initialFocus
                      locale={i18n.language === "zh" ? zhCN : undefined}
                    />
                  </PopoverContent>
                </Popover>

                <Popover open={endOpen} onOpenChange={setEndOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="secondary"
                      className={cn(
                        "justify-start text-left font-normal w-full sm:w-[240px]",
                        !endDate && "text-muted-foreground"
                      )}
                    >
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {formatDate(endDate)}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                      mode="single"
                      selected={endDate}
                      defaultMonth={endDate}
                      onSelect={(date) => {
                        if (date) {
                          handleDateChange(startDate, date);
                          setEndOpen(false);
                        }
                      }}
                      disabled={(date) =>
                        startDate
                          ? dayjs(date).isBefore(startDate, "day")
                          : false
                      }
                      initialFocus
                      locale={i18n.language === "zh" ? zhCN : undefined}
                    />
                  </PopoverContent>
                </Popover>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}