<template>
<view class="con-body">
    <view class="con-bg">
        <!-- 头部 -->
        <customHeader ref="customHeaderRef" :title="'常用服务'" 
            :leftFlag="true" :rightFlag="false" 
        ></customHeader>
        <!-- 高度来避免头部遮挡 -->
        <view class="top-height"></view>

        <!-- 下拉刷新 -->
        <mescroll-uni ref="mescrollRef" @init="mescrollInit"
            :down="downOption"  @down="downCallback"
            :fixed="false" class="scroll-h"
        >
            <view class="white-bg">
                <view v-for="(item,index) in list" :key="index">
                    <view class="bus-title">{{ item.bizName }}</view>
                    <view class="bus-list">
                        <view class="bus-tips" :class="{'bus-blue':item2.isDaily}" 
                            v-for="(item2,index2) in item.children" :key="index2" 
                            @click="handleCheck(item2)"
                        >
                            {{ item2.bizName }}
                            <view class="bus-icon" v-if="item2.isDaily">
                                <uni-icons type="checkmarkempty" size="12" color="#fff"></uni-icons>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="bottom-height"></view>
            </view>
        </mescroll-uni>

        <!-- 提交按钮 -->
        <view class="bus-btn-con">
            <view class="bus-btn" @click="handleSubmit">提 交（{{count}}）</view>
        </view>
    </view>
</view>
</template>

<script setup>
import { ref,onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app';
import customHeader from '@/components/customHeader.vue'
import MescrollUni from 'mescroll-uni/mescroll-uni.vue';
import { getNavBarPaddingTop} from '@/utils/system.js'
import { businessList,bizFavoriteSetting } from '@/api/business.js';
import { getUserFavorite } from '@/api/home.js';
import {showLoading,hideLoading,showAlert} from '@/utils/message.js'
import { initTree } from '@/utils/common.js'

// 初始化加载
onLoad(async(opt) => {
    uni.setStorageSync('page_cache',true);
    try {
        showLoading("加载中...")
        getList();
        hideLoading();
    } catch (error) {
        hideLoading();
    }
})

// 获取导航栏高度用于内容区域padding
const navBarPaddingTop = ref(0);
onMounted(() => {
    navBarPaddingTop.value = getNavBarPaddingTop()*2;
})

// 查询列表
let list = ref([]);
let count = ref(0);
let bizIds = ref([]);//常用服务列表
let getList = async()=>{
    let arrNew = [];
    bizIds.value = [];
    let res = await businessList({});//查询所有业务
    let arr = res || [];

    let res2 = await getUserFavorite({});//查询当前用户的常用服务
    let arr2 = res2 || [];
    count.value = arr2.length;
    arr2.forEach(item=>{
        bizIds.value.push(item.bizId)
    });
   
    arr.forEach(item=>{
        item.isDaily=false;
        arr2.forEach(item2=>{
            if(item2.bizId==item.bizId){
                item.isDaily=true;
            }
        })
        arrNew.push(item)
    })

    let bizList = initTree(arrNew,0,'bizId');//递归获取数组处理
    bizList.forEach(item => {
        item.expandFlag = false;
    });
    list.value = bizList;
    // console.log("list=>",list.value)
}

// 下拉刷新
const mescrollRef = ref(null);
const mescrollInit = (mescroll) => {
    mescrollRef.value = mescroll;
};
const downOption = ref({
    auto: true,
    textInOffset: '下拉刷新',
    textOutOffset: '释放更新',
    textLoading: '刷新中...'
});

// 下拉刷新
const downCallback = async (mescroll) => {
    try {
        setTimeout(async ()=>{
            // mescroll.resetUpScroll();
        },500);
    } catch (error) {
        mescroll.endErr();
    } finally {
        setTimeout(async ()=>{
            mescroll.endSuccess();
        },500);
    }
}


// 选择常用
const handleCheck=(item)=>{
    item.isDaily = !item.isDaily;
    if(item.isDaily){
        count.value++;
        bizIds.value.push(item.bizId);
    }else{
        count.value--;
        const index = bizIds.value.findIndex(item2 => item2 == item.bizId);
        if (index !== -1) {
            bizIds.value.splice(index, 1);
        }
    }

    // console.log("handleCheck=>bizIds=>",bizIds.value)
}

// 提交
const handleSubmit= async()=>{
    try {
        showLoading("加载中...")
        console.log("bizIds=>",bizIds.value)
        await bizFavoriteSetting({bizIds:bizIds.value.join(",")});
        showAlert("操作成功")
        hideLoading();
        uni.navigateBack();
    } catch (error) {
        hideLoading();
    }
}
</script>

<style scoped>
.scroll-h{
   height: 100vh;
}

.white-bg{
    width: 690rpx;
    margin-bottom:0;
    border-radius: 8px 8px 0 0;
    min-height: calc(100vh - 100px);
}

:deep(.mescroll-upwarp){
  display:none
}

.bus-title{
    font-weight: bold;
    margin:0rpx 0 30rpx;
}

.bus-list{
    display: flex;
    align-items: center;
    flex-flow:row wrap;
    margin:-10rpx;
    margin-bottom:40rpx;
}
.bus-list .bus-tips{
    /* width:210rpx; */
    min-width: calc(100% / 3 - 30px); 
    height:60rpx;
    line-height: 60rpx;
    font-size:28rpx;
    border-radius: 5px;
    text-align: center;
    padding:0 10px;
    background-color: #fff;
    color:#333333;
    border:1px solid #E8E8E8;
    margin-left:8rpx;
    margin-right:8rpx;
    margin-bottom:20rpx;
}

.bus-list .bus-blue{
    border:1px solid #05A3F4;
    background-color: #05A3F4;
    color:#fff;
    position: relative;
}
.bus-list .bus-blue .bus-icon{
    position:absolute;
    right:-10rpx;
    top:-10rpx;
    background-color: #02C74C;
    width:32rpx;
    height:32rpx;
    line-height: 32rpx;
    border-radius: 50%;
    text-align: center;
}

.bus-btn-con{
    position: fixed;
    bottom:0;
    background-color: #fff;
    width:100%;
    padding:70rpx 0;
}
.bus-btn-con .bus-btn{
    background-color: #05A3F4;
    color:#fff;
    text-align: center;
    width:360rpx;
    height:80rpx;
    line-height: 80rpx;
    margin:0 auto;
    border-radius: 40rpx;
}
</style>