import CollisionDetection from "./CollisionDetection";
import JiaZai from "./JiaZai";
import MapConroler from "./Map";
import Utils from "./module/Pay/Utils";
import { MiniGameManager } from "./Sdk/MiniGameManager";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Avatar extends cc.Component {

    // @property({
    //     tooltip: '碰撞形状，None就是无敌，不参与碰撞',
    //     type: cc.Enum(BlockType),
    //     // default: BlockType.Nomal,
    //     displayName: '碰撞形状'
    // })
    @property(cc.Node)
    content: cc.Node = null;

    @property(cc.Node)
    content2: cc.Node = null;

    @property(cc.Node)
    content3: cc.Node = null;

    @property(cc.SpriteAtlas)
    ui: cc.SpriteAtlas = null;

    avatar: any;  //正在使用中的头像
    address: string = "";
    avatarNow: any// 选中的头像
    avatarKuang: any;





    onLoad() {
    }
    start() {
    }
    init() {
        this.avatar = cc.fx.GameConfig.GM_INFO.useravatarIcon;
        this.avatarKuang = cc.fx.GameConfig.GM_INFO.useravaterkuang;
        this.address = cc.fx.GameConfig.GM_INFO.address;
        console.log("进入头像:", this.avatar, this.avatarKuang);
        this.changeBtnState("avatar");
        this.changeAvatar(null, this.avatar);
        this.changeState(null, "tou");
        this.getSelfAvatar();

        let Info = this.node.getChildByName("Info");
        //用户ID
        Info.getChildByName("Id").getComponent(cc.Label).string = cc.fx.GameConfig.GM_INFO.userId + "";
        //用户名称
        let username = cc.fx.GameConfig.GM_INFO.username;
        if (username.length > 12) username = cc.fx.GameTool.subName(username, 12);
        else if (username == "user") username = "匿名玩家";
        Info.getChildByName("Name").getComponent(cc.Label).string = username;
        //用户城市
        let city = cc.fx.GameConfig.GM_INFO.address;
        if (city == "北京" || city == "上海" || city == "重庆" || city == "天津") {
            city = city + "市";
        }
        Info.getChildByName("Address").getComponent(cc.Label).string = city + "";
        //用户注册时间
        let time = cc.fx.GameConfig.GM_INFO.firstTime;
        let formattedDate = "";
        if (time != 0) {
            let date = new Date(time);
            console.log("原始时间:", time, date);
            // 格式化年月日
            let year = date.getFullYear();
            let month = date.getMonth() + 1; // 月份从0开始，需要+1
            let day = date.getDate();

            formattedDate = `${year}年${month}月${day}日`;
        }

        Info.getChildByName("FirstTime").getComponent(cc.Label).string = formattedDate;
        for (let i = 0; i < this.content.children.length; i++) {
            this.content.children[i].getChildByName("kuang").getComponent(cc.Sprite).spriteFrame = this.ui.getSpriteFrame(this.avatarKuang);
        }

    }

    getSelfAvatar() {
        // this.content2.getChildByName(this.avatarKuang).getChildByName("select").active = true;
        console.log("获取进入头像:", this.avatar);
        if (this.avatar.length > 10) {
            this.node.getChildByName("self").getChildByName("icon").getChildByName("sp").active = false;
            this.node.getChildByName("self").getChildByName("icon").getChildByName("texture").active = true;
            this.setSelfAvatar(true);
        }
        else {
            console.log("没有头像", this.avatar);
            this.node.getChildByName("self").getChildByName("icon").getChildByName("sp").active = true;
            this.node.getChildByName("self").getChildByName("icon").getChildByName("texture").active = false;
            let actionName = cc.fx.GameTool.getActionName(this.avatar);
            this.node.getChildByName("self").getChildByName("icon").getChildByName("sp").scale = 0.85;
            cc.fx.GameTool.loadSpineSimple(this.node.getChildByName("self").getChildByName("icon").getChildByName("sp"), actionName);
            // this.node.getChildByName("self").getChildByName("icon").getChildByName("texture").getComponent(cc.Sprite).spriteFrame =
            //     this.ui.getSpriteFrame(this.avatar);
        }

        this.node.getChildByName("self").getChildByName("kuang").getComponent(cc.Sprite).spriteFrame =
            this.ui.getSpriteFrame(this.avatarKuang);
        // this.node.getChildByName("self").getChildByName("kuang").getComponent(cc.Sprite).spriteFrame =
        //     this.ui.getSpriteFrame(this.avatarKuang);
        cc.fx.GameTool.getUserAvatar((data) => {
            console.log("有头像__________", cc.fx.GameConfig.GM_INFO.useravatar)
            this.setSelfAvatar(true);
            if (data == true) {
                this.avatar = cc.fx.GameConfig.GM_INFO.useravatar;
                this.changeAvatar(null, this.avatar);
                this.clickBtn();
            }

        })
    }

    closeAvatar() {
        const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
        const jiazaiComp = jiazaiNode.getComponent(JiaZai);
        if (jiazaiComp) {
            console.log("获取到JiaZai组件", jiazaiComp);
            jiazaiComp.closeAvatar();

        } else {
            console.log("无法获取JiaZai组件");
        }
    }

    // 切换状态 头像和头像框
    changeState(event, state) {
        if (state == 'tou') {
            if (this.node.getChildByName("tou").opacity == 0) {
                return;
            }
            else {
                this.node.getChildByName("tou").opacity = 0;
                this.node.getChildByName("kuang").opacity = 255;
                this.node.getChildByName("avatar").active = true;
                this.node.getChildByName("avatarKuang").active = false;
                this.changeBtnState("avatar");
            }
        }
        else if (state == 'kuang') {
            this.closeSelectKuang();
            this.avatarKuang == cc.fx.GameConfig.GM_INFO.useravaterkuang;
            console.log("我的框状态:_________", this.avatarKuang);
            this.changeKuang(null, this.avatarKuang);
            if (this.node.getChildByName("kuang").opacity == 0) {
                this.changeBtnState("kuang");
                return;
            }
            else {
                this.node.getChildByName("tou").opacity = 255;
                this.node.getChildByName("kuang").opacity = 0;
                this.node.getChildByName("avatar").active = false;
                this.node.getChildByName("avatarKuang").active = true;
                this.changeBtnState("kuang");
            }
        }
    }

    // 判断按钮状态，切换按钮状态
    changeBtnState(state) {
        if (state == 'avatar') {
            if (this.avatar == cc.fx.GameConfig.GM_INFO.useravatarIcon) {
                this.node.getChildByName("btn").active = false;
                this.node.getChildByName("btnUse").active = true;
            }
            else {
                this.node.getChildByName("btn").active = true;
                this.node.getChildByName("btnUse").active = false;
            }
        }
        else if (state == 'kuang') {
            if (this.avatarKuang == cc.fx.GameConfig.GM_INFO.useravaterkuang) {
                this.node.getChildByName("btn").active = false;
                this.node.getChildByName("btnUse").active = true;
            }
            else {
                this.node.getChildByName("btn").active = true;
                this.node.getChildByName("btnUse").active = false;
            }
        }
    }

    //改变头像
    changeAvatar(event, avatar) {
        this.closeSelectAvatar();
        this.avatar = avatar;
        switch (avatar) {
            case "icon":
                if (cc.fx.GameConfig.GM_INFO.useravatar.length > 10) {
                    this.avatar = cc.fx.GameConfig.GM_INFO.useravatar;
                }
                this.content.children[0].getChildByName("select").active = true;
                break;
            case "icon_0":
                this.content.children[1].getChildByName("select").active = true;
                break;
            case "icon_1":
                this.content.children[2].getChildByName("select").active = true;
                break;
            case "icon_2":
                this.content.children[3].getChildByName("select").active = true;
                break;
            case "icon_3":
                this.content.children[4].getChildByName("select").active = true;
                break
            case "icon_4":
                this.content.children[4].getChildByName("select").active = true;
                break;
            case "icon_5":
                this.content.children[5].getChildByName("select").active = true;
                break;
            case "icon_6":
                this.content.children[6].getChildByName("select").active = true;
                break;
            case "icon_7":
                this.content.children[7].getChildByName("select").active = true;
                break;
            case "icon_8":
                this.content.children[8].getChildByName("select").active = true;
                break;
            case "icon_9":
                this.content.children[9].getChildByName("select").active = true;
                break;
            case "icon_10":
                this.content.children[9].getChildByName("select").active = true;
                break;
            case "icon_11":
                this.content.children[10].getChildByName("select").active = true;
                break;
            case "icon_12":
                this.content.children[11].getChildByName("select").active = true;
                break;
            case "icon_13":
                this.content.children[12].getChildByName("select").active = true;
                break;
            case "icon_14":
                this.content.children[11].getChildByName("select").active = true;
                break;
            case "icon_15":
                this.content.children[13].getChildByName("select").active = true;
                break;
            case "icon_16":
                this.content.children[14].getChildByName("select").active = true;
                break;
            default:
                if (this.avatar.length > 10) {
                    this.content.children[0].getChildByName("select").active = true;
                }

                break;
        }
        this.changeBtnState("avatar");
    }

    setSelfAvatar(data) {
        let url = cc.fx.GameConfig.GM_INFO.useravatar;
        if (url == "") {
            return;
        }
        var self = this;
        cc.assetManager.loadRemote(cc.fx.GameConfig.GM_INFO.useravatar, { ext: '.png' }, (err, texture: cc.Texture2D) => {
            if (texture) {
                if (data == true || cc.fx.GameConfig.GM_INFO.useravatar.length > 10) {
                    if (this.avatar == cc.fx.GameConfig.GM_INFO.useravatar) {
                        var sprite = self.node.getChildByName("self").getChildByName("icon").getChildByName("texture").getComponent(cc.Sprite);
                        sprite.spriteFrame = new cc.SpriteFrame(texture);
                    }
                    var sprite2 = self.content.children[0].getChildByName("icon").getChildByName("texture").getComponent(cc.Sprite);
                    sprite2.spriteFrame = new cc.SpriteFrame(texture);
                }
                // var sprite2 = self.content.children[0].getChildByName("icon").getComponent(cc.Sprite);
                // sprite2.spriteFrame = new cc.SpriteFrame(texture);
            }
        })
    }

    //使用 按钮
    clickBtn() {
        if (this.node.getChildByName("avatar").active == true) {
            cc.fx.GameConfig.GM_INFO.useravatarIcon = this.avatar;
            if (cc.fx.GameConfig.GM_INFO.useravatarIcon.length > 10) {
                cc.fx.GameConfig.GM_INFO.useravatarIcon = cc.fx.GameConfig.GM_INFO.useravatar;
                this.node.getChildByName("self").getChildByName("icon").getChildByName("sp").active = false;
                this.node.getChildByName("self").getChildByName("icon").getChildByName("texture").active = true;
                this.setSelfAvatar(true);
            }
            else {
                this.node.getChildByName("self").getChildByName("icon").getChildByName("sp").active = true;
                this.node.getChildByName("self").getChildByName("icon").getChildByName("texture").active = false;
                let actionName = cc.fx.GameTool.getActionName(this.avatar);
                this.node.getChildByName("self").getChildByName("icon").getChildByName("sp").scale = 0.85;
                cc.fx.GameTool.loadSpineSimple(this.node.getChildByName("self").getChildByName("icon").getChildByName("sp"), actionName);
                // this.node.getChildByName("self").getChildByName("icon").getChildByName("texture").getComponent(cc.Sprite).spriteFrame =
                //     this.ui.getSpriteFrame(this.avatar);
            }
        }
        else {
            console.log("________________保存头像框");
            cc.fx.GameConfig.GM_INFO.useravaterkuang = this.avatarKuang;
            this.node.getChildByName("self").getChildByName("kuang").getComponent(cc.Sprite).spriteFrame =
                this.ui.getSpriteFrame(this.avatarKuang);
        }
        for (let i = 0; i < this.content.children.length; i++) {
            this.content.children[i].getChildByName("kuang").getComponent(cc.Sprite).spriteFrame = this.ui.getSpriteFrame(this.avatarKuang);
        }
        this.node.getChildByName("btn").active = false;
        this.node.getChildByName("btnUse").active = true;
    }

    //改变头像框
    changeKuang(event, kuang) {
        this.closeSelectKuang();
        this.avatarKuang = kuang;
        console.log("谁应该为true", kuang);
        this.content3.getChildByName(kuang).getChildByName("select").active = true;
        this.changeBtnState("kuang");
    }

    closeSelectAvatar() {
        for (let i = 0; i < this.content.children.length; i++) {
            this.content.children[i].getChildByName("select").active = false;
        }
    }

    closeSelectKuang() {
        for (let i = 0; i < this.content3.children.length; i++) {
            this.content3.children[i].getChildByName("select").active = false;
        }
    }

    switchAddress(event, address) {
        if (cc.fx.GameConfig.GM_INFO.address != address) {
            cc.fx.GameConfig.GM_INFO.address = address;
        }

        let node = this.content2.getChildByName(address);
        if (node) {
            this.content2.getChildByName("choice").active = true;
            this.content2.getChildByName("choice").x = node.x;
            this.content2.getChildByName("choice").y = node.y;
            let name = address;
            if (name != "北京" && name != "天津" && name != "上海" && name != "重庆" && name != "广西" && name != "新疆" && name != "西藏" && name != "宁夏" && name != "港澳台" && name != "内蒙古") {
                name = name.substring(0, name.length - 1);
            }
            this.content2.getChildByName("choice").getChildByName("cityName").getComponent(cc.Label).string = name;
        }
    }

    openAddress() {
        let change = cc.fx.StorageMessage.getStorage("changeAddress");
        //没缓存过，没授权过
        if (change == "" || change == null || change == undefined) {
        }
        else {
            let time = change.time;
            let changeCount = change.changeCount;
            if (changeCount >= 2) {
                // 获取当前时间戳
                let nowTime = Math.floor(Date.now() / 1000);

                // 将时间戳转换为日期对象
                let currentDate = new Date(nowTime * 1000);
                let storedDate = new Date(time * 1000);

                // 比较年月日是否相同
                let currentYear = currentDate.getFullYear();
                let currentMonth = currentDate.getMonth();
                let currentDay = currentDate.getDate();

                let storedYear = storedDate.getFullYear();
                let storedMonth = storedDate.getMonth();
                let storedDay = storedDate.getDate();

                // 如果年月日没变，则return
                if (currentYear === storedYear && currentMonth === storedMonth && currentDay === storedDay) {
                    MiniGameSdk.API.showToast("每日可变更地址两次，今日变更次数已用完");
                    return;
                }
                else {
                    changeCount = 0;
                    let changeInfo = {
                        time: nowTime,
                        changeCount: changeCount
                    }
                    cc.fx.StorageMessage.setStorage("changeAddress", changeInfo);
                }
                // 否则不处理，继续执行后续代码
            }
        }

        this.node.getChildByName("address").active = true;
        this.content2.getChildByName("choice").active = false;
        this.address = cc.fx.GameConfig.GM_INFO.address;
        if (cc.fx.GameConfig.GM_INFO.address != "" && cc.fx.GameConfig.GM_INFO.address != null) {
            let node = this.content2.getChildByName(this.address);
            if (node) {
                this.content2.getChildByName("choice").active = true;
                this.content2.getChildByName("choice").x = node.x;
                this.content2.getChildByName("choice").y = node.y;
                this.content2.getChildByName("choice").getChildByName("cityName").getComponent(cc.Label).string = this.address;
            }
        }

    }

    closeAddress() {
        if (this.address != cc.fx.GameConfig.GM_INFO.address) {
            this.address = cc.fx.GameConfig.GM_INFO.address;
            let Info = this.node.getChildByName("Info");
            //用户城市
            let city = cc.fx.GameConfig.GM_INFO.address;
            if (city == "北京" || city == "上海" || city == "重庆" || city == "天津") {
                city = city + "市";
            }
            Info.getChildByName("Address").getComponent(cc.Label).string = city + "";

            let nowTime = Math.floor(Date.now() / 1000);
            let addressInfo = {
                address: cc.fx.GameConfig.GM_INFO.address,
                time: nowTime,
                authorize: false
            }
            cc.fx.StorageMessage.setStorage("address", addressInfo);
            Utils.setCityInfo(null, cc.fx.GameConfig.GM_INFO.address, true);
            let locationInfo = {
                type: "manual",
                result: cc.fx.GameConfig.GM_INFO.address,
                is_success: true,
                info: ""
            }
            cc.fx.GameTool.shushu_Track("location", locationInfo);


            let changeCount = 0;
            let change = cc.fx.StorageMessage.getStorage("changeAddress");
            //没缓存过，没授权过
            if (change == "" || change == null || change == undefined) {
                // changeCount = 1;
                changeCount += 1;
            }
            else {
                changeCount = change.changeCount + 1;
            }

            let changeInfo = {
                time: nowTime,
                changeCount: changeCount
            }
            cc.fx.StorageMessage.setStorage("changeAddress", changeInfo);
        }


        this.node.getChildByName("address").active = false;

        const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
        const jiazaiComp = jiazaiNode.getComponent(JiaZai);
        if (jiazaiComp) {
            console.log("获取到JiaZai组件", jiazaiComp);
            jiazaiComp.getSRank();

        } else {
            console.log("无法获取JiaZai组件");
        }
    }
}


