<template>
    <!-- 全局page 不带tab切换-->
    <z-paging
        ref="paging"
        v-model="dataList"
        :auto="auto || showEmpty"
        :fixed="fixed"
        :height="height"
        :refresher-enabled="refresherEnabled"
        :refresher-threshold="refresherThreshold"
        :auto-show-back-to-top="autoShowBackToTop"
        :loading-more-enabled="loadingMoreEnabled"
        :back-to-top-bottom="backToTopBottom"
        show-refresher-update-time
        :hide-empty-view="!(auto || showEmpty)"
        @query="queryList"
        @scroll="scroll"
        :paging-style="getPagingStyle"
        :default-page-size="pageSize"
    >
        <template #empty v-if="showEmpty || (auto && !dataList.length)">
            <global-empty></global-empty>
        </template>
        <!-- 头部 -->
        <template #top>
            <view
                style="position: relative; z-index: -2"
                :style="{ height: safeAreaInsets?.top + 'px', background: navbgColor }"
                v-if="custom"
            ></view>
            <!-- 自定义导航栏 -->
            <global-navbar :title="title" v-if="showNavbar" :bgColor="navbgColor" :color="navColor">
                <template #left v-if="pages.length > 1 && showNavLeft">
                    <up-icon v-if="navLeftType == 'icon'" :name="navLeftIcon" size="16" @tap="handleLeftClick" :color="navColor"></up-icon>
                    <view v-if="navLeftType == 'text'" class="cancel" @tap="handleLeftClick">{{ navLeftText }}</view>
                </template>
                <template #right v-if="showNavRight">
                    <global-button type="text" size="small" v-if="navRightType == 'text'" @tap="handleRightClick" :disabled="navRightDisabled">
                        {{ navRightText }}
                    </global-button>
                    <global-button
                        type="primary"
                        :disabled="navRightDisabled"
                        size="small"
                        v-if="navRightType == 'button'"
                        style="padding: 0 32rpx"
                        @tap="handleRightClick"
                    >
                        {{ navRightText }}
                    </global-button>
                    <global-icon v-if="navRightType == 'icon'" :icon="navRightIcon" @tap="handleRightClick"></global-icon>
                </template>
            </global-navbar>
            <slot name="top"></slot>
        </template>
        <!-- 滚动内容 -->
        <view class="mocp-content" :style="getStyle">
            <template v-if="isDataList || localData">
                <up-checkbox-group v-model="chooseValue" v-if="chooseDataType == 'checkbox'">
                    <template v-for="(item, index) in dataList" :key="index">
                        <up-checkbox :name="index" v-if="chooseDataType == 'checkbox'">
                            <template #label>
                                <slot :item="item" :index="index"></slot>
                            </template>
                        </up-checkbox>
                    </template>
                </up-checkbox-group>
                <template v-for="(item, index) in dataList" :key="index" v-else>
                    <slot :item="item" :index="index"></slot>
                </template>
            </template>
            <slot v-else></slot>
        </view>
        <!-- 底部 -->
        <template #bottom>
            <view class="footer-btn" v-if="showFooterBtn">
                <global-button type="primary" size="large" @tap="handleFooterClick">{{ footerBtnText }}</global-button>
            </view>
            <slot name="bottom"></slot>
        </template>
        <!-- 消息提醒 -->
        <up-toast ref="uToastRef"></up-toast>
    </z-paging>
</template>
<script setup>
import { filterEmptyValues } from 'mocp/utils/tool'
import { computed, nextTick, onUnmounted, ref, watch } from 'vue'

