import { DateRangePickerDefaultProps } from './props';
import dayjs from 'dayjs';
import computed from '../../mixins/computed';
import equal from 'fast-deep-equal';
import { getRangeData, getDateByValue, getValueByDate, getValidValue, isEqualDate, } from '../util';
import fmtEvent from '../../_util/fmtEvent';
import mixinValue from '../../mixins/value';
var component2 = my.canIUse('component2');
Component({
    mixins: [
        mixinValue({
            transformValue: function (value) {
                return {
                    value: value && value[0] && value[1]
                        ? [dayjs(value[0]).toDate(), dayjs(value[1]).toDate()]
                        : undefined,
                    needUpdate: true,
                };
            },
        }),
        computed,
    ],
    props: DateRangePickerDefaultProps,
    pickerVisible: false,
    data: function () {
        return {
            currentValue: [],
            columns: [],
            pickerType: 'start',
            currentStartDate: null,
            currentEndDate: null,
            forceUpdate: 0, // 强制更新picker组件，已知需处理的情况：value超限，但是需要更新format，由于picker的参数均未变化，无法触发picker的渲染
        };
    },
    didMount: function () {
        this.pickerVisible = false;
    },
    deriveDataFromProps: function (nextProps) {
        this.updateValue(this.props, nextProps);
    },
    didUpdate: function (prevProps) {
        if (!component2) {
            this.updateValue(prevProps, this.props);
        }
    },
    methods: {
        updateValue: function (prevProps, currentProps) {
            var _a, _b, _c, _d;
            if (!isEqualDate((_a = prevProps.value) === null || _a === void 0 ? void 0 : _a[0], (_b = currentProps.value) === null || _b === void 0 ? void 0 : _b[0]) ||
                !isEqualDate((_c = prevProps.value) === null || _c === void 0 ? void 0 : _c[1], (_d = currentProps.value) === null || _d === void 0 ? void 0 : _d[1])) {
                this.setData({
                    forceUpdate: this.data.forceUpdate + 1,
                });
                if (this.pickerVisible) {
                    // 展开状态才更新picker的数据，否则下次triggerVisible触发
                    this.setCurrentValue(currentProps);
                }
            }
        },
        computed: function () {
            var _a = this.data, currentStartDate = _a.currentStartDate, currentEndDate = _a.currentEndDate, pickerType = _a.pickerType;
            var format = this.props.format;
            if (pickerType)
                return {
                    currentStartValueStr: currentStartDate
                        ? dayjs(currentStartDate).format(format)
                        : '',
                    currentEndValueStr: currentEndDate
                        ? dayjs(currentEndDate).format(format)
                        : '',
                };
        },
        getMin: function (min) {
            return min ? dayjs(min) : dayjs().subtract(10, 'year');
        },
        getMax: function (max) {
            return max ? dayjs(max) : dayjs().add(10, 'year');
        },
        // didUpdate、弹窗打开、切换pickerType触发
        setCurrentValue: function (currentProps) {
            var _this = this;
            var pickerVisible = this.pickerVisible; // 隐藏状态下从CValue触发，展开状态使用当前数据
            var precision = currentProps.precision;
            var _a = this.data, pickerType = _a.pickerType, columns = _a.columns;
            var realValue = this.getValue();
            var _b = this.data, currentStartDate = _b.currentStartDate, currentEndDate = _b.currentEndDate;
            var currentStartDateByCValue = (realValue === null || realValue === void 0 ? void 0 : realValue[0]) || null;
            var currentEndDateByCValue = (realValue === null || realValue === void 0 ? void 0 : realValue[1]) || null;
            // 展开状态，说明在切换pickerType
            if (pickerVisible) {
                if (pickerType === 'start') {
                    if (!currentStartDate) {
                        currentStartDate = currentEndDate;
                    }
                }
                else {
                    // pickerType=end start已存在
                    // 结束时间默认选中开始
                    if (!currentEndDate) {
                        currentEndDate = currentStartDate;
                    }
                }
            }
            else {
                // 否则是在从cValue初始化
                currentStartDate = currentStartDateByCValue;
                currentEndDate = currentEndDateByCValue;
                // 开始默认取优先取当前时间，不在时间范围内取开始时间
                if (!currentStartDate) {
                    var min = this.getMin(currentProps.min).toDate();
                    var max = currentProps.max;
                    currentStartDate = new Date();
                    if ((min && dayjs(currentStartDate).isBefore(min, precision)) ||
                        (max && dayjs(currentStartDate).isAfter(max, precision)) ||
                        (currentEndDateByCValue &&
                            currentStartDate > currentEndDateByCValue)) {
                        currentStartDate = min;
                    }
                }
            }
            var currentValue = getValueByDate(pickerType === 'start' ? currentStartDate : currentEndDate, precision);
            var newColumns = this.generateData(currentValue, currentProps);
            if (!equal(newColumns, columns)) {
                this.setData({ columns: newColumns }, function () {
                    _this.setData({ currentStartDate: currentStartDate, currentEndDate: currentEndDate, currentValue: currentValue });
                });
            }
            else {
                this.setData({ currentStartDate: currentStartDate, currentEndDate: currentEndDate, currentValue: currentValue });
            }
        },
        /**
         * 生成选项数据，didmound、picker change、打开弹窗、切换picker type触发
         */
        generateData: function (currentValue, currentProps) {
            var precision = currentProps.precision, propsMin = currentProps.min, propsMax = currentProps.max;
            var min = this.getMin(propsMin);
            var max = this.getMax(propsMax);
            if (max < min) {
                return [];
            }
            var currentPickerDay = dayjs();
            if (currentValue.length > 0) {
                currentPickerDay = dayjs(getDateByValue(currentValue));
            }
            if (currentPickerDay < min || currentPickerDay > max) {
                currentPickerDay = min;
            }
            var newColumns = getRangeData(precision, min, max, currentPickerDay, this.onFormatLabel.bind(this));
            return newColumns;
        },
        onChange: function (selectedIndex) {
            var _this = this;
            selectedIndex = getValidValue(selectedIndex);
            var _a = this.props, onPickerChange = _a.onPickerChange, format = _a.format, precision = _a.precision;
            var date = getDateByValue(selectedIndex);
            var min = this.getMin(this.props.min);
            var max = this.getMax(this.props.max);
            if (dayjs(date).isBefore(min)) {
                date = min.toDate();
                selectedIndex = getValueByDate(date, precision);
            }
            if (dayjs(date).isAfter(max)) {
                date = max.toDate();
                selectedIndex = getValueByDate(date, precision);
            }
            var _b = this.data, pickerType = _b.pickerType, columns = _b.columns, currentEndDate = _b.currentEndDate, currentStartDate = _b.currentStartDate;
            var newData = {
                currentValue: selectedIndex,
            };
            if (pickerType === 'start') {
                newData.currentStartDate = date;
                if (currentEndDate && dayjs(date).isAfter(currentEndDate)) {
                    newData.currentEndDate = null;
                }
            }
            else {
                newData.currentEndDate = date;
                if (currentStartDate && dayjs(date).isBefore(currentStartDate)) {
                    newData.currentStartDate = null;
                }
            }
            var newColumns = this.generateData(selectedIndex, this.props);
            if (!equal(newColumns, columns)) {
                this.setData({
                    columns: newColumns,
                }, function () {
                    _this.setData(newData);
                    if (onPickerChange) {
                        onPickerChange(pickerType, date, dayjs(date).format(format), fmtEvent(_this.props));
                    }
                });
            }
            else {
                this.setData(newData);
                if (onPickerChange) {
                    onPickerChange(pickerType, date, dayjs(date).format(format), fmtEvent(this.props));
                }
            }
        },
        onCancel: function (e) {
            var onCancel = this.props.onCancel;
            if (onCancel) {
                onCancel(fmtEvent(this.props, e));
            }
        },
        onOk: function () {
            var format = this.props.format;
            var _a = this.data, currentStartDate = _a.currentStartDate, currentEndDate = _a.currentEndDate;
            var realValue = [currentStartDate, currentEndDate];
            if (!this.isControlled()) {
                this.update(realValue);
            }
            if (this.props.onOk) {
                this.props.onOk(realValue, realValue.map(function (v) { return dayjs(v).format(format); }), fmtEvent(this.props));
            }
        },
        onFormatLabel: function (type, value) {
            var onFormatLabel = this.props.onFormatLabel;
            var formatValueByProps = onFormatLabel && onFormatLabel(type, value);
            if (typeof formatValueByProps !== 'undefined') {
                return String(formatValueByProps);
            }
            return this.defaultFormatLabel(type, value);
        },
        defaultFormatLabel: function (type, value) {
            var suffixMap = {
                year: '年',
                month: '月',
                day: '日',
                hour: '时',
                minute: '分',
                second: '秒',
            };
            return "".concat(value).concat(suffixMap[type]);
        },
        defaultFormat: function (date, valueStrs) {
            var _a = this.props, format = _a.format, splitCharacter = _a.splitCharacter;
            if (format && valueStrs && valueStrs[0] && valueStrs[1]) {
                return valueStrs.join("".concat(splitCharacter));
            }
            return '';
        },
        onFormat: function () {
            var _a = this.props, onFormat = _a.onFormat, format = _a.format;
            var realValue = this.getValue();
            var formatValueByProps = onFormat &&
                onFormat(realValue, realValue
                    ? realValue.map(function (v) { return (v ? dayjs(v).format(format) : null); })
                    : null);
            if (typeof formatValueByProps !== 'undefined') {
                return formatValueByProps;
            }
            return this.defaultFormat(realValue, realValue
                ? realValue.map(function (v) { return (v ? dayjs(v).format(format) : null); })
                : null);
        },
        /**
         * 显示/隐藏切换
         * @param visible
         */
        onVisibleChange: function (visible) {
            var onVisibleChange = this.props.onVisibleChange;
            if (visible) {
                this.setData({ pickerType: 'start' });
                this.setCurrentValue(this.props);
            }
            if (onVisibleChange) {
                onVisibleChange(visible, fmtEvent(this.props));
            }
            this.pickerVisible = visible;
        },
        onChangeCurrentPickerType: function (e) {
            var type = e.target.dataset.type;
            var pickerType = this.data.pickerType;
            if (type !== pickerType) {
                this.setData({
                    pickerType: type,
                });
                this.setCurrentValue(this.props);
            }
        },
    },
});
