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

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

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

    const emits = defineEmits(['register'])

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

    const positionTop = computed(() => cssAdditionCalc(95, 30, data.top))
    const height = computed(() => cssAdditionCalc(30, data.bottom, data.bottomPadding))
    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>) {
        deepMerge(data, value)
    }

    function getProp(key: keyof typeof props) {
        return data[key]
    }

    function onButtonTap(button: ToolBoxButton) {
        if (button.disabled) {
            return
        }

        if (button.type === 'button') {
            button.handle?.({ type: 'click', name: button.name, button })
        } else if (button.type === 'toggle') {
            button.handle?.({ type: 'toggle', name: button.name, button })
        } else if (button.type === 'select') {
            // 打开 Select 组件
            model.selectPopup.title = button.name
            model.selectPopup.options = button.options ?? []
            model.selectPopup.checked = button.options?.filter((item) => item.checked).map((item) => item.value) ?? []
            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: [],
            checked: [],
            onConfirm: (item: Recordable, close?: boolean) => {
                if (model.selectPopup.multiple) {
                    item.checked = !item.checked
                } else {
                    model.selectPopup.options.forEach((option) => (option.checked = false))
                    item.checked = true
                }

                model.activeButton?.handle({
                    type: 'change',
                    name: model.activeButton.name,
                    value: toRaw(
                        model.selectPopup.options[model.selectPopup.multiple ? 'filter' : 'find'](
                            (item) => item.checked,
                        ),
                    ),
                })

                close && model.selectPopup.onClose()
            },
            onClose: () => (model.selectPopup.show = false),
        },
        filterPopup: {
            show: false,
            title: '',
            min: '',
            max: '',
            onConfirm: () => {
                model.activeButton?.handle({
                    type: 'change',
                    name: model.activeButton.name,
                    value: [model.filterPopup.min, model.filterPopup.max],
                })
                model.filterPopup.onClose()
            },
            onRest: () => {
                model.filterPopup.min = ''
                model.filterPopup.max = ''
            },
            onClose: () => (model.filterPopup.show = false),
        },
    })

    emits('register', {
        setProps,
        getProp,
        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" :style="{ color: item.color || '#666' }">{{ item.name }}</view>

                        <!-- TODO: 过滤的结果展示 -->
                        <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 yr-toolbox-style">
            <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
            :type="model.selectPopup.multiple ? 'select' : 'list'"
            :show="model.selectPopup.show"
            :title="`选择${model.selectPopup.title}`"
            :options="model.selectPopup.options"
            :multiple="model.selectPopup.multiple"
            @click="model.selectPopup.onConfirm"
            @confirm="model.selectPopup.onConfirm"
            @close="model.selectPopup.onClose"
        /> -->
        <fui-bottom-popup
            :show="model.selectPopup.show"
            :z-index="900"
            @close="model.selectPopup.onClose"
            :safeArea="false"
        >
            <view class="popup-wrap">
                <view class="fui-title">{{ `选择${model.selectPopup.title}` }}</view>
                <view class="fui-icon__close" @tap="model.selectPopup.onClose">
                    <fui-icon name="close" :size="48" />
                </view>
                <scroll-view scroll-y class="fui-scroll__view">
                    <view class="fui-custom__wrap">
                        <!-- 多选 -->
                        <template v-if="model.selectPopup.multiple">
                            <fui-checkbox-group>
                                <fui-label
                                    v-for="(item, index) in model.selectPopup.options"
                                    :key="index"
                                    @tap="model.selectPopup.onConfirm(item, false)"
                                >
                                    <fui-list-cell>
                                        <view class="fui-align__center">
                                            <fui-checkbox v-model:checked="item.checked" :value="item.value" />
                                            <text class="fui-text pl-2">{{ item.text }}</text>
                                        </view>
                                    </fui-list-cell>
                                </fui-label>
                            </fui-checkbox-group>
                        </template>
                        <!-- 单选 -->
                        <template v-else>
                            <!--  -->
                            <fui-radio-group>
                                <fui-label
                                    v-for="(item, index) in model.selectPopup.options"
                                    :key="index"
                                    @tap="model.selectPopup.onConfirm(item, true)"
                                >
                                    <fui-list-cell>
                                        <view class="fui-align__center">
                                            <fui-radio :checked="item.checked" :value="item.value" />
                                            <text class="fui-text pl-2">{{ item.text }}</text>
                                        </view>
                                    </fui-list-cell>
                                </fui-label>
                            </fui-radio-group>
                        </template>
                    </view>
                </scroll-view>
            </view>

            <!-- 底部安全区 -->
            <fui-safe-area />
        </fui-bottom-popup>

        <!-- 2. 过滤 Popup -->
        <fui-bottom-popup
            :show="model.filterPopup.show"
            :z-index="900"
            @close="model.filterPopup.onClose"
            :safeArea="false"
        >
            <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-safe-area />
        </fui-bottom-popup>
    </view>
</template>

<style lang="scss" scoped>
    .wrap {
        transition: all 0.35s;
    }

    .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.2);
            margin-top: 30rpx;

            .text {
                margin-right: 6rpx;
            }

            .icon {
                transition: all 0.35s;

                transform: rotate(0);
            }

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

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

        .bottom {
            transition: all 0.35s;

            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.2);
            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: 520rpx;
        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>
