import Gamecfg from "../../common/gameCfg";
import { gameMethod } from "../../common/gameMethod";
import { TaobaoAddAction, TaobaoAddActionPram, UserWechatSq, UserWechatSqPram } from "../../common/Xyc";
import Config from "../../Config";
import UIHelp from "../../logic/ui/UIHelp";
import PlatformBase from "../../plat/PlatformBase";
import PlatformDianHunWeChat from "../../plat/PlatformDianHunWeChat";
import PlatformFenYouH5 from "../../plat/PlatformFenYouH5";
import PlatformHaiTuoH5 from "../../plat/PlatformHaiTuoH5";
import PlatformHaiTuoMini from "../../plat/PlatformHaiTuoMini";
import PlatformLocal from "../../plat/PlatformLocal";
import PlatformQuickH5 from "../../plat/PlatformQuickH5";
import PlatformTaoBao from "../../plat/PlatformTaoBao";
import PlatformWan17 from "../../plat/PlatformWan17";
import PlatformWan17H5 from "../../plat/PlatformWan17H5";
import PlatformWan17MiniGame from "../../plat/PlatformWan17MiniGame";
import PlatformXXGame from "../../plat/PlatformXXGame";
import PlatformZhilingH5 from "../../plat/PlatformZhilingH5";
import { I18n } from "../../utils/I18nUtil";
import WechatUserBtn from "../../utils/WechatUserBtn";
import { GameErrCode, InGame, PlatformType, PlatUserInfo } from "../const/TypeConst";
import GameDataCenter from "../GameDataCenter";
import IDataModel from "../../frameWork/model/IDataModel";
export default class PlatformModel extends IDataModel {
    instance: PlatformBase
    type: PlatformType

    queryparams: {
        inviter: string  // 邀请者uuid
        sharer: string // 分享者uuid
        scene: number   // 微信场景值
    } = { inviter: "", sharer: "", scene: 1000 }
    hasGetWechatUserInfo: boolean = false;
    constructor() {
        super('platform');
        console.log("=====pid=====", Config.pid)
        let packageCfg = Gamecfg.packageInfo.getItem(Config.pid)
        this.type = <PlatformType>packageCfg.plat
        switch (packageCfg.plat) {
            case PlatformType.zhiling:
                this.instance = new PlatformZhilingH5()
                break;
            case PlatformType.fenyou:
                this.instance = new PlatformFenYouH5()
                break;
            case PlatformType.haituoH5:
                this.instance = new PlatformHaiTuoH5()
                break;
            case PlatformType.haituoMini:
                this.instance = new PlatformHaiTuoMini()
                break;
            case PlatformType.DHWeChat:
                this.instance = new PlatformDianHunWeChat()
                break;
            case PlatformType.bth5:
                this.instance = new PlatformQuickH5()
                break;
            case PlatformType.wan17H5:
                this.instance = new PlatformWan17H5()
                break;
            case PlatformType.taobao:
                this.instance = new PlatformTaoBao()
                break;
            case PlatformType.wan17:
                this.instance = new PlatformWan17()
                break;
            case PlatformType.wan17MiniGame:
                this.instance = new PlatformWan17MiniGame()
                break;
            case PlatformType.XXGame:
                this.instance = new PlatformXXGame()
                break;
            default:
                this.instance = new PlatformLocal()
                break;
        }
    }

