<template>
    <view :class="['u-theme-' + cTheme]" :data-body="appendToBody">
        <div class="modal" :class="{'popup-show': show}" @touchmove.stop.prevent="moveStop" @click.stop.prevent="closeMask">
            <div class="content" :class="{'popup-show': show, 'safe-area-inset-bottom': safeAreaInsetBottom}" @click.stop.prevent="moveStop">
                <div class="types" v-if="tabList.length > 1">
                    <div class="type" :class="[typeSelected === type  ? 'typeSelected' : '']" v-for="type in tabList" :key="type" @click="selTypes(type)">{{typesToName(type)}}</div>
                </div>
                <date-timePanel :typeSelected="typeSelected" :valueList="valSelected" :onPickerCancel="onCancel" :onPickerConfirm="onConfirm" ref="dateTimePanelRef" />
            </div>
        </div>
    </view>
</template>

<script>
import propsDefault from './props';
import moment, { timeTypeDefault } from './common/timePickerContant';
import DateTimePanel from './panel/DateTimePanel.vue'

export default {
    name: 'DateTimeGroupPicker',
    emits: ["onPickerCancel", "update:modelValue", "input", "onPickerConfirm"],
    data() {
        return {
            typeSelected: null, //当前切换时间类型
            valSelected: null, //当前切换时间值
            tabList: null, //tab的选项数组
            tab: null, //当前time类型的选项
        };
    },
    props: {
        ...propsDefault,
        ...{
            value: {
                validator: function (value) {
                    return true
                },
                default: () => {
                    return timeTypeDefault.hour.value
                }
            }, //默认时间
            modelValue: {
                validator: function (value) {
                    return true
                },
                default: () => {
                    return timeTypeDefault.hour.value
                }
            },
            types: {
                type: Array,
                default: () => {
                    return ['hour', 'day', 'month', 'quarter', 'year']
                } //时间类型数组
            },
            // 关怀模式: normal, care
            theme: {
                type: String,
                default: ''
            },
            safeAreaInsetBottom: {
                type: Boolean,
                default: true
            },
            // 是否可以通过点击遮罩进行关闭
			maskClickAble: {
				type: Boolean,
				default: true
			},
			//是否把$el绑定到body -- h5、app
			appendToBody: {
				type: String,
				default: '0' // '0' || '1'
			},
        }
    },
    // filters: {
    //     typesToName: function (type) {
    //         return timeTypeDefault[type].name
    //     }
    // },
    computed: {
        cTheme() {
            return this.theme || (uni.$u || {}).theme;
        },
        typesToName() {
            return function(type) {
                return timeTypeDefault[type].name
            }
        },
        compConfig() {
            return { ...this.$props, tabList: this.tabList, tab: this.tab }
        }
    },
    watch: {
        type: {
            immediate: true,
            handler: function (val) {
                if (this.mode === 'timerange') {
                    val = `${val}range`
                }
                // console.log('这是type', val);
                this.tab = val
                this.typeSelected = val
                this.curDateTimeType = val
            }
        },
        types: {
            immediate: true,
            handler: function (val) {
                let list = val
                if (this.mode === 'timerange') {
                    list = val.map(item => {
                        return `${item}range`
                    });
                }
                this.tabList = list
                // console.log('这是types', this.tabList);
            }
        },
        value: {
            immediate: true,
            handler: function (val) {
                this.valSelected = val
                this.curDateTimeVal = val
            }
        },
        modelValue: {
            immediate: true,
            handler: function (val) {
                this.valSelected = val
                this.curDateTimeVal = val
            }
        }
    },
    provide() {
        return {
            config: () => this.compConfig
        }
    },
    components: {
        DateTimePanel
    },
    mounted() {
        // console.log(this.$props)
    },
    methods: {
        /**
         * 解决滚动穿透
         */
        moveStop() { },
        /**
         * 点击类型切换
         */
        selTypes(type) {
            if (this.typeSelected === type) {
                return
            }
            this.tab = type
            this.typeSelected = type
            this.curDateTimeType = type
            // console.log(timeTypeDefault[type].default);
            // if(Array.isArray(timeTypeDefault[type].default)){

            // console.log(timeTypeDefault[type].default[0].getMonth() + 1,timeTypeDefault[type].default[1].getMonth() + 1);
            // }else{
            //     console.log(timeTypeDefault[type].default.getMonth() + 1);

            // }
            this.valSelected = timeTypeDefault[type].default
            this.$emit('onChangeTab', type)
        },
        /**
         * 点击蒙层关闭
         */
        closeMask() {
            if (!this.maskClickAble) return;
            this.$refs.dateTimePanelRef && this.$refs.dateTimePanelRef.onCancel()
        },
        /**
         * 取消按钮
         */
        onCancel() {
            this.$emit('onPickerCancel', 'cancel')
        },
        /**确认按钮
         * @param {Object} selectedValueDate
         */
        onConfirm(selectedValueDate) {
            this.curDateTimeVal = selectedValueDate
            this.$emit('input', selectedValueDate)
            this.$emit('update:modelValue', selectedValueDate)
            this.$emit('onPickerConfirm', selectedValueDate, this.typeSelected)
        },
        /**
         * 点击取消按钮或者遮罩关闭picker，重置picker已选为当前时间
         */
        _cancelPicker() {
            this.typeSelected = this.curDateTimeType
            this.valSelected = this.curDateTimeVal
            this.$refs.dateTimePanelRef && this.$refs.dateTimePanelRef.cancelPicker()
        },
        /**
         * 加减指定个时间类型的时间
         * @param number 加减时间个数（例：前一年：-1，后一年：1）
         */
        // addOneTime(number) {
        //     if (!number || isNaN(number) || !this.type || this.type.indexOf('range') > -1 || this.curDateTimeVal ===
        //         'lastMonths') {
        //         return;
        //     }
        //     if (this.curDateTimeVal) {
        //         //当前时间加减指定个数时间后
        //         let newTime = moment(this.curDateTimeVal)
        //             .add(number, this.type + 's')
        //             .startOf(this.type);
        //         //禁用日期
        //         if (this.disabledDate && this.disabledDate(newTime.toDate())) {
        //             return;
        //         }
        //         //小于开始年
        //         if (number < 0 && this.startYear) {
        //             if (newTime.isBefore(moment(this.startYear, 'YYYY').startOf('year'))) {
        //                 return;
        //             }
        //         }
        //         //大于结束年
        //         if (number > 0 && this.endYear) {
        //             if (newTime.isAfter(moment(this.endYear, 'YYYY').endOf('year'))) {
        //                 return;
        //             }
        //         }
        //         //设置当前时间为新时间
        //         this.curDateTimeVal = newTime.toDate()

        //         //回调
        //         if (typeof this.onPickerConfirm === 'function') {
        //             this.onPickerConfirm(newTime.toDate())
        //         }
        //     }
        // }
    }
}
</script>
//#ifdef APP || H5
<script module="datePickModule" lang="renderjs">
export default {
    mounted() {
		const el = this.$ownerInstance.$el
		if(el.getAttribute('data-body') === '1'){
			document.body.appendChild(el);
		}
    },
	//#ifdef VUE2
	beforeDestroy() {
		const el = this.$ownerInstance.$el
		if(el.getAttribute('data-body') === '1'){
			el.parentNode.removeChild(el);
		}
	},
	//#endif
	//#ifdef VUE3
	beforeUnmount() {
		const el = this.$ownerInstance.$el
		if(el.getAttribute('data-body') === '1'){
			el.parentNode.removeChild(el);
		}
	},
	//#endif
}
</script>
//#endif

<style lang="scss">
@import "./style/uview.theme.scss";

@include themify($themes) {
.modal {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.3);
    z-index: 2000;
    transition: all 0 ease;
    transform: translateY(100%);
}

.content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 2001;
    transition: all 0.3s ease;
    transform: translateY(100%);
    background-color: #fff;
}
.popup-show {
    transform: translateY(0);
}

.types {
    display: flex;
    height: themed('grid-size-48');
    line-height: themed('grid-size-48');
    border-radius: 12px 12px 0 0;
    background: #fff;
    padding: 0 16px;
    text-align: center;

    .type {
        color: themed('u-tips-color');
        padding: 0 8px;
        display: inline-block;
		font-size: themed('font-size-14');
        flex: 1;
    }

    .type + .type {
        // padding-left: 40px;
    }

    .typeSelected {
        color: themed('u-main-color');
        font-weight: bold;
        border-bottom: 3px solid themed('u-type-primary');
    }
}
}
</style>