const dataList = ref([])
const es = defineEmits(['handleQuery', 'handleLeftClick', 'handleRightClick', 'handleFooterClick', 'handleChooseData'])
const paging = ref()
const ps = defineProps({
    showEmpty: {
        type: Boolean,
        default: false
    },
    background: {
        type: String,
        default: '#f7f8fa'
    },
    padding: {
        type: [String, Number],
        default: 0
    },
    margin: {
        type: [String, Number],
        default: 0
    },
    //是页面滚动还是局部滚动(默认页面滚动)
    fixed: {
        type: Boolean,
        default: true
    },
    //局部滚动的高度
    height: {
        type: String,
        default: ''
    },
    //是否自动加载
    auto: {
        type: Boolean,
        default: false
    },
    //是否展示自定义导航栏
    showNavbar: {
        type: Boolean,
        default: true
    },
    //导航栏背景色
    navbgColor: {
        type: String,
        default: '#f7f8fa'
    },
    //导航栏字体颜色
    navColor: {
        type: String,
        default: '#4e5969'
    },
    //是否显示nav左边插槽
    showNavLeft: {
        type: Boolean,
        default: true
    },
    //nav左边插槽类型:icon,text
    navLeftType: {
        type: String,
        default: 'icon'
    },
    //nav左边插槽图标
    navLeftIcon: {
        type: String,
        default: 'arrow-left'
    },
    //nav左边插槽文字
    navLeftText: {
        type: String,
        default: '取消'
    },
    //点击nav左边插槽default,emit
    navLeftClick: {
        type: String,
        default: 'default'
    },
    //是否显示nav右边插槽
    showNavRight: {
        type: Boolean,
        default: false
    },
    //nav右边插槽类型:icon,text,button
    navRightType: {
        type: String,
        default: 'text'
    },
    //nav右边插槽图标
    navRightIcon: {
        type: String,
        default: 'navbarright'
    },
    //nav右边插槽文字
    navRightText: {
        type: String,
        default: '编辑'
    },
    navRightDisabled: {
        type: Boolean,
        default: false
    },
    //是否显示底部按钮
    showFooterBtn: {
        type: Boolean,
        default: false
    },
    //底部按钮文字内容
    footerBtnText: {
        type: String,
        default: '保存'
    },
    //页面标题
    title: {
        type: String,
        default: ''
    },
    //是否关闭原生导航栏
    custom: {
        type: Boolean,
        default: true
    },
    //是否展示列表
    isDataList: {
        type: Boolean,
        default: false
    },
    //选择数据的类型'checkbox' | 'radio'
    chooseDataType: {
        type: String,
        default: ''
    },
    mapFieldName: {
        type: String,
        default: ''
    },
    mapFieldSplit: {
        type: String,
        default: ','
    },
    //查询参数
    params: {
        type: Object,
        default: () => {
            return {}
        }
    },
    //查询接口
    api: {
        type: Function,
        default: null
    },
    //是否开启下拉刷新
    refresherEnabled: {
        type: Boolean,
        default: false
    },
    refresherThreshold: {
        type: [String, Boolean],
        default: '150rpx'
    },
    //是否启用加载更多数据
    loadingMoreEnabled: {
        type: Boolean,
        default: false
    },
    autoShowBackToTop: {
        type: Boolean,
        default: true
    },
    backToTopBottom: {
        type: [Number, String],
        default: '160rpx'
    },
    //静态数据
    localData: {
        type: [Object, Array],
        default: null
    },
    //是否本地分页
    localPaging: {
        type: Boolean,
        default: false
    },
    //数据转换
    transformData: {
        type: Function,
        default: null
    },
    //分页页码
    pageSize: {
        type: Number,
        default: 10
    }
})
// z-page样式
const getPagingStyle = computed(() => {
    return {
        fontSize: '28rpx',
        background: ps.background
    }
})
//滚动区域样式
const getStyle = computed(() => {
    let padding = typeof ps.padding == 'number' ? ps.padding + 'rpx' : ps.padding
    let margin = typeof ps.margin == 'number' ? ps.margin + 'rpx' : ps.margin
    let style = {
        margin,
        padding
    }
    return style
})
//监听滚动
const scrollTime = ref(null)
const scroll = () => {
    // #ifdef APP
    if (scrollTime.value) {
        clearTimeout(scrollTime.value)
    }
    scrollTime.value = setTimeout(() => {
        uni.$emit('$upload-show', {})
    }, 500)
    // #endif
}
//监听选择
const chooseValue = ref([])
watch(chooseValue, (value) => {
    let data = value.map((index) => dataList.value[index])
    if (ps.mapFieldName) {
        data = data.map((v) => v[ps.mapFieldName]).join(ps.mapFieldSplit)
    }
    es('handleChooseData', data)
})
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
//列表加载
const queryList = (pageIndex, pageSize) => {
    if (ps.isDataList) {
        const params = {
            ...filterEmptyValues(ps.params)
        }
        //是否开启本地分页
        if (!ps.localPaging) {
            params['pageIndex'] = pageIndex
            params['pageSize'] = pageSize
        }
        if (Object.prototype.toString.call(ps.api) == '[object Function]') {
            ps.api(params, { loading: true })
                .then((res) => {
                    if (res.code == 200 || res.list?.length) {
                        let data = res.list || res.data?.list || res?.data || []
                        if (ps.transformData) {
                            data = ps.transformData(data) || []
                        }
                        if (ps.localPaging) {
                            paging.value?.setLocalPaging(data)
                        } else {
                            paging.value?.complete(data)
                        }
                        es('handleQuery', { pageIndex, pageSize, res })
                    } else {
                        paging.value?.complete(false)
                        uni.$mocpMessage.error(res.message)
                    }
                })
                .catch(() => {
                    paging.value?.complete(false)
                })
        } else {
            paging.value?.complete(false)
        }
    } else {
        if (ps.localData) {
            paging.value?.complete(ps.localData || [])
        } else if (ps.showEmpty) {
            paging.value?.complete([])
        } else {
            paging.value?.complete(true)
        }
        es('handleQuery', { pageIndex, pageSize })
    }
}
//点击左边插槽
const handleLeftClick = () => {
    if (ps.navLeftClick == 'default') {
        uni.$mocpJump.navigateBack()
        es('handleLeftClick')
    } else {
        es('handleLeftClick')
    }
}
//点击右边插槽
const handleRightClick = () => {
    if (!ps.navRightDisabled) {
        es('handleRightClick')
    }
}
//消息提示
const uToastRef = ref()
const openToast = (params) => {
    nextTick(() => {
        uToastRef.value?.show(params)
    })
}
uni.$on('useMessage', (params) => openToast(params))
onUnmounted(() => {
    uni.$off('useMessage', openToast)
})
//点击底部按钮
const handleFooterClick = () => {
    es('handleFooterClick')
}
// 获取页面栈
const pages = getCurrentPages()
defineExpose({
    reload: () => {
        chooseValue.value = []
        paging.value?.reload()
    },
    updateCache: () => {
        chooseValue.value = []
        paging.value?.updateCache()
    },
    element: paging
})
</script>
<script>
export default {
    options: {
        styleIsolation: 'shared'
    }
}
</script>
<style lang="scss" scoped>
.mocp-content {
    // 表单内容
    :deep(.u-form-item__body) {
        padding: 24rpx 0 !important;
        .u-form-item__body__left__content__label {
            color: $mocp-text-5 !important;
            font-size: 28rpx !important;
        }
        .u-input__content__field-wrapper__field {
            color: $mocp-text-4 !important;
        }
        .u-textarea {
            margin-top: 8rpx;
            .u-textarea__field {
                font-size: 28rpx !important;
                color: $mocp-text-4 !important;
            }
        }
    }
    //多选框
    :deep(.u-checkbox__icon-wrap) {
        min-width: 18px;
    }
}
.cancel {
    font-size: 28rpx;
}
.footer-btn {
    padding: 24rpx 32rpx;
    background-color: #fff;
}
</style>