    //微信获取个人信息
    checkUserInfo(type: string, node: fgui.GObject, cb: Function) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME) {
            return
        }
        if (this.instance.hasAuthUserInfo) {
            console.log("已授权")
            // 已授权,如果是初次,获取一次用户信息
            //		 如果不是首次,则不做任何事情
            if (!this.hasGetWechatUserInfo) {
                console.log("获取用户信息111")
                this.hasGetWechatUserInfo = true
                // setTimeout(()=>{
                this.getWechatUserInfo()
                // }, 100)

            }
        } else {
            // 未授权,弹出按钮
            console.log("未授权,弹出按钮")
            // setTimeout(()=>{
            this.createUserInfoBtn(type, node, cb)
            // }, 100)

        }
    }
    userInfoBtnList: any = {}
    hasClickUserInfoBtn: boolean = false // 是否点击过了
    // 创建授权个人信息按钮
    createUserInfoBtn(type: string, node: fgui.GObject, cb: Function) {
        if (this.hasClickUserInfoBtn) {
            return
        }
        // if (this.userInfoBtn) {
        //     this.userInfoBtn.show()
        //     return
        // }
        // let param = uiCommon.getWxBtnPos(this.ui.btnUser) //  this.getWxBtnParam(this.ui.btnUser)
        let userInfoBtn = WechatUserBtn.create(node, () => {
            this.hasClickUserInfoBtn = true
            this.removeAllUserBtn()
            cb && cb()
        })
        this.userInfoBtnList[type] = userInfoBtn
    }

    removeAllUserBtn() {
        for (const key in this.userInfoBtnList) {
            if (Object.prototype.hasOwnProperty.call(this.userInfoBtnList, key)) {
                this.userInfoBtnList[key].hide();
            }
        }
    }

    removeUserBtn(type: string) {
        this.userInfoBtnList[type]?.hide()
    }

    // 从微信平台获取个人信息
    getWechatUserInfo() {
        if (cc.sys.platform != cc.sys.WECHAT_GAME) { return }
        // 用户已授权
        GameDataCenter.plat.instance.hasAuthUserInfo = true
        wx.getUserInfo({
            lang: "zh_CN",
            success: function (res) {
                GameDataCenter.plat.instance.reportUserInfo(res)
                if (Config.inGame >= InGame.home) {
                    // 在游戏内部时才触发储存
                    GameDataCenter.plat.sendWxSq({
                        nickName: res.userInfo.nickName,
                        avatarUrl: res.userInfo.avatarUrl
                    })
                    // huosdk 需要上传用户信息
                    console.log("接收到了信息:", res.userInfo.nickName, res.userInfo.avatarUrl)
                }
            },
            fail: function () { }
        })
    }
    // 微信授权后保存名字和头像到后端
    sendWxSq(platUserInfo: PlatUserInfo) { // @TODO 抖音平台也用这个?
        if (cc.sys.platform != cc.sys.WECHAT_GAME) { return }
        let param: UserWechatSqPram = { nickname: platUserInfo.nickName, headimgurl: platUserInfo.avatarUrl }
        console.log("通知储存用户数据")
        this.send(UserWechatSq.url, param)
        //保存微信头像地址
        // let paramWxHead: UserSetWxheadPram = { str: platUserInfo.avatarUrl }
        // this.send(UserSetWxhead.url, paramWxHead)
    }

    showErrDialog(errCode: GameErrCode) {
        UIHelp.ShowDialog({
            content: I18n.getI18nText("PlatformModel_showtips_1", errCode),
            onlyConfirm: true,
            cbConfirm: () => {
                GameDataCenter.plat.instance.restart()
            }
        })
    }

    sendTBActionId() {
        let param: TaobaoAddActionPram = {
        }
        this.send(TaobaoAddAction.url, param, () => {

        })
    }

    shareAppMessage(params: { [key: string]: string }): void {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            // let param: UserGetFxPram = {}
            // GameController.network.send(UserGetFx.url, param, (result: SevBack) => {
            //     if (result.type == 1 && result.fenxiang) {
            //         let qurey = ""
            //         for (const key in params) {
            //             if (qurey.length > 0) {
            //                 qurey += "&"
            //             }
            //             qurey += key + "=" + params[key]
            //         }

            //         let userSDKVersion = wx.getAppBaseInfo().SDKVersion
            //         console.log("---分享参数:", result.fenxiang.newtupian)
            //         if (GameDataCenter.plat.compareWxVersion(userSDKVersion, "2.4.3") < 0 || gameMethod.isEmpty(result.fenxiang.newtupian)) {
            //             console.log("版本低了", userSDKVersion, "2.4.3")
            //             wx.shareAppMessage({
            //                 title: result.fenxiang.wenan, // 标题会导致场景值变为1044
            //                 imageUrl: result.fenxiang.tupian, // 比例为5:4
            //                 query: qurey
            //             })
            //         } else {
            //             console.log("版本高,可高级分享", userSDKVersion, "2.4.3")
            //             wx.shareAppMessage({
            //                 title: result.fenxiang.wenan, // 标题会导致场景值变为1044
            //                 imageUrlId: result.fenxiang.newtupian[0],
            //                 imageUrl: result.fenxiang.newtupian[1],
            //                 query: qurey
            //             })
            //         }
            //         console.log("分享上报")
            //         if (!gameMethod.isEmpty(window["huoSdk"])) {
            //             window["huoSdk"].addShareInfo({
            //                 data: {
            //                     to_target: 'wx'
            //                 }
            //             }).then(res => {
            //                 console.log("分享结果:", res)
            //             })
            //         }
            //         GameDataCenter.plat.instance.resportShareEvent()
            //     }
            // })
        }
    }
    // wx版本对比专用 [玩家系统版本,指定版本] 1:玩家版本高 -1玩家版本低 0一样
    compareWxVersion(v1, v2): number {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    }
    //是否能调用微信的重启
    canRestartApp(): boolean {
        let sysInfo = wx.getSystemInfoSync();
        let SDKVersion = sysInfo.SDKVersion;
        return this.compareWxVersion(SDKVersion, "2.22.1") >= 0;
    }
}

