<!-- 左侧工具盒子控制组件 -->

<script setup lang="ts">
    import { createReusableTemplate } from '@vueuse/core'
    import type { ToolBoxButton, ToolBoxButtonGroup } from './types'

    const props = defineProps({
        // 显示
        show: {
            type: Boolean,
            default: true,
        },
        // 展开
        expand: {
            type: Boolean,
            default: false,
        },
        // 是否显示是否展开按钮
        showExpandButton: {
            type: Boolean,
            default: false,
        },
        // 顶部距离 rpx
        top: {
            type: String,
            default: '1rpx',
        },
        // 底部距离 rpx
        bottom: {
            type: String,
            default: '1rpx',
        },
        // 底部内边距 rpx (用于避免遮挡)
        bottomPadding: {
            type: String,
            default: '1rpx',
        },
        // 工具集
        tools: {
            type: Array as PropType<ToolBoxButtonGroup[]>,
            default: () => [],
        },
    })

    const emits = defineEmits(['register'])

    // 定义复用渲染组件
    const [DefineTemplate, ReuseTemplate] = createReusableTemplate<{ items: ToolBoxButton[] }>()

    const positionTop = computed(() => `calc(125rpx + ${data.top})`)
    const height = computed(() => `calc(30rpx + ${data.bottomPadding} + ${data.bottom})`)
    const data = reactive({
        show: props.show,
        expand: props.expand,
        showExpandButton: props.showExpandButton,
        top: props.top,
        bottom: props.bottom,
        bottomPadding: props.bottomPadding,
        tools: props.tools,
    })

    function toggleShow(show?: boolean) {
        data.show = show ?? !data.show
    }

    function toggleExpand(expand?: boolean) {
        data.expand = expand ?? !data.expand
    }

    function setProps(value: Partial<typeof props>) {
        Object.assign(data, value)
    }

    function onButtonTap(button: ToolBoxButton) {
        console.log('onButtonTap', button)

        if (button.disabled) {
            return
        }

        if (button.type === 'button') {
            button.handle?.({ type: 'click', name: button.name })
        } else if (button.type === 'select') {
            // 打开 Select 组件
            model.selectPopup.title = button.name
            model.selectPopup.options = button.options ?? []
            model.selectPopup.multiple = button.multiple ?? false
            model.selectPopup.show = true
        } else if (button.type === 'filter') {
            // 打开 Filter 组件
            model.filterPopup.title = button.name
            model.filterPopup.show = true
        }

        // 设置当前激活的按钮
        model.activeButton = button
    }

    const zIndex = computed(() => (model.selectPopup.show || model.filterPopup.show ? 200 : 100))
    const model = reactive({
        activeButton: null as ToolBoxButton | null,
        selectPopup: {
            show: false,
            multiple: false,
            title: '',
            options: [],
            onConfirm: (e: Recordable) => {
                console.log('onConfirm', e)
                model.activeButton?.handle({
                    type: 'change',
                    name: model.activeButton.name,
                    value: toRaw(e.options),
                })
                model.selectPopup.onClose()
            },
            onClose: () => (model.selectPopup.show = false),
        },
        filterPopup: {
            show: false,
            title: '',
            min: '',
            max: '',
            onConfirm: () => {
                console.log('onConfirm', model.filterPopup.min, model.filterPopup.max)
                model.activeButton?.handle({
                    type: 'change',
                    name: model.activeButton.name,
                    value: [model.filterPopup.min, model.filterPopup.max],
                })
                model.filterPopup.onClose()
            },
            onRest: () => {
                console.log('onRest')
                model.filterPopup.min = ''
                model.filterPopup.max = ''
            },
            onClose: () => (model.filterPopup.show = false),
        },
    })

    emits('register', {
        setProps,
        toggleShow,
        toggleExpand,
    })
</script>

