/**
 * 用户信息类
 */
import { getStorage, setStorage } from "@/utils/storage";
import { onPullDownRefresh, onShow, onLoad } from "@dcloudio/uni-app";
import { computed, onBeforeUnmount, ref } from "vue";
import { timeFormatD } from "@/utils/tools";
import { store } from "@/store";
import useGlobalFunc from "@/composables/useGlobalFunc";

function userInfo() {
    // vuex
    const { newMessage, logOutFn, getMtStoreIMStatus } = useGlobalFunc()


    /**
     * 门店自动营业时间
     */
    const newAutoEnableAt = ref<string>('')
    const switchOpenTime = computed(() => {
        if (newAutoEnableAt.value) {
            let now = +new Date(timeFormatD(+new Date()));
            let time = +new Date(timeFormatD(newAutoEnableAt.value));
            let num = time - now;
            if (num < 0) {
                return "营业时间错误请联系运营";
            } else {
                let day = num / 1000 / 3600 / 24;
                if (day < 1) return "门店将在今天自动营业";
                else if (day >= 1 && day < 2) return "门店将在明天自动营业";
                else if (day >= 2 && day < 3) return "门店将在后天自动营业";
                else return `将在 ${timeFormatD(newAutoEnableAt.value)} 自动营业`;
            }
        } else {
            return "";
        }
    })

    /**
     * 下拉刷新
     */
    let onPullDownRefreshTimer: any = null
    onPullDownRefresh(async () => {
        await getStores()
        clearTimeout(onPullDownRefreshTimer)
        onPullDownRefreshTimer = setTimeout(() => {
            uni.stopPullDownRefresh()
        }, 1000)
    })

    /**
     * 用户头像、门店名字
     */
    interface StoreInfoType {
        avatar: string;
        storeName: string;
    }
    const storeInfo = ref<StoreInfoType>({
        avatar: "https://image.jxc4.com/image/70143fcf48aefe74537533f35a0a8153.jpg",
        storeName: "",
    });
    let oldStoreID: any = 0
    onShow(async () => {
        getStores()
        storeInfo.value.storeName = getStorage("storeName")
        if (oldStoreID != getStorage('storeID') && oldStoreID != 0) {
            uni.startPullDownRefresh({})
        }
        oldStoreID = getStorage('storeID')
    });
    onLoad(async () => {
        await getStores()
        await newMessage()        // 商家中心有新信息了
    })

    const businessHours = ref<AnyObject>({})
    async function getStores() {
        await store.dispatch('storeInfo/getOneStore',getStorage("storeID"))
        businessHours.value = store.getters['storeInfo/businessHours']  // 营业时间
        newAutoEnableAt.value = store.getters['storeInfo/newAutoEnableAt']  // 手机门店休息时间

        await getMtStoreIMStatus()   // 获取门店的IM单聊开关状态

        await newMessage()        // 商家中心有新信息了
    }


    /*************************************************
     * 去修改营业时间
    */
    function setTime() {
        uni.navigateTo({ url: `/subPages/merchantChild/setBusinessTime/setBusinessTime` })
    }


    /**
     * 退出登录
     */
    let goLoginTime: any = null
    function goLogin() {
        uni.showActionSheet({
            title: '退出后不会删除任何数据',
            itemColor: '#e70808',
            itemList: ['退出登录'],
            popover: {
                width: 5000,
            },
            success: function (res) {
                logOutFn();
                // uni.navigateTo({ url: '/subPages/login/wxLogin/wxLogin' })
                uni.reLaunch({ url: '/subPages/login/wxLogin/wxLogin' })
            },
            fail: () => {
                console.log('ZSW-取消退出');
            }
        });
    }

    /**
     * 切换门店
     */
    function switchStore() {
        uni.navigateTo({ url: "/subPages/switchStore/switchStore" });
    }

    /**
     * 跳转到设置营业状态页面
     */
    function jumpBusinessStatus() {
        uni.navigateTo({
            url: '/subPages/merchantChild/setBusinessStatus/setBusinessStatus'
        })
    }


    /*************************************************
     * 做收尾工作
    */
    onBeforeUnmount(() => {
        clearTimeout(onPullDownRefreshTimer)
        clearTimeout(goLoginTime)
    })


    return {
        storeInfo,              // 用户信息
        businessHours,          // 营业时间段
        goLogin,                // 退出登录
        switchStore,            // 切换门店
        switchOpenTime,         // 门店休息到那天
        setTime,                // 去修改营业时间
        jumpBusinessStatus,     // 跳转到营业状态页面  
        store
    }
}


export default userInfo