"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "DatePicker", {
    enumerable: true,
    get: function() {
        return DatePicker;
    }
});
var _interop_require_default = require("@swc/helpers/_/_interop_require_default");
var _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
var _define_property = require("@swc/helpers/_/_define_property");
var _object_spread = require("@swc/helpers/_/_object_spread");
var _object_spread_props = require("@swc/helpers/_/_object_spread_props");
var _object_without_properties = require("@swc/helpers/_/_object_without_properties");
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 _picker = /*#__PURE__*/ _interop_require_default._(require("../picker"));
var _configprovider = require("../configprovider");
var _usepropsvalue = require("../../hooks/use-props-value");
var _typings = require("../../utils/typings");
var _isdate = require("../../utils/is-date");
var _padzero = require("../../utils/pad-zero");
var currentYear = new Date().getFullYear();
var defaultProps = (0, _object_spread_props._)((0, _object_spread._)({}, _typings.ComponentDefaults), {
    visible: false,
    title: '',
    type: 'date',
    showChinese: false,
    threeDimensional: true,
    minuteStep: 1,
    startDate: new Date(currentYear - 10, 0, 1),
    endDate: new Date(currentYear + 10, 11, 31)
});
var DatePicker = function DatePicker(props) {
    var getMonthEndDay = function getMonthEndDay(year, month) {
        return new Date(year, month, 0).getDate();
    };
    var _ref = (0, _object_spread._)({}, defaultProps, props), startDate = _ref.startDate, endDate = _ref.endDate, type = _ref.type, showChinese = _ref.showChinese, minuteStep = _ref.minuteStep, visible = _ref.visible, title = _ref.title, defaultValue = _ref.defaultValue, _ref_pickerProps = _ref.pickerProps, pickerProps = _ref_pickerProps === void 0 ? {} : _ref_pickerProps, formatter = _ref.formatter, onClose = _ref.onClose, onCancel = _ref.onCancel, onConfirm = _ref.onConfirm, filter = _ref.filter, onChange = _ref.onChange, threeDimensional = _ref.threeDimensional, className = _ref.className, style = _ref.style, rest = (0, _object_without_properties._)(_ref, [
        "startDate",
        "endDate",
        "type",
        "showChinese",
        "minuteStep",
        "visible",
        "title",
        "defaultValue",
        "pickerProps",
        "formatter",
        "onClose",
        "onCancel",
        "onConfirm",
        "filter",
        "onChange",
        "threeDimensional",
        "className",
        "style"
    ]);
    var locale = (0, _configprovider.useConfig)().locale;
    var lang = locale.datepicker;
    var zhCNType = {
        day: lang.day,
        year: lang.year,
        month: lang.month,
        hour: lang.hour,
        minute: lang.min,
        seconds: lang.seconds
    };
    var _useState = (0, _sliced_to_array._)((0, _react.useState)([]), 2), pickerValue = _useState[0], setPickerValue = _useState[1];
    var _useState1 = (0, _sliced_to_array._)((0, _react.useState)([]), 2), pickerOptions = _useState1[0], setPickerOptions = _useState1[1];
    var formatValue = function formatValue(value) {
        if (!value || value && !(0, _isdate.isDate)(value)) {
            value = startDate;
        }
        return Math.min(Math.max(value.getTime(), startDate.getTime()), endDate.getTime());
    };
    var _usePropsValue = (0, _sliced_to_array._)((0, _usepropsvalue.usePropsValue)({
        value: props.value && formatValue(props.value),
        defaultValue: props.defaultValue && formatValue(props.defaultValue),
        finalValue: 0
    }), 2), selectedDate = _usePropsValue[0], setSelectedDate = _usePropsValue[1];
    var getBoundary = function getBoundary(type, value) {
        var boundary = type === 'min' ? startDate : endDate;
        var year = boundary.getFullYear();
        var month = 1;
        var date = 1;
        var hour = 0;
        var minute = 0;
        if (type === 'max') {
            month = 12;
            date = getMonthEndDay(value.getFullYear(), value.getMonth() + 1);
            hour = 23;
            minute = 59;
        }
        var seconds = minute;
        if (value.getFullYear() === year) {
            month = boundary.getMonth() + 1;
            if (value.getMonth() + 1 === month) {
                date = boundary.getDate();
                if (value.getDate() === date) {
                    hour = boundary.getHours();
                    if (value.getHours() === hour) {
                        minute = boundary.getMinutes();
                    }
                }
            }
        }
        var _obj;
        return _obj = {}, (0, _define_property._)(_obj, "".concat(type, "Year"), year), (0, _define_property._)(_obj, "".concat(type, "Month"), month), (0, _define_property._)(_obj, "".concat(type, "Date"), date), (0, _define_property._)(_obj, "".concat(type, "Hour"), hour), (0, _define_property._)(_obj, "".concat(type, "Minute"), minute), (0, _define_property._)(_obj, "".concat(type, "Seconds"), seconds), _obj;
    };
    var ranges = function ranges() {
        var selected = new Date(selectedDate);
        if (!selected) return [];
        var _getBoundary = getBoundary('max', selected), maxYear = _getBoundary.maxYear, maxDate = _getBoundary.maxDate, maxMonth = _getBoundary.maxMonth, maxHour = _getBoundary.maxHour, maxMinute = _getBoundary.maxMinute, maxSeconds = _getBoundary.maxSeconds;
        var _getBoundary1 = getBoundary('min', selected), minYear = _getBoundary1.minYear, minDate = _getBoundary1.minDate, minMonth = _getBoundary1.minMonth, minHour = _getBoundary1.minHour, minMinute = _getBoundary1.minMinute, minSeconds = _getBoundary1.minSeconds;
        var result = [
            {
                type: 'year',
                range: [
                    minYear,
                    maxYear
                ]
            },
            {
                type: 'month',
                range: [
                    minMonth,
                    maxMonth
                ]
            },
            {
                type: 'day',
                range: [
                    minDate,
                    maxDate
                ]
            },
            {
                type: 'hour',
                range: [
                    minHour,
                    maxHour
                ]
            },
            {
                type: 'minute',
                range: [
                    minMinute,
                    maxMinute
                ]
            },
            {
                type: 'seconds',
                range: [
                    minSeconds,
                    maxSeconds
                ]
            }
        ];
        switch(type.toLocaleLowerCase()){
            case 'date':
                return result.slice(0, 3);
            case 'datetime':
                return result.slice(0, 5);
            case 'time':
                return result.slice(3, 6);
            case 'year-month':
                return result.slice(0, 2);
            case 'hour-minutes':
                return result.slice(3, 5);
            case 'month-day':
                return result.slice(1, 3);
            case 'datehour':
                return result.slice(0, 4);
            default:
                return result;
        }
    };
    var compareDateChange = function compareDateChange(currentDate, newDate, selectedOptions, index) {
        var _this;
        var isEqual = ((_this = new Date(currentDate)) === null || _this === void 0 ? void 0 : _this.getTime()) === (newDate === null || newDate === void 0 ? void 0 : newDate.getTime());
        if (newDate && (0, _isdate.isDate)(newDate)) {
            if (!isEqual) {
                setSelectedDate(formatValue(newDate));
            }
            onChange === null || onChange === void 0 ? void 0 : onChange(selectedOptions, [
                String(newDate.getFullYear()),
                String(newDate.getMonth() + 1),
                String(newDate.getDate())
            ], index);
        }
    };
    var handlePickerChange = function handlePickerChange(selectedOptions, selectedValue, index) {
        var rangeType = type.toLocaleLowerCase();
        if ([
            'date',
            'datetime',
            'datehour',
            'month-day',
            'year-month'
        ].includes(rangeType)) {
            var formatDate = [];
            selectedValue.forEach(function(item) {
                formatDate.push(item);
            });
            if (rangeType === 'month-day' && formatDate.length < 3) {
                formatDate.unshift(new Date(defaultValue || startDate || endDate).getFullYear());
            }
            if (rangeType === 'year-month' && formatDate.length < 3) {
                formatDate.push(new Date(defaultValue || startDate || endDate).getDate());
            }
            var year = Number(formatDate[0]);
            var month = Number(formatDate[1]) - 1;
            var day = Math.min(Number(formatDate[2]), getMonthEndDay(Number(formatDate[0]), Number(formatDate[1])));
            var date = null;
            if (rangeType === 'date' || rangeType === 'month-day' || rangeType === 'year-month') {
                date = new Date(year, month, day);
            } else if (rangeType === 'datetime') {
                date = new Date(year, month, day, Number(formatDate[3]), Number(formatDate[4]));
            } else if (rangeType === 'datehour') {
                date = new Date(year, month, day, Number(formatDate[3]));
            }
            compareDateChange(selectedDate, date, selectedOptions, index);
        } else {
            // 'hour-minutes' 'time'
            var _selectedValue = (0, _sliced_to_array._)(selectedValue, 3), hour = _selectedValue[0], minute = _selectedValue[1], seconds = _selectedValue[2];
            var currentDate = new Date(selectedDate);
            var year1 = currentDate.getFullYear();
            var month1 = currentDate.getMonth();
            var day1 = currentDate.getDate();
            var date1 = new Date(year1, month1, day1, Number(hour), Number(minute), rangeType === 'time' ? Number(seconds) : 0);
            compareDateChange(selectedDate, date1, selectedOptions, index);
        }
    };
    var formatOption = function formatOption(type, value) {
        if (formatter) {
            return formatter(type, {
                text: (0, _padzero.padZero)(value, 2),
                value: (0, _padzero.padZero)(value, 2)
            });
        }
        var padMin = (0, _padzero.padZero)(value, 2);
        var fatter = showChinese ? zhCNType[type] : '';
        return {
            text: padMin + fatter,
            value: padMin
        };
    };
    var generateColumn = function generateColumn(min, max, val, type, columnIndex) {
        var _arr_index;
        var cmin = min;
        var arr = [];
        var index = 0;
        while(cmin <= max){
            arr.push(formatOption(type, cmin));
            if (type === 'minute') {
                cmin += minuteStep;
            } else {
                cmin++;
            }
            if (cmin <= Number(val)) {
                index++;
            }
        }
        pickerValue[columnIndex] = (_arr_index = arr[index]) === null || _arr_index === void 0 ? void 0 : _arr_index.value;
        setPickerValue((0, _to_consumable_array._)(pickerValue));
        if (filter === null || filter === void 0 ? void 0 : filter(type, arr)) {
            return filter === null || filter === void 0 ? void 0 : filter(type, arr);
        }
        return arr;
    };
    var getDateIndex = function getDateIndex(type) {
        var date = new Date(selectedDate);
        if (!selectedDate) return 0;
        if (type === 'year') {
            return date.getFullYear();
        }
        if (type === 'month') {
            return date.getMonth() + 1;
        }
        if (type === 'day') {
            return date.getDate();
        }
        if (type === 'hour') {
            return date.getHours();
        }
        if (type === 'minute') {
            return date.getMinutes();
        }
        if (type === 'seconds') {
            return date.getSeconds();
        }
        return 0;
    };
    var columns = function columns() {
        var val = ranges().map(function(res, columnIndex) {
            return generateColumn(res.range[0], res.range[1], getDateIndex(res.type), res.type, columnIndex);
        });
        return val || [];
    };
    (0, _react.useEffect)(function() {
        setPickerOptions(columns());
    }, [
        selectedDate,
        startDate,
        endDate
    ]);
    return /*#__PURE__*/ _react.default.createElement("div", (0, _object_spread._)({
        className: "nut-datepicker ".concat(className),
        style: style
    }, rest), pickerOptions.length > 0 && /*#__PURE__*/ _react.default.createElement(_picker.default, (0, _object_spread_props._)((0, _object_spread._)({}, pickerProps), {
        title: title,
        visible: visible,
        options: pickerOptions,
        onClose: onClose,
        onCancel: onCancel,
        value: pickerValue,
        onConfirm: function onConfirm1(options, value) {
            return onConfirm && onConfirm(options, value);
        },
        onChange: function onChange(options, value, index) {
            return handlePickerChange(options, value, index);
        },
        threeDimensional: threeDimensional
    })));
};
DatePicker.displayName = 'NutDatePicker';