<template>
    <view class="wrap tool-box">
        <DefineTemplate v-slot="{ items }">
            <view class="button-group flex-center" v-show="data.expand">
                <template v-for="(item, index) in items" :key="`tool_box_button_${index}_${item.name}`">
                    <view class="button flex-center" :class="{ disabled: item.disabled }" @tap="onButtonTap(item)">
                        <CacheImage class="icon" :src="item.icon" width="40" height="40" background="transparent" />
                        <view class="text">{{ item.name }}</view>

                        <!-- 过滤的结果展示 -->
                        <view v-if="item.type === 'filter'" class="result">
                            <view class="text">{{ item.result }}</view>
                        </view>
                    </view>

                    <fui-divider v-if="index !== items.length - 1" :height="4" />
                </template>
            </view>
        </DefineTemplate>

        <view class="top">
            <template v-for="tool in data.tools.filter((item) => item.align === 'top')" :key="`group_${tool.key}`">
                <ReuseTemplate :items="tool.buttons" />
            </template>
        </view>
        <view class="bottom">
            <template v-for="tool in data.tools.filter((item) => item.align === 'bottom')" :key="`group_${tool.key}`">
                <ReuseTemplate :items="tool.buttons" />
            </template>

            <!-- 展开/收起操作按钮 -->
            <view
                v-if="data.showExpandButton"
                class="expand-action flex-center"
                :class="{ expand: data.expand }"
                @tap="data.expand = !data.expand"
            >
                <view class="text">{{ data.expand ? '收起' : '展开' }}</view>
                <Icon icon="ic-round-keyboard-arrow-up" size="42" color="#1890ff" class="icon" />
            </view>
        </view>

        <!-- 交互组件 -->
        <!-- 1. Select Popup -->
        <fui-select
            maskClosable
            :show="model.selectPopup.show"
            :title="`选择${model.selectPopup.title}`"
            :options="model.selectPopup.options"
            :multiple="model.selectPopup.multiple"
            @confirm="model.selectPopup.onConfirm"
            @close="model.selectPopup.onClose"
        />

        <!-- 2. 过滤 Popup -->
        <fui-bottom-popup
            :show="model.filterPopup.show"
            :z-index="900"
            @close="model.filterPopup.onClose"
            :safeArea="true"
        >
            <view class="popup-wrap">
                <view class="fui-title">{{ model.filterPopup.title }}</view>
                <view class="fui-icon__close" @tap="model.filterPopup.onClose">
                    <fui-icon name="close" :size="48" />
                </view>
                <scroll-view scroll-y class="fui-scroll__view">
                    <view class="fui-custom__wrap">
                        <view class="branch">
                            <view class="title">阈值范围（仅支持数值）</view>
                            <view class="timeBox">
                                <!--  -->
                                <fui-input
                                    type="number"
                                    borderTop
                                    isFillet
                                    inputBorder
                                    maxlength="10"
                                    backgroundColor="#F5F5F5"
                                    placeholder="最小值"
                                    v-model="model.filterPopup.min"
                                />
                                <view class="mark split" />
                                <fui-input
                                    type="number"
                                    borderTop
                                    isFillet
                                    inputBorder
                                    maxlength="10"
                                    backgroundColor="#F5F5F5"
                                    placeholder="最大值"
                                    v-model="model.filterPopup.max"
                                />
                            </view>
                        </view>
                        <view class="signMan">
                            <fui-button
                                width="330rpx"
                                height="86rpx"
                                radius="86rpx"
                                text="重置"
                                background="#FFFFFF"
                                border-color="#AAAAAA"
                                color="#AAAAAA"
                                :margin="['70rpx', '0rpx', '0rpx', '30rpx']"
                                @click="model.filterPopup.onRest"
                            />
                            <fui-button
                                width="330rpx"
                                height="90rpx"
                                radius="90rpx"
                                text="确定"
                                background="#1890FF"
                                color="#FFFFFF"
                                :margin="['70rpx', '30rpx', '0rpx', '0rpx']"
                                @click="model.filterPopup.onConfirm"
                            />
                        </view>
                    </view>
                </scroll-view>
            </view>
        </fui-bottom-popup>
    </view>
