import { defineStore } from "pinia";
import { useStores } from "@/store/modules/index";
import { storage, storageSystem } from "@/utils/storage";
import { getToken, setToken, removeToken } from "@/utils/auth";
// 接口引用
import { uploadAvatar, updateUserProfile } from "@/api/system/user";
import { baseAppInfoApi } from "@/api/common/index";
import { checkUpdates } from "@/api/system/setting";
// 组件引用
import config from "@/config";
import tab from "@/plugins/tab.plugins.js";
import modal from "@/plugins/modal.plugins.js";
import common from "@/plugins/common.plugins.js";
import setting from "@/plugins/setting.plugins.js";
import constData from "@/plugins/constData.plugins.js";

const settingStores = defineStore("storage-setting", {
    state: () => ({
        pushClientId: undefined,//应用消息推送cid
        currentSize: "",//APP缓存
        barHeight: 0,//微信小程序顶部安全距离
        webViewHeight: "",//webView整体高度-铺满
        StatusBarHeight: "",//APP顶部安全距离
        tabBarHeight: "",//APP底部安全距离
        deviceList: {
            networkType: null, //网络类型
            deviceBrand: null, //设备品牌
            deviceId: null, //设备编号
            deviceModel: null, //设备型号
            userName: null, //用户账号
            longitude: "", //经度
            latitude: "", //纬度
            deviceStatus: 0,//设备状态
        },

        themeColor: storageSystem.get("themeColor"),//主题
        fingerprintUserList: storageSystem.get("fingerprintUserList"),//指纹登录用户数据
        nfcWaiting: "请将手机靠近NFC标签", //nfc读取页面-提示文字-数据存储
        webSocket: null,//巡检webSocket
    }),
    actions: {
        /**
         * @动态获取屏幕头部高度
         */
        systemHeightTop() {
            let systemInfo = uni.getSystemInfoSync();
            this.webViewHeight = systemInfo.safeArea.bottom  //高度+安全区域的高度
            this.StatusBarHeight = systemInfo.statusBarHeight + "px"
            this.tabBarHeight = common.isWechatMp() ? "0px" : systemInfo.screenHeight - systemInfo.safeArea.bottom + "px"

            //#ifdef MP
            let custom = wx.getMenuButtonBoundingClientRect();
            let CustomBar = custom.bottom + custom.top - systemInfo.statusBarHeight;
            this.barHeight = CustomBar || 0
            //#endif
        },
        /**
         * @动态获取用户设备信息
         */
        baseAppInfo() {
            var _this = this

            //判断用户是否登录
            if (!getToken()) {
                return false
            }
            //判断用户拒绝权限是否超过48小时
            if (!common.isExpirationTime()) {
                return false
            }

            // 获取系统信息
            const systemInfo = uni.getSystemInfoSync();
            _this.deviceList.deviceBrand = systemInfo.deviceBrand;
            _this.deviceList.deviceId = systemInfo.deviceId;
            _this.deviceList.deviceModel = systemInfo.deviceModel;
            _this.deviceList.operateSystem = systemInfo.platform;

            // 获取网络状态
            uni.getNetworkType({
                success: function (res) {
                    _this.deviceList.networkType = res.networkType;
                },
            });

            // 获取定位信息
            uni.getLocation({
                type: "gcj02",
                geocode: true,
                highAccuracyExpireTime: 5000,
                success: (res) => {
                    _this.deviceList.longitude = res.longitude.toString();
                    _this.deviceList.latitude = res.latitude.toString();
                    baseAppInfoApi(_this.deviceList).then((res) => { })
                    uni.setStorageSync("expirationTime", "");
                },
                fail: (res) => {
                    if (res.errMsg.indexOf('获取定位权限失败') != -1) {
                        uni.setStorageSync("expirationTime", Date.parse(new Date()) / 1000);
                    }
                },
            });
        },
        /**
         * @消息推送监听
         */
        pushMessage() {
            uni.onPushMessage((res) => {
                const platform = uni.getSystemInfoSync().platform;
                console.log("收到推送消息：", res); //监听推送消息

                if (res.type === "click") {
                    if (platform == "android") {
                    } else {
                    }
                } else if (res.type === "receive") {
                    if (platform == "android") {
                    } else {
                    }
                }
            });
        },
        /**
         * @消息推送监听
         */
        pushListener() {
            //获取应用的CID
            uni.getPushClientId({
                success: (res) => {
                    this.pushClientId = res.cid
                },
                fail(err) {
                    console.log(err);
                },
            });
            const platform = uni.getSystemInfoSync().platform;
            // 接收推送信息  在线
            plus.push.addEventListener("receive", (res) => {
                console.log(res)
                uni.createPushMessage({
                    title: res.title,
                    content: res.content,
                    payload: res.payload
                });
            });
            // 点击推送信息
            plus.push.addEventListener("click", (res) => {
                console.log(res);
                if ("payload" in res) {
                    if ("infoType" in res.payload) {
                        if (res.payload.infoType == 5) {
                            tab.navigateTo(`/pages/business/common/projectMange/record/details?reportId=${res.payload.moduleId}`);
                        }
                    }
                }
            });
        },
        /**
         * @初始化WebSocket
         */
        initWebSocket() {
            var _this = this

            const systemInfo = uni.getSystemInfoSync();
            _this.webSocket = uni.connectSocket({
                // url: `wss://gateway.usky.cn/wss${systemInfo.deviceId},${new Date().getTime()}`,
                url: `ws://120.26.164.249:9891/webSocketPatrol/${systemInfo.deviceId},${new Date().getTime()}`,
            });
        },
        /**
         * @开启WebSocket
         */
        openWebSocket() {
            var _this = this

            if (uni.getStorageSync("serveUrl").indexOf("xf.usky.cn:13212") == -1) {
                return false
            }

            _this.initWebSocket()

            uni.onSocketOpen(function (res) {
                console.log('WebSocket连接已打开！', res);
            });

            uni.onSocketMessage(function (res) {
                console.log('收到服务器内容：' + res.data);
                _this.baseAppInfo();
            });

            uni.onSocketClose(function (res) {
                console.log('WebSocket 已关闭！', res);
                _this.closeWebSocket();
                _this.initWebSocket()
            });

            uni.onSocketError(function (res) {
                console.log('WebSocket连接打开失败，请检查！');
                _this.initWebSocket()
            });
        },
        /**
         * @关闭WebSocket
         */
        closeWebSocket() {
            uni.closeSocket();
        },
        /**
         * @点击登录
         */
        handleToLogin() {
            tab.reLaunch("/pages/login");
        },

        /**
         * @点击头像
         */
        handleToAvatar(type) {
            var _this = this

            if (type == 1) {
                uni.chooseImage({
                    count: 1, //默认9
                    sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
                    sourceType: ["album", "camera"], //从相册选择、摄像头
                    success: function (res) {
                        _this.uploadApi(res);
                    },
                });
            } else if (type == 2) {
                tab.navigateTo("/pages/mine/avatar/index");
            }
        },

        /**
         * @upload上传头像
         * @api接口请求
         */
        uploadApi(res) {
            const useStore = useStores();
            let data = { name: "file", filePath: res.tempFilePaths[0] };
            uploadAvatar(data).then((response) => {
                useStore.avatar = response.data.url;
                updateUserProfile({
                    avatar: response.data.url,
                }).then(() => { });
            });
        },

        /**
         * @常见问题
         */
        handleHelp() {
            tab.navigateTo("/pages/mine/help/index");
        },

        /**
         * @我的信息
         */
        handleToEditInfo() {
            tab.navigateTo("/pages/mine/info/index");
        },

        /**
         * @关于我们
         */
        handleAbout() {
            tab.navigateTo("/pages/mine/about/index");
        },

        /**
         * @清理缓存
         */
        handleCleanTmp() {
            // #ifdef H5
            uni.showToast({
                title: "缓存清理完成",
                duration: 2000,
                mask: true,
            });
            // #endif

            // #ifdef APP-PLUS
            setting.clearCache();//清除应用访问缓存
            // #endif
        },

        /**
         * @检查更新
         */
        handleToUpgrade({ success, error }) {
            let platform = uni.getSystemInfoSync().platform; //手机平台
            let data = {
                _api_key: "fba7440cd37400b6ff46e303896af4df",
                appKey: "",
                buildVersion: config.appInfo.version,
            };

            // 综合智慧云
            if (config.appInfo.appid === "__UNI__36DE3A0") {
                data.appKey = platform === "android" ? "cbd3508235d03365f4253f6aae6b68ab" : "4b858fce6367652f5c0959a0444a4bea"
            }
            // 智能巡更
            else if (config.appInfo.appid === "__UNI__BF1A1F0") {
                data.appKey = platform === "android" ? "d67e04ab2f4b8a1fa01a773692fc666c" : "d67e04ab2f4b8a1fa01a773692fc666c"
            }
            // 智能会议
            else if (config.appInfo.appid === "__UNI__F3963F8") {
            }

            modal.loading("加载中");
            checkUpdates(data).then((res) => {
                if (res.code == 0) {
                    if (res.data.buildHaveNewVersion == true) {
                        //安卓手机弹窗升级
                        if (platform === "android") {
                            success(res)
                        }
                        //IOS无法在线升级提示到商店下载
                        else {
                            let appleId = 6449016600
                            plus.runtime.launchApplication({
                                action: `itms-apps://itunes.apple.com/cn/app/id${appleId}`,
                            })
                        }
                    } else {
                        modal.msg("您的软件版本已是最新");
                    }
                    modal.closeLoading();
                }
            });
        },

        /**
         * @新消息通知
         */
        handleToMessage() {
            tab.navigateTo("/pages/mine/msg/index");
        },

        /**
         * @账号与安全
         */
        handleToSecure() {
            tab.navigateTo("/pages/mine/secure/index");
        },

        /**
         * @设置
         */
        handleSetting() {
            tab.navigateTo("/pages/mine/setting/index");
        },

        /**
         * @退出登录
         */
        handleLogout() {
            const useStore = useStores();
            modal.confirm("确定注销并退出系统吗？").then(() => {
                useStore.LogOut().then(() => {
                    tab.reLaunch("/pages/index");
                });
            });
        },
        /**
         * @初始化默认主题
         */
        initThemeColor(themeColor) {
            if (!themeColor) {
                this.themeColor = constData.themeList[0];
                storageSystem.set("themeColor", constData.themeList[0]);
            } else {
                this.themeColor = themeColor;
                storageSystem.set("themeColor", themeColor);
            }
        },
        /**
         * @系统主题颜色
         */
        systemThemeColor(type) {
            setTimeout(() => {
                if (type.includes(2)) {
                    uni.setTabBarStyle({
                        selectedColor: this.themeColor.color,
                        borderStyle: "white",
                    });

                    this.themeColor.tabList.forEach((selectedIconPath, index) => {
                        uni.setTabBarItem({
                            index,
                            selectedIconPath,
                        });
                    });
                }

                if (type.includes(1)) {
                    uni.setNavigationBarColor({
                        frontColor: "#ffffff",
                        backgroundColor: this.themeColor.color,
                        animation: {
                            duration: 400,
                            timingFunc: "easeIn",
                        },
                    });
                }
            }, 0);
        },
        SET_FINGERPRINT(array) {
            this.fingerprintUserList = array;
            storageSystem.set("fingerprintUserList", array);
        },
        SET_STORAGE_OBJECT_KEYS(LIST) {
            Object.keys(LIST).forEach(function (key) {
                storageSystem.set(key, LIST[key]);
                settingStores()[key] = LIST[key];
            });
        },
    },
});

export default settingStores;
