import { defineStore } from 'pinia'
import { current, getSiteInfo,getMemberMobileExist } from '@/app/api/system'
import useConfigStore from '@/stores/config'
import useMemberStore from '@/stores/member'
import { isWeixinBrowser } from '@/utils/common'
import { cloneDeep } from 'lodash-es';

interface System {
    site: AnyObject | null,
    siteApps: string[],
    siteAddons: string[],
    currRoute: string,
    mapConfig: any,
    initStatus: any, // 初始化状态
    menuButtonInfo: any, // 如果是小程序，获取右上角胶囊的尺寸信息
    shareCallback: any, // 分享回调
    defaultPositionAddress: any,
    diyAddressInfo: any,  // 定位信息
    currTabbar: {
        path: string,
        query: object
    },
    systemInfo: any, // 系统设备信息
    topTabbarInfo: {
        height: number
        fullHeight: string
    }
}

const useSystemStore = defineStore('system', {
    state: (): System => {
        return {
            site: null,
            siteApps: [],
            siteAddons: [],
            currRoute: '',
            mapConfig: {
                is_open: 1,
                valid_time: 0
            },
            initStatus: 'wait',
            menuButtonInfo: {
                height: 0,
                top: 0,
                right: 0,
                width: 0
            },
            shareCallback: null,
            defaultPositionAddress: '定位中',
            diyAddressInfo: null,
            currTabbar: {
                path: '',
                query: {}
            },
            systemInfo: null,
            topTabbarInfo: {
                height: 0,
                fullHeight: ''
            }
        }
    },
    actions: {
        // 获取初始化数据信息
        getInitFn(callback: any) {

            let url = '';
            // #ifdef H5
            if (isWeixinBrowser()) {
                url = this.systemInfo.platform == 'ios' ? uni.getStorageSync('initUrl') : location.href
            }
            // #endif

            current({}).then((res: any) => {
                if (res.data) {
                    let data = res.data;

                    // 底部导航
                    const configStore = useConfigStore()
                    configStore.tabbarList = data;
						
                    this.initStatus = 'finish'; // 初始化完成
                    if (callback) callback()
                }
            })

            this.getMenuButtonInfoFn();
        },
		// 如果已有手机号，就不弹出绑定手机号弹框
		getMemberMobileExistFn (){
			getMemberMobileExist({
				openid: uni.getStorageSync('openid')
			}).then((res:any)=>{
				uni.setStorageSync('member_mobile_exist', res.data.member_mobile_exist)
			})
		},
        getMenuButtonInfoFn() {
            // 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
            // #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
            this.menuButtonInfo = uni.getMenuButtonBoundingClientRect();
            // #endif
        },
        async getSiteInfoFn() {
            await getSiteInfo().then((res: any) => {
                this.site = res.data
                const apps: any = [], addons: any = []
                Object.keys(res.data.site_addons).forEach((key: string) => {
                    const item = res.data.site_addons[key]
                    item.type == 'app' ? apps.push(key) : addons.push(key)
                })
                this.siteApps = apps
                this.siteAddons = addons
            }).catch((err) => {
            })
        },
        // 当前选择的收货地址信息[经纬度，当前定位地址，定位过期时间]
        setAddressInfo(data: any = {}) {
            let addressInfo = cloneDeep(data);
            // 过期时间
            const date = new Date();
            date.setSeconds(60 * this.mapConfig.valid_time);
            addressInfo.valid_time = date.getTime() / 1000; // 定位信息 5分钟内有效，过期后将重新获取定位信息

            if (this.diyAddressInfo) {
                this.diyAddressInfo = Object.assign(this.diyAddressInfo, addressInfo);
            } else {
                this.diyAddressInfo = addressInfo;
            }

            if (Object.keys(data).length) {
                uni.setStorageSync('location_address', addressInfo);
            } else {
                uni.removeStorageSync('location_address');
            }
        },
        setTopTabbar(data: any = {}) {
            this.topTabbarInfo = Object.assign({}, this.topTabbarInfo, data);
            this.topTabbarInfo.height = this.topTabbarInfo.height || 0
            this.topTabbarInfo.fullHeight = this.topTabbarInfo.height ? this.topTabbarInfo.height+'px' : 0
        }
    }
})

export default useSystemStore