</template>

<style lang="scss" scoped>
    @import '../../common.scss';

    .wrap {
        @include animate();
    }

    .tool-box {
        .expand-action {
            font-size: 26rpx;
            font-weight: bold;
            color: #1890ff;
            padding: 12rpx 20rpx;
            background-color: #fff;
            border-radius: 10rpx;
            box-shadow: 0 0 15rpx rgba(0, 0, 0, 0.3);
            margin-top: 30rpx;

            .text {
                margin-right: 6rpx;
            }

            .icon {
                @include animate();

                transform: rotate(0);
            }

            &.expand {
                .icon {
                    transform: rotate(180deg) !important;
                }
            }
        }

        .top {
            position: absolute;
            top: v-bind(positionTop);
            right: 30rpx;
            z-index: v-bind(zIndex);
        }

        .bottom {
            @include animate();

            position: absolute;
            right: 30rpx;
            bottom: v-bind(height);
            z-index: v-bind(zIndex);

            display: flex;
            flex-direction: column;
            align-items: flex-end;
        }

        .button-group {
            flex-direction: column;
            box-shadow: 0 0 15rpx rgba(0, 0, 0, 0.3);
            background-color: white;
            border-radius: 10rpx;
            padding: 5rpx 0;
            width: 95rpx;

            + .button-group {
                margin-top: 30rpx;
            }

            .button {
                flex-direction: column;
                font-size: 24rpx;
                color: #666;
                padding: 10rpx;
                min-width: 80rpx;

                &.disabled {
                    filter: grayscale(1);
                }

                .text {
                    margin-top: 5rpx;
                }
            }
        }
    }

    .popup-wrap {
        height: 500rpx;
        padding-top: 30rpx;
        position: relative;
    }

    .fui-custom__wrap {
        width: 100%;
        display: flex;
        align-items: center;
        flex-direction: column;
        font-size: 28rpx;

        .branch {
            margin-top: 30rpx;
            width: 690rpx;
            display: flex;
            flex-direction: column;

            .title {
                font-size: 32rpx;
                font-weight: bold;
                color: #333;
            }

            .timeBox {
                width: 100%;
                margin-top: 30rpx;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .mark {
                    width: 20rpx;
                    height: 4rpx;
                    background: #ddd;
                    margin: 0 20rpx;
                }

                .timeSelect {
                    width: 260rpx;
                    height: 80rpx;
                    padding: 0 30rpx;
                    background: #f4f5f9;
                    border-radius: 45rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    overflow: hidden;

                    .text {
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                }

                .selected {
                    background: #f3f9ff;
                    color: #1890ff;
                    border: 2rpx solid #1890ff;
                }
            }

            .typeBox {
                width: 100%;
                margin-top: 10rpx;
                display: flex;
                align-items: center;
                flex-wrap: wrap;

                .typeSelect {
                    width: 156rpx;
                    height: 80rpx;
                    margin-top: 20rpx;
                    padding: 0 30rpx;
                    background: #f4f5f9;
                    border-radius: 45rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border: 2rpx solid #f4f5f9;
                    overflow: hidden;

                    .text {
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }

                    + .typeSelect {
                        margin-left: 20rpx;
                    }
                }

                .typeSelected {
                    background: #f3f9ff;
                    color: #1890ff;
                    border: 2rpx solid #1890ff;
                }
            }
        }

        .signMan {
            width: 100%;
            background: #fff;
            margin-bottom: 70rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .handleBtn {
            border: 1rpx solid #aaa;
            border-radius: 86rpx;
        }
    }

    .fui-title {
        font-size: 32rpx;
        font-weight: bold;
        text-align: center;
        padding-bottom: 24rpx;
    }

    .fui-icon__close {
        position: absolute;
        top: 20rpx;
        right: 30rpx;
    }

    .fui-scroll__view {
        width: 100%;
        height: 790rpx;
    }
</style>
