"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "CalendarCard", {
    enumerable: true,
    get: function() {
        return CalendarCard;
    }
});
var _interop_require_default = require("@swc/helpers/_/_interop_require_default");
var _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
var _object_spread = require("@swc/helpers/_/_object_spread");
var _object_spread_props = require("@swc/helpers/_/_object_spread_props");
var _sliced_to_array = require("@swc/helpers/_/_sliced_to_array");
var _to_consumable_array = require("@swc/helpers/_/_to_consumable_array");
var _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
var _classnames = /*#__PURE__*/ _interop_require_default._(require("classnames"));
var _components = require("@tarojs/components");
var _icon = require("./icon");
var _typings = require("../../utils/typings");
var _utils = require("./utils");
var _index = require("../configprovider/index");
var _usepropsvalue = require("../../hooks/use-props-value");
var defaultProps = (0, _object_spread_props._)((0, _object_spread._)({}, _typings.ComponentDefaults), {
    type: 'single',
    firstDayOfWeek: 0,
    weekdays: []
});
var prefixCls = 'nut-calendarcard';
var CalendarCard = /*#__PURE__*/ _react.default.forwardRef(function(props, ref) {
    var locale = (0, _index.useConfig)().locale;
    var _$_object_spread = (0, _object_spread._)({}, defaultProps, props), style = _$_object_spread.style, className = _$_object_spread.className, type = _$_object_spread.type, title = _$_object_spread.title, value = _$_object_spread.value, defaultValue = _$_object_spread.defaultValue, firstDayOfWeek = _$_object_spread.firstDayOfWeek, startDate = _$_object_spread.startDate, endDate = _$_object_spread.endDate, disableDay = _$_object_spread.disableDay, renderDay = _$_object_spread.renderDay, renderDayTop = _$_object_spread.renderDayTop, renderDayBottom = _$_object_spread.renderDayBottom, weekdays = _$_object_spread.weekdays, onDayClick = _$_object_spread.onDayClick, onPageChange = _$_object_spread.onPageChange, onChange = _$_object_spread.onChange;
    var onPageChangeRef = (0, _react.useRef)(onPageChange);
    // 当前月份信息
    var _useState = (0, _sliced_to_array._)((0, _react.useState)(function() {
        var date = new Date(Date.now());
        var val = value || defaultValue;
        if (Array.isArray(val)) {
            if (val.length) {
                date = val[0];
            }
        } else if (val) {
            date = val;
        }
        return {
            year: date.getFullYear(),
            month: date.getMonth() + 1
        };
    }), 2), month = _useState[0], setMonth = _useState[1];
    // 当前月份对应的日期(6 * 7 视图)
    var _useState1 = (0, _sliced_to_array._)((0, _react.useState)([]), 2), days = _useState1[0], setDays = _useState1[1];
    var valueToRange = function valueToRange(val) {
        if (Array.isArray(val)) {
            return val.map(function(date) {
                return (0, _utils.convertDateToDay)(date);
            });
        }
        return val ? [
            (0, _utils.convertDateToDay)(val)
        ] : [];
    };
    var rangeTovalue = function rangeTovalue(range) {
        if (Array.isArray(range)) {
            return range.map(function(day) {
                return (0, _utils.convertDayToDate)(day);
            });
        }
        return range ? [
            (0, _utils.convertDayToDate)(range)
        ] : [];
    };
    var _usePropsValue = (0, _sliced_to_array._)((0, _usepropsvalue.usePropsValue)({
        value: value ? valueToRange(value) : undefined,
        defaultValue: defaultValue ? valueToRange(defaultValue) : undefined,
        finalValue: []
    }), 2), innerValue = _usePropsValue[0], setInnerValue = _usePropsValue[1];
    var change = function change(v) {
        setInnerValue(v);
        if (type === 'single') {
            var date = (0, _utils.convertDayToDate)(v[0]);
            onChange === null || onChange === void 0 ? void 0 : onChange(date);
        } else if (type === 'multiple' || type === 'range' || type === 'week') {
            var val = rangeTovalue(v);
            onChange === null || onChange === void 0 ? void 0 : onChange(val);
        }
    };
    var getDays = (0, _react.useCallback)(function(month) {
        var y = month.year;
        var m = month.month;
        var days = (0, _to_consumable_array._)((0, _utils.getPrevMonthDays)(y, m, firstDayOfWeek)).concat((0, _to_consumable_array._)((0, _utils.getCurrentMonthDays)(y, m)));
        var size = days.length;
        var yearOfNextMonth = month.month === 12 ? month.year + 1 : month.year;
        var monthOfNextMonth = month.month === 12 ? 1 : month.month + 1;
        // 补全 6 行 7 列视图
        for(var i = 1; i <= 42 - size; i++){
            days.push({
                type: 'next',
                year: yearOfNextMonth,
                month: monthOfNextMonth,
                date: i
            });
        }
        return days;
    }, [
        firstDayOfWeek
    ]);
    (0, _react.useEffect)(function() {
        onPageChangeRef.current = onPageChange;
    }, [
        onPageChange
    ]);
    (0, _react.useEffect)(function() {
        var _onPageChangeRef_current;
        var newDays = getDays(month);
        setDays(newDays);
        (_onPageChangeRef_current = onPageChangeRef.current) === null || _onPageChangeRef_current === void 0 ? void 0 : _onPageChangeRef_current.call(onPageChangeRef, month);
    }, [
        month,
        getDays,
        firstDayOfWeek
    ]);
    var isSameDay = function isSameDay(day1, day2) {
        return (day1 === null || day1 === void 0 ? void 0 : day1.year) === (day2 === null || day2 === void 0 ? void 0 : day2.year) && (day1 === null || day1 === void 0 ? void 0 : day1.month) === (day2 === null || day2 === void 0 ? void 0 : day2.month) && (day1 === null || day1 === void 0 ? void 0 : day1.date) === (day2 === null || day2 === void 0 ? void 0 : day2.date);
    };
    var compareDay = function compareDay(day1, day2) {
        if (day1 && day2) {
            if (day1.year === day2.year) {
                if (day1.month === day2.month) {
                    return day1.date - day2.date;
                }
                return day1.month - day2.month;
            }
            return day1.year - day2.year;
        }
    };
    var isDisable = function isDisable(day) {
        if (disableDay && disableDay(day)) {
            return true;
        }
        if (startDate && Number(compareDay(day, (0, _utils.convertDateToDay)(startDate))) < 0) {
            return true;
        }
        if (endDate && Number(compareDay(day, (0, _utils.convertDateToDay)(endDate))) > 0) {
            return true;
        }
        return false;
    };
    var isActive = function isActive(day) {
        if (type === 'single' || type === 'multiple') {
            for(var val in innerValue){
                if (isSameDay(day, innerValue[val])) {
                    return true;
                }
            }
        } else if (type === 'range' && innerValue.length === 1 && isSameDay(innerValue[0], day)) {
            return true;
        }
        return false;
    };
    var isStart = function isStart(day) {
        return (type === 'range' || type === 'week') && innerValue.length === 2 && isSameDay(day, innerValue[0]);
    };
    var isEnd = function isEnd(day) {
        return (type === 'range' || type === 'week') && innerValue.length === 2 && isSameDay(day, innerValue[1]);
    };
    var isMid = function isMid(day) {
        if (type === 'range' || type === 'week') {
            if (innerValue.length === 2) {
                var c1 = compareDay(innerValue[0], day);
                var c2 = compareDay(day, innerValue[1]);
                if (c1 && c1 < 0 && c2 && c2 < 0) {
                    return true;
                }
            }
        }
        return false;
    };
    var isWeekend = function isWeekend(day) {
        var d = new Date(day.year, day.month - 1, day.date).getDay();
        return d === 0 || d === 6;
    };
    var getClasses = function getClasses(day) {
        /**
     * active: single、multiple 激活日期
     * start: 范围开始日期
     * end: 范围结束日期
     * mid: 范围中间日期
     */ if (isDisable(day)) {
            return [
                'disabled'
            ];
        }
        var res = [];
        if (day.type === 'current') {
            if (isActive(day)) {
                res.push('active');
            }
            if (isStart(day)) {
                res.push('start');
            }
            if (isEnd(day)) {
                res.push('end');
            }
            if (isMid(day)) {
                res.push('mid');
            }
            if (isWeekend(day)) {
                res.push('weekend');
            }
        }
        return res;
    };
    var jumpTo = function jumpTo(year, month) {
        if (startDate) {
            var c = compareDay({
                year: year,
                month: month,
                date: 31
            }, (0, _utils.convertDateToDay)(startDate));
            if (c && c < 0) {
                return;
            }
        }
        if (endDate) {
            var c1 = compareDay({
                year: year,
                month: month,
                date: 1
            }, (0, _utils.convertDateToDay)(endDate));
            if (c1 && c1 > 0) {
                return;
            }
        }
        setMonth({
            year: year,
            month: month
        });
    };
    var jump = function jump() {
        var step = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 1;
        var current = month.year * 12 + month.month;
        var newMonth = (current + step) % 12;
        if (newMonth === 0) {
            newMonth = 12;
        }
        var newYear = Math.floor((current + step - newMonth) / 12);
        jumpTo(newYear, newMonth);
    };
    _react.default.useImperativeHandle(ref, function() {
        return {
            jump: jump,
            jumpTo: jumpTo
        };
    });
    var handleDayClick = function handleDayClick(day) {
        onDayClick === null || onDayClick === void 0 ? void 0 : onDayClick(day);
        if (day.type === 'prev' || day.type === 'next' || isDisable(day)) {
            return;
        }
        switch(type){
            case 'single':
                {
                    if (innerValue[0] && isSameDay(innerValue[0], day)) {
                        change([]);
                    } else {
                        change([
                            day
                        ]);
                    }
                    break;
                }
            case 'multiple':
                {
                    var t = innerValue.find(function(i) {
                        return isSameDay(i, day);
                    });
                    if (t) {
                        change(innerValue.filter(function(i) {
                            return i !== t;
                        }));
                    } else {
                        change((0, _to_consumable_array._)(innerValue).concat([
                            day
                        ]));
                    }
                    break;
                }
            case 'range':
                {
                    var len = innerValue.length;
                    if (len === 0 || len === 2) {
                        change([
                            day
                        ]);
                    } else if (len === 1) {
                        var t1 = compareDay(innerValue[0], day);
                        if (t1 === null || t1 === undefined) {
                            change([]);
                        } else if (t1 < 0) {
                            change([
                                innerValue[0],
                                day
                            ]);
                        } else {
                            change([
                                day,
                                innerValue[0]
                            ]);
                        }
                    } else {
                        console.warn('[NutUI] Calendar range error');
                    }
                    break;
                }
            case 'week':
                {
                    if (innerValue.length === 2 || innerValue.length === 0) {
                        var _getCurrentWeekDays = (0, _sliced_to_array._)((0, _utils.getCurrentWeekDays)(day, firstDayOfWeek), 2), left = _getCurrentWeekDays[0], right = _getCurrentWeekDays[1];
                        change([
                            left,
                            right
                        ]);
                    } else {
                        console.warn('[NutUI] Calendar week error');
                    }
                    break;
                }
            default:
                {
                    console.warn('[NutUI] Calendar type error');
                }
        }
    };
    var monthTitle = locale.calendaritem.monthTitle;
    var renderHeader = function renderHeader() {
        return /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(prefixCls, "-header")
        }, /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(prefixCls, "-header-left")
        }, /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "double-left",
            onClick: function onClick() {
                return jump(-12);
            }
        }, /*#__PURE__*/ _react.default.createElement(_icon.DoubleLeft, null)), /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "left",
            onClick: function onClick() {
                return jump(-1);
            }
        }, /*#__PURE__*/ _react.default.createElement(_icon.ArrowLeft, null))), /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(prefixCls, "-header-title")
        }, monthTitle(month.year, month.month)), /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(prefixCls, "-header-right")
        }, /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "right",
            onClick: function onClick() {
                return jump(1);
            }
        }, /*#__PURE__*/ _react.default.createElement(_icon.ArrowRight, null)), /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "double-right",
            onClick: function onClick() {
                return jump(12);
            }
        }, /*#__PURE__*/ _react.default.createElement(_icon.DoubleRight, null))));
    };
    var weekHeader = (0, _react.useMemo)(function() {
        var weekdaysList = weekdays.length > 0 ? weekdays : locale.calendaritem.weekdays;
        var weekdaysData = weekdaysList.map(function(day, index) {
            return {
                name: day,
                key: index
            };
        });
        return (0, _to_consumable_array._)(weekdaysData.slice(firstDayOfWeek, 7)).concat((0, _to_consumable_array._)(weekdaysData.slice(0, firstDayOfWeek)));
    }, [
        weekdays,
        firstDayOfWeek,
        locale.calendaritem.weekdays
    ]);
    var renderContent = function renderContent() {
        return /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(prefixCls, "-content")
        }, /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(prefixCls, "-days")
        }, weekHeader.map(function(day) {
            return /*#__PURE__*/ _react.default.createElement(_components.View, {
                className: (0, _classnames.default)("".concat(prefixCls, "-day"), 'header', {
                    weekend: day.key === 0 || day.key === 6
                }),
                key: day.key
            }, day.name);
        })), /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(prefixCls, "-days")
        }, days.map(function(day) {
            return /*#__PURE__*/ _react.default.createElement(_components.View, {
                className: (0, _classnames.default)("".concat(prefixCls, "-day"), day.type, getClasses(day)),
                key: "".concat(day.year, "-").concat(day.month, "-").concat(day.date),
                onClick: function onClick() {
                    return handleDayClick(day);
                }
            }, /*#__PURE__*/ _react.default.createElement(_components.View, {
                className: "".concat(prefixCls, "-day-top")
            }, renderDayTop ? renderDayTop(day) : ''), /*#__PURE__*/ _react.default.createElement(_components.View, {
                className: "".concat(prefixCls, "-day-inner")
            }, renderDay ? renderDay(day) : day.date), /*#__PURE__*/ _react.default.createElement(_components.View, {
                className: "".concat(prefixCls, "-day-bottom")
            }, renderDayBottom ? renderDayBottom(day) : ''));
        })));
    };
    return days.length > 0 ? /*#__PURE__*/ _react.default.createElement(_components.View, {
        className: (0, _classnames.default)(prefixCls, className),
        style: style
    }, title || renderHeader(), renderContent()) : null;
});
CalendarCard.displayName = 'NutCalendarCard';
