// import { Action } from './../../../creator.d';
import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import shop from "./model/shop";
import pg from "./pg";
import Api from "./net/api";
import user from "./model/user";
import Item from "./model/item";
import HouseItem from "./model/houseItem";
import kitchen from "./model/kitchen";
import { ITEM_TYPE } from "./config/config";
import house from "./model/house";
import dress from "./model/dress";
import PengPeng from "./pengpeng";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
    @property(cc.SpriteFrame)
    icon_1: cc.SpriteFrame = null;
    @property(cc.SpriteFrame)
    icon_2: cc.SpriteFrame = null;
    @property(cc.SpriteFrame)
    icon_3: cc.SpriteFrame = null;
    @property(cc.SpriteFrame)
    icon_4: cc.SpriteFrame = null;
    @property(cc.SpriteFrame)
    icon_5: cc.SpriteFrame = null;
    @property(cc.SpriteFrame)
    icon_6: cc.SpriteFrame = null;
    @property(cc.SpriteFrame)
    icon_7: cc.SpriteFrame = null;
    @property(cc.SpriteFrame)
    icon_8: cc.SpriteFrame = null;


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

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

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

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

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

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

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

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


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

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

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

    @property(cc.AudioClip)
    starPop: cc.AudioClip = null;

    private pengpeng: PengPeng|null = null;





    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.audio_url });
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        const isLocalDev = !cc.find('middleLayer');
        // globalThis.USER_TOKEN =  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2Mzk2MjE3MTIsImV4cCI6MTY0MjIxMzcxMiwiaWQiOjQwMDY2LCJwYXNzd29yZCI6IjE5QTEwM0E3NUUzM0QzQTNCODg0QkQxNTUwMjhENTA1Iiwic2Nob29sX2lkIjoyODYsInBob25lIjoiMTMxMDAwMDAwMDAiLCJuYW1lIjoi5bCP546J5rWL6K-VMCIsInN0YXR1cyI6MCwidHlwZSI6MCwicm9sZXMiOjEsImV4cGlyZWQiOiIyMDIyLTAzLTE5VDE2OjAwOjAwLjAwMFoiLCJzY2hvb2xfbmFtZSI6Iue7mOeOqea1i-ivleeOr-Wig-WtpuagoSIsInNjaG9vbF90eXBlIjoyLCJjcmVhdGVvbiI6MTU3MDc2MTk3NDAwMCwiY2xhc3NfbmFtZSI6IuS4ieW5tDHnj60iLCJjbGFzc19pbmZvIjpbeyJjbGFzc19pZCI6MzkxNSwiY2xhc3NfbmFtZSI6IuS4ieW5tDHnj60ifV0sIm90aGVycyI6W119.4T-Lnsl25aJ-rvUOCDwShq4F5u3BbR86ZLPew4zyULU"
        // globalThis.CLIENT_TYPE = 'student'
        // globalThis.SERVER_HOST = 'http://192.168.3.127:3900'
        // globalThis.____GAME_ENV____ = {
        //     baseUrl: isLocalDev ? 'http://192.168.99.41:3900/api/' : cc.find('middleLayer').getComponent('middleLayer').baseUrl,
        //     token: isLocalDev 
        //             ? "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2NTQ3Mzk5MzQsImV4cCI6MTY1NzMzMTkzNCwiaWQiOjE4LCJwYXNzd29yZCI6IkNDNkZBNjJEMjNFOTM1QjlBRUFGODMxQ0UwNEEyMzNEIiwic2Nob29sX2lkIjoxLCJwaG9uZSI6IjEzMzk5OTk5OTkxIiwibmFtZSI6IuWOu-WOu-WOuyIsInN0YXR1cyI6MCwidHlwZSI6MCwicm9sZXMiOjEsImV4cGlyZWQiOiIyMDIzLTEwLTI5VDE2OjAwOjAwLjAwMFoiLCJzY2hvb2xfbmFtZSI6IumYs-WFieaVmeiCsumbhuWbojciLCJzY2hvb2xfdHlwZSI6MSwiY3JlYXRlb24iOjE1NDE0OTc2NzYwMDB9.cOnkBbscUD4Dkc5ZqtH6WV6Nd7-KxvVitY6uRgLs6zQ" 
        //             : cc.find('middleLayer').getComponent('middleLayer').token
        // }

        if (cc.find('middleLayer')) {
            globalThis.____GAME_ENV____ = {
                baseUrl: cc.find('middleLayer').getComponent('middleLayer').baseUrl,
                token: cc.find('middleLayer').getComponent('middleLayer').token
            }
        }

        if (cc.sys.platform === cc.sys.DESKTOP_BROWSER ) {
            const u = new URL(window.location.href);
            const baseUrl = u.searchParams.get('baseUrl')
            const token = u.searchParams.get('token')
            if (baseUrl && token) {
                globalThis.____GAME_ENV____ = {
                    baseUrl,
                    token
                }
            } else {
                console.warn('in browser Env need baseUrl and token, eg. baseUrl is http://127.0.0.1:3900/api/ and token is xxxxx')
            }
        }



        this.initGame();


        this.initView();

        this.initEvent();
        this.initTipSys();
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.fetchUserData();
        return Promise.resolve()
    }
    fetchUserData() {
        this.showWaitingLetters();
        return Api.askUser().then(() => {
            this.hideWaitingLetters()
            this.initData();
        }).catch((e) => {
            this.hideWaitingLetters();
            let message = '网络错误，请返回重新进入';
            if (typeof e == 'string' && e) {
                message = e
            }
            // add for relogn
            let fn = null;
            if (message.includes('重新登录') || message.includes('登陆') ) {
                fn = () => {
                    cc.find('middleLayer').getComponent('middleLayer').exit();
                }
            }
            this.openTipAlert({message, 
            callback: () => {
                this.closeTipAlert();
                if (fn && fn.call) {
                    fn()
                }
                this.fetchUserData();
            }})
        })
    }
    initGame() {
        //基础效果 需要隐藏的内容处理。  首屏展示
    }
    _cantouch = null;

    initData() {
        // 所有全局变量 默认都是null
        this._cantouch = true;
        this.pengpeng.elephentState(user.mood == 0 ? 1 : 2);
        this.renderMyHouse();
    }

    private home: cc.Node;
    private kitchen: cc.Node;
    private shop: cc.Node;
    private loading: cc.Node;
    private exitButton: cc.Node;
    tws: any[] = [];
    LoadingCount: number = 1;
    initView() {
        this.tws = [];
        this.LoadingCount = 0;
        this.home = pg.view.find(this, "home");
        this.kitchen = pg.view.find(this, "kitchen");
        this.shop = pg.view.find(this, "shop");
        // this.elephant = pg.view.find(this.home, "elephant");
        const pengpengNode = pg.view.find(this.home, "pengpeng");
        this.pengpeng = pengpengNode.getComponent('pengpeng')
        this.loading = pg.view.find(this, "loading");
        this.exitButton = pg.view.find(this.home, "exit_btn");
    }

    initEvent() {
        // @ts-ignore
        this.wallpaper.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('wallpaper');
        }, this);
        // @ts-ignore
        this.floor.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('floor');
        }, this);
        // @ts-ignore
        this.wainscoting.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('wainscoting');
        }, this);
        // @ts-ignore
        // this.door.on(cc.Node.EventType.LONG_PRESS, function(){
        //     this.onTouchItemToChange('door');
        // }, this);
        // @ts-ignore
        this.lamp.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('lamp');
        }, this);
        // @ts-ignore
        this.carpet.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('carpet');
        }, this);
        // @ts-ignore
        this.window.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('window');
        }, this);
        // @ts-ignore
        this.sofa.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('sofa');
        }, this);
        // @ts-ignore
        this.flower.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('flower');
        }, this);
        // @ts-ignore
        this.cabinet.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('cabinet');
        }, this);
        // @ts-ignore
        this.photo.on(cc.Node.EventType.LONG_PRESS, function(){
            this.onTouchItemToChange('photo');
        }, this);
         // @ts-ignore
        this.door.on(cc.Node.EventType.LONG_PRESS, function(){
            pg.view.touchOff(pg.view.find(this.home, "btn_kitchen"), this.onTouchKitchen, this);
            // setTimeout(() => {
            //     pg.view.touchOn(pg.view.find(this.home, "btn_kitchen"), this.onTouchKitchen, this);
            // });
            this.onTouchItemToChange('door');
        }, this);
        // @ts-ignore
        this.door.on(cc.Node.EventType.LONG_PRESS_END, function(){
            pg.view.touchOn(pg.view.find(this.home, "btn_kitchen"), this.onTouchKitchen, this);
        }, this);

        console.log('this.pengpeng', this.pengpeng);
        const walkNode = pg.view.find(this.pengpeng, "walk")
        walkNode.on(cc.Node.EventType.LONG_PRESS, function(){
            console.log('walk cc.Node.EventType.LONG_PRESS')
            this.onTouchPengPengToChange();
        }, this);

        pg.view.touchOn(pg.view.find(this.home, "btn_kitchen"), this.onTouchKitchen, this);
        pg.view.touchOn(pg.view.find(this, "kitchen/btn_close"), this.onTouchKitchenClose, this);
        pg.view.touchOn(pg.view.find(this.home, "btn_shop"), this.onTouchShop, this);
        pg.view.touchOn(pg.view.find(this, "shop/btn_close"), this.onTouchShopClose, this);
        // pg.view.touchOn(pg.view.find(this.elephant, "walk"), this.onTouchElephent, this);
        // pg.view.touchOn(pg.view.find(this.elephant, "panel_info/btn_close"), this.onTouchPanel, this);
        pg.view.touchOn(this.exitButton, this.onExitPetRoom, this);
    }
    renderMyHouse() {
        const fur_kinds = Object.keys(user.myFurniture.furniture);
        const self = this;
        fur_kinds.forEach(kind => {
            const fur = user.myFurniture.furniture[kind];
            // console.log(kind, fur.rect)
            house.setFurnitureItem(self[kind], fur.id);
        });
    }
    //----------------------------商店部分--------------------------------------
    // 推出按钮
    onExitPetRoom() {
        cc.find('middleLayer').getComponent('middleLayer').exit();
    }
    // 换装相关
    onTouchItemToChange(kind){
        console.log('house', house.list);
        console.log('change', kind);
        this.updateMyHouseItemsListView(kind);
        this.skin_choice_dialog.active = true;
    }
    // 小鹏鹏
    onTouchPengPengToChange(){
        let scroll = pg.view.find(this.skin_choice_dialog, "dialog/scrollview");
        let svt = scroll.getComponent("svt");
        let list = dress.list;
        svt.list = list;
        if (list.length == 0) {
            return list;
        }
        svt.updateItem = this.updatemMyHouseItemsList;
        svt.target = this;
        svt.addNum = 2;
        svt.flush();
        this.skin_choice_dialog.active = true;
    }
    updateMyHouseItem(item, data: HouseItem) {
        item.active = true;

        let icon = pg.view.find(item, "icon");
        let current = pg.view.find(item, "current");
        pg.view.setNetImg(icon, data.cover, true);

        if (data.current) {
            pg.view.visible(current, true);
        } else {
            pg.view.visible(current, false);
        }
        if (data.type == ITEM_TYPE.HOUSE) {
            pg.view.touchOn(item, this.changeHouseItem.bind(this, data), this);
        } else {
            pg.view.touchOn(item, this.changeDressItem.bind(this, data), this);
        }
        item.data = data;
    }
    changeDressItem(data) {
        console.log('chanchangeDressItemgeHouseItem', data);
        const current = user.isCurrentDress(data.id);
        if (current) {
            return;
        }
        this.showWaitingLetters();
        this.pengpeng?.changeDress(data).then(() => {
            user.useClothes = data.id;
            this.hideWaitingLetters();
            Api.updateUserDress({id: data.id});
        }).catch(e => {
            this.openTipAlert({message: '皮肤加载失败，请退出重试(err: 1)',
                callback: () => {
                    this.closeTipAlert();
                }
            })
        });
        this.skin_choice_dialog.active = false;
    }
    changeHouseItem(data) {
        console.log('changeHouseItem', data);
        const {id, kind} = data;
        const current = user.isCurrentFurniture(id, kind);
        if (current) {
            return;
        }
        console.log(111,data);
        // close dialog
        this.skin_choice_dialog.active = false;
        // @ts-ignore
        this[kind].changeFurniture(data);
    }
    updatemMyHouseItemsList(item, datas) {
        item.children.forEach(it => it.active = false);
        for (let i = 0; i < datas.length; i++) {
            let it = item.children[i];
            let dt = datas[i];
            if (dt) {
                // console.log(dt.name);
                this.updateMyHouseItem(it, dt);
            }
        }
    }

    updateMyHouseItemsListView(kind) {
        let scroll = pg.view.find(this.skin_choice_dialog, "dialog/scrollview");
        let svt = scroll.getComponent("svt");
        let list = house.getListByKind(kind);
        svt.list = list;
        if (list.length == 0) {
            return list;
        }
        svt.updateItem = this.updatemMyHouseItemsList;
        svt.target = this;
        svt.addNum = 2;
        svt.flush();
        return list;
    }

    //商店按钮
    private shopType = 0;
    onTouchShop() {console.log('onTouchShop')
        this.shop.active = true;

        this.updateShopCoin();

        let btns = pg.view.find(this.shop, "btns");
        let btn_food_wait = pg.view.find(btns, "btn_food_wait");
        let btn_house_wait = pg.view.find(btns, "btn_house_wait");
        let btn_clothes_wait = pg.view.find(btns, "btn_clothes_wait");
        pg.view.touchOn(btn_food_wait, this.onTouchShopFood, this);
        pg.view.touchOn(btn_house_wait, this.onTouchShopHouse, this);
        pg.view.touchOn(btn_clothes_wait, this.onTouchShopClothes, this);

        this.shopType = ITEM_TYPE.FOOD;
        this.updateShopList();
        this.updateShopBtns();

    }
    onTouchShopClose() {
        this.shop.active = false;
    }
    onTouchShopFood() {
        this.shopType = ITEM_TYPE.FOOD;
        this.updateShopList();
        this.updateShopBtns();
    }
    onTouchShopHouse() {
        this.shopType = ITEM_TYPE.HOUSE;
        const list = this.updateShopList();
        if (!list.length) {
            this.openTipEmpty(() => {
                this.closeTipEmpty();
            });
            return;
        }
        this.updateShopBtns();
    }
    onTouchShopClothes() {console.log('onTouchShopClothes')
        this.shopType = ITEM_TYPE.CLOTHES;
        const list = this.updateShopList();
        if (!list.length) {
            this.openTipEmpty(() => {
                this.closeTipEmpty();
            });
        }
        this.updateShopBtns();
    }
    updateShopCoin() {
        let coin = pg.view.find(this.shop, "coin/num");
        pg.view.setString(coin, user.coin);
    }
    updateShopList() {
        let scroll = pg.view.find(this.shop, "scrollview");
        let svt = scroll.getComponent("svt");
        let list = shop.getListByType(this.shopType);
        svt.list = list;
        if (list.length == 0) {
            return list;
        }
        svt.updateItem = this.updateShopItems;
        svt.target = this;
        svt.addNum = 4;
        svt.flush();
        return list;
    }
    updateShopBtns() {
        let btns = pg.view.find(this.shop, "btns");
        let btn_food_wait = pg.view.find(btns, "btn_food_wait");
        let btn_food_active = pg.view.find(btns, "btn_food_active");
        let btn_house_wait = pg.view.find(btns, "btn_house_wait");
        let btn_house_active = pg.view.find(btns, "btn_house_active");
        let btn_clothes_wait = pg.view.find(btns, "btn_clothes_wait");
        let btn_clothes_active = pg.view.find(btns, "btn_clothes_active");
        btn_food_wait.active = this.shopType != ITEM_TYPE.FOOD;
        btn_food_active.active = this.shopType == ITEM_TYPE.FOOD;
        btn_house_wait.active = this.shopType != ITEM_TYPE.HOUSE;
        btn_house_active.active = this.shopType == ITEM_TYPE.HOUSE;
        btn_clothes_wait.active = this.shopType != ITEM_TYPE.CLOTHES;
        btn_clothes_active.active = this.shopType == ITEM_TYPE.CLOTHES;
    }
    updateShopItems(item, datas) {
        item.children.forEach(it => it.active = false);
        for (let i = 0; i < datas.length; i++) {
            let it = item.children[i];
            let dt = datas[i];
            if (dt) {
                // console.log(dt.name);
                this.updateShopItem(it, dt);
            }
        }
    }
    updateShopItem(item, data: Item|HouseItem) {
        item.active = true;
        let growth = pg.view.find(item, "bg_food/growth");
        let txt = pg.view.find(item, "bg_food/txt");
        let name = pg.view.find(item, "bg_food/name");
        let icon = pg.view.find(item, "bg_food/icon");
        let discount = pg.view.find(item, "bg_food/discount");
        let btn_buy = pg.view.find(item, "bg_food/btn_buy");

        if(([ITEM_TYPE.HOUSE, ITEM_TYPE.CLOTHES].includes(data.type)) && (data as HouseItem).num > 0) {
            let own = pg.view.find(item, "bg_food/own");
            pg.view.visible(own, true);
        }

        pg.view.setString(txt, `可增加        个成长值`)
        pg.view.setString(growth, data.growthValue)
        pg.view.setString(name, data.name)
        // console.log(data.cover);
        pg.view.setNetImg(icon, data.cover, false)
        // icon.getComponent(cc.Sprite).spriteFrame = this[data.icon];

        let dis = Math.round((1 - data.discount) * 100);
        if (dis > 0) {
            pg.view.setString(discount, `${dis}%`)
            pg.view.visible(pg.view.find(item, "bg_food/bg_sale"), true);
            pg.view.visible(pg.view.find(item, "bg_food/discount"), true);
        } else {
            pg.view.visible(pg.view.find(item, "bg_food/bg_sale"), false);
            pg.view.visible(pg.view.find(item, "bg_food/discount"), false);
        }

        pg.view.setString(pg.view.find(btn_buy, "num"), data.cost)
        pg.view.touchOn(item, this.onTouchShopItem, this);
        item.data = data;
    }
    onTouchShopItem(e) {console.log('onTouchShopItem')
        let item = e.target; // .parent;
        let data: Item = item.data;
        let action = null;
        if (data.type == ITEM_TYPE.FOOD) {
            action = this.buy.bind(this);
        } else if (data.type == ITEM_TYPE.HOUSE || data.type == ITEM_TYPE.CLOTHES) {
            //物品已购买
            if (data.num > 0) {
                this.openTipNormal(data, () => {
                    this.closeTipNormal();
                }, null, '你已经拥有该物品，无需购买！')
                return;
            }
            action = this.buy.bind(this);
        }

        if (!action) {
            return;
        }
        //弹出购买弹窗
        console.log(user, data)
        if (user.coin >= data.cost * data.discount) {
            this.openTipNormal(data, () => {
                action(data);
                this.closeTipNormal();
            }, () => {
                this.closeTipNormal();
            })
        } else {
            this.openTipFail(data, () => {
                this.closeTipFail();
            }, () => {
                this.closeTipFail();
            })
        }
    }
    buy(data) {
        this.showWaitingLetters();
        console.log('buy', data)
        Api.askBuyItem(data).then((resp) => {
            this.fetchUserData().then(ud => {
                this.hideWaitingLetters(true)
                this.updateShopCoin();
                this.updateShopList();
                this.updateShopBtns();
                this.openTipBuy(data, () => {
                    this.closeTipBuy();
                    if (data.type == ITEM_TYPE.HOUSE) {
                        this.openTipAlert({message: '长按家具，可以更换装扮哦～',
                            callback: () => {
                                this.closeTipAlert();
                            }
                        })
                    }
                });
            }).catch(e => {
                this.hideWaitingLetters(true);
                this.openTipAlert({message: '网络错误，请重试(err: 1)', 
                    callback: () => {
                        this.closeTipAlert();
                    }
                })
            });
        }).catch(e => {
            this.hideWaitingLetters(true);
            this.openTipAlert({message: '网络错误，请重试(err: 2)',  
                callback: () => {
                    this.closeTipAlert();
                }
            })
        })
    }
    //----------------------------冰箱部分--------------------------------------
    onTouchKitchen() {
        this.kitchen.active = true;
        let coin = pg.view.find(this.kitchen, "coin/num");
        pg.view.setString(coin, user.coin);

        let scroll = pg.view.find(this.kitchen, "scrollview");
        let svt = scroll.getComponent("svt");
        svt.list = kitchen.getListByType(ITEM_TYPE.FOOD); //kitchen.list;
        svt.updateItem = this.updateChickenItems;
        svt.target = this;
        svt.addNum = 4;
        svt.flush();
    }
    onTouchKitchenClose() {
        this.kitchen.active = false;
    }
    updateChickenItems(item, datas) {
        item.children.forEach(it => it.active = false);
        for (let i = 0; i < datas.length; i++) {
            let it = item.children[i];
            it.active = false;
            let dt = datas[i];
            if (dt) {
                this.updateChickenItem(it, dt);
            }
        }
    }
    updateChickenItem(item, data: Item) {
        // console.log(data);
        item.active = true;
        let growth = pg.view.find(item, "growth");
        let name = pg.view.find(item, "name");
        let icon = pg.view.find(item, "icon");
        let num = pg.view.find(item, "num");
        pg.view.setString(growth, `成长值+${data.growthValue}`)
        pg.view.setString(name, data.name)
        pg.view.setString(num, data.num)
        // icon.getComponent(cc.Sprite).spriteFrame = this[data.icon];
        pg.view.setNetImg(icon, data.cover)
        pg.view.touchOn(item, this.onTouchChickenItem, this);
        item.data = data;
    }
    onTouchChickenItem(e) {
        let item = e.target;
        let data: Item = item.data;
        //吃东西。  关闭界面，并展示吃东西的画面，如果不足的情况提示不足。
        if (data.num <= 0) return;
        if (data.type == 1) {
            this.eating(data);
        } else if (data.type == 2) {
            //物品使用
        }
    }
    eating(data) {
        //可以检测是否升级等---升级说明之类的
        this.showWaitingLetters();
        window.aaaa = this;
        Api.askUseItem(data).then((resp) => {
            this.fetchUserData().then(ud => {
                this.hideWaitingLetters(true);
                // this.elephentState(3);
                this.onTouchKitchenClose();
                setTimeout(() => {
                    this.pengpeng.elephentState(3);
                })
            }).catch(e => {
                this.hideWaitingLetters(true);
                this.openTipAlert({message: '网络错误，请重试(err: 1)', 
                    callback: () => {
                        this.closeTipAlert();
                    }
                })
            });
        }).catch(e => {
            this.hideWaitingLetters(true);
            this.openTipAlert({message: '网络错误，请重试(err: 2)',  
                callback: () => {
                    this.closeTipAlert();
                }
            })
        })
    }

    /*
    //----------------------------主界面部分--------------------------------------
    //打开提示面板
    onTouchElephent() {
        this.elephentState(user.mood == 0 ? 1 : 2);

        let panel_info = pg.view.find(this.elephant, "panel_info");
        panel_info.active = true;
        //刷新内容
        let label_name = pg.view.find(panel_info, "label_name");
        pg.view.setString(label_name, user.name);
        let label_level = pg.view.find(panel_info, "label_level");
        pg.view.setString(label_level, `LV.${user.level ? user.level : 0 }`);

        let icon_happy = pg.view.find(panel_info, "icon_happy");
        let icon_hungry = pg.view.find(panel_info, "icon_hungry");
        icon_happy.active = user.mood == 0;
        icon_hungry.active = user.mood == 1;

        let percent = user.growth / user.growthLevel;
        let progress = pg.view.find(panel_info, "progress");
        progress.getComponent(cc.ProgressBar).progress = percent;
    }
    //关闭提示面板
    onTouchPanel() {
        let panel_info = pg.view.find(this.elephant, "panel_info");
        panel_info.active = false;
        this.elephentState(0);
    }
    //小象的动作管理。
    private elephant: cc.Node;
    private _timer: number;
    elephentState(state) {
        switch (state) {
            case 0:
                this.elephantWalk();
                break;
            case 1:
                this.elephantHappy();
                break;
            case 2:
                this.elephantHungry();
                break;
            case 3:
                this.elephantEating();
                break;
        }
    }
    elephantWalk() {
        let walkAni = pg.view.find(this.elephant, "walk");
        let eatAni = pg.view.find(this.elephant, "eat");
        walkAni.active = true;
        eatAni.active = false;
        let db = pg.view.playDBAnimation(walkAni, "walking", 0);
        this.removeHungryAudio(db);
        cc.Tween.stopAllByTarget(this.elephant);
        walkAni.scaleX = 1;
        let moveX = 400;
        let moveY = 0;
        let winSize = cc.winSize;
        if (winSize.width / winSize.height < 16 / 9) {
            moveY = -(16 / 9 - winSize.width / winSize.height) * 750 / 2;
        }
        if (!this.elephant.active) {
            this.elephant.active = true;
            this.elephant.x = 0;
            this.elephant.y = moveY + Math.random() * 100;
        }
        cc.tween(this.elephant)
            .to(4, { x: moveX, y: moveY + Math.random() * 100 })
            .call(() => {
                walkAni.scaleX = -1;
            })
            .to(4, { x: 0, y: moveY + Math.random() * 100 })
            .to(4, { x: -moveX, y: moveY + Math.random() * 100 })
            .call(() => {
                walkAni.scaleX = 1;
            })
            .to(4, { x: 0, y: moveY + Math.random() * 100 })
            .call(() => {
                this.elephentState(0);
            })
            .start();
    }
    elephantHappy() {
        let walkAni = pg.view.find(this.elephant, "walk");
        let eatAni = pg.view.find(this.elephant, "eat");
        walkAni.active = true;
        eatAni.active = false;
        let db = pg.view.playDBAnimation(walkAni, "happy", 0);
        this.removeHungryAudio(db);
        cc.Tween.stopAllByTarget(this.elephant);
        walkAni.scaleX = 1;
    }
    elephantHungry() {
        let walkAni = pg.view.find(this.elephant, "walk");
        let eatAni = pg.view.find(this.elephant, "eat");
        walkAni.active = true;
        eatAni.active = false;
        this.playLocalAudio("hungry");
        let db: dragonBones.ArmatureDisplay = pg.view.playDBAnimation(walkAni, "hungry", 0);
        this.removeHungryAudio(db);
        this.addHungryAudio(db);
        cc.Tween.stopAllByTarget(this.elephant);
        walkAni.scaleX = 1;
    }
    elephantEating() {
        let walkAni = pg.view.find(this.elephant, "walk");
        let eatAni = pg.view.find(this.elephant, "eat");
        walkAni.active = false;
        eatAni.active = true;
        pg.view.playDBAnimation(eatAni, "eating", 0);
        cc.Tween.stopAllByTarget(this.elephant);
        this.playLocalAudio("eating");
        setTimeout(() => {
            this.elephentState(0);
        }, 3500);
    }

    addHungryAudio(db: dragonBones.ArmatureDisplay) {
        db.addEventListener(dragonBones.EventObject.LOOP_COMPLETE, this.playHungryAudio, this)
    }
    removeHungryAudio(db: dragonBones.ArmatureDisplay) {
        db.removeEventListener(dragonBones.EventObject.LOOP_COMPLETE, this.playHungryAudio, this)
    }
    playHungryAudio() {
        this.playLocalAudio("hungry");
    }
    */



    //-----------------------------提示面板部分-----------------------------------------
    private tip_normal: cc.Node;
    private tip_buy: cc.Node;
    private tip_fail: cc.Node;
    private tip_empty: cc.Node;
    private tip_alert: cc.Node;
    private tipSuccess: Function|null;
    private tipCancel: Function|null;
    private tipBuySuccess: Function|null;
    private tipFailSuccess: Function|null;
    private tipFailCancel: Function|null;
    private tipEmptySuccess: Function|null;
    private tipAlertCallback: Function|null;

    private skin_choice_dialog: cc.Node;
    
    initTipSys() {
        this.tip_normal = pg.view.find(this, "tip_normal");
        this.tip_buy = pg.view.find(this, "tip_buy");
        this.tip_fail = pg.view.find(this, "tip_fail");
        this.tip_empty = pg.view.find(this, "tip_empty");
        this.tip_alert = pg.view.find(this, "tip_alert");
        pg.view.touchOn(pg.view.find(this.tip_normal, "btn_sure"), () => { this.tipSuccess && this.tipSuccess() }, this);
        pg.view.touchOn(pg.view.find(this.tip_normal, "btn_cancel"), () => { this.tipCancel && this.tipCancel() }, this);
        pg.view.touchOn(pg.view.find(this.tip_buy, "btn_cancel"), () => { this.tipBuySuccess && this.tipBuySuccess() }, this);
        pg.view.touchOn(pg.view.find(this.tip_fail, "btn_sure"), () => { this.tipFailSuccess && this.tipFailSuccess() }, this);
        pg.view.touchOn(pg.view.find(this.tip_fail, "btn_cancel"), () => { this.tipFailCancel && this.tipFailCancel() }, this);
        pg.view.touchOn(pg.view.find(this.tip_empty, "btn_cancel"), () => { this.tipEmptySuccess && this.tipEmptySuccess() }, this);
        pg.view.touchOn(pg.view.find(this.tip_alert, "btn_cancel"), () => { this.tipAlertCallback && this.tipAlertCallback() }, this);


        this.skin_choice_dialog = pg.view.find(this, "home/item_choice_dialog");
        pg.view.touchOn(pg.view.find(this.skin_choice_dialog, "dialog/close"), () => {
            this.skin_choice_dialog.active = false;
         }, this);

    }
    openTipNormal(data: Item, success, cancel, msg = null) {
        this.tip_normal.active = true;
        this.tipSuccess = success;
        this.tipCancel = cancel;
        if (!cancel) {
            pg.view.visible(pg.view.find(this.tip_normal, "btn_cancel"), false);
        } else {
            pg.view.visible(pg.view.find(this.tip_normal, "btn_cancel"), true);
        }
        if (data) {
            let message = `确定花${data.cost * data.discount}金币购买${data.name}吗？`;
            if (msg) {
                message = msg;
            }
            pg.view.setString(pg.view.find(this.tip_normal, "desc"), message);
            let icon = pg.view.find(this.tip_normal, "icon");
            // icon.getComponent(cc.Sprite).spriteFrame = this[data.icon];
            pg.view.setNetImg(icon, data.cover)
        }
    }
    closeTipNormal() {
        this.tip_normal.active = false;
        this.tipSuccess = null;
        this.tipCancel = null;
    }
    openTipFail(data: Item, success, cancel) {
        this.tip_fail.active = true;
        this.tipFailSuccess = success;
        this.tipFailCancel = cancel;
    }
    closeTipFail() {
        this.tip_fail.active = false;
        this.tipFailSuccess = null;
        this.tipFailCancel = null;
    }

    openTipBuy(data: Item, success) {
        this.tip_buy.active = true;
        this.tipBuySuccess = success;
        if (data) {
            let icon = pg.view.find(this.tip_buy, "icon");
            // icon.getComponent(cc.Sprite).spriteFrame = this[data.icon];
            pg.view.setNetImg(icon, data.cover, false)
        }
    }
    closeTipBuy() {
        this.tip_buy.active = false;
        this.tipBuySuccess = null;
    }

    openTipEmpty(success) {
        this.tip_empty.active = true;
        this.tipEmptySuccess = success;
    }
    closeTipEmpty() {
        this.tip_empty.active = false;
    }


    openTipAlert({message, btnText, callback}: {message?: string, btnText?: string, callback: (...args) => void}) {
        if (message) {
            const tipNode = this.tip_alert.getChildByName('tip_empty');
            const messageNode = tipNode.getChildByName('message');
            const lbl = messageNode.getComponent(cc.RichText);
            lbl.string = `<color=#333333>${message}</color>`;
        }
        if (btnText) {
            const btnNode = this.tip_alert.getChildByName('btn_ok');
            const btnTxtNode = btnNode.getChildByName('txt');
            const lbl = btnTxtNode.getComponent(cc.Label);
            lbl.string = btnText;
        }
        this.tip_alert.active = true;
        this.tipAlertCallback = callback;
    }
    closeTipAlert() {
        this.tip_alert.active = false;
    }

    
    hideWaitingLetters(force = false) {
        if (force) {
            this.LoadingCount = 0;
        } else {
            this.LoadingCount--;
        }
        
        if (this.LoadingCount <= 0) {
            this.LoadingCount = 0;
            setTimeout(() => {
                if (this.tws){
                    for (const tw of this.tws) {
                        tw.node.y = 0;
                        tw.tw.stop();
                    }
                } 
                this.loading.active = false;
            });
        }
    }
    showWaitingLetters() {
        this.LoadingCount += 1;
        if (this.loading.active) {
            return;
        }
        const colorList = this.getRainbowColorList();
        const text = this.loading.getChildByName('text')
        text.children.forEach((node, idx) => {
            node.color = colorList[idx];
            const tw = cc.tween(node)
            .delay(idx / 4)
            .to(0.3, { y: 30 }, { easing: 'sineOut' })
            .to(0.3, { y: -30 }, { easing: 'sineIn' })
            .delay((text.children.length - idx) / 4)
            .union()
            .repeatForever()
            .start();
            this.tws.push({
                tw,
                node
            });
        });
        this.loading.active = true;
    }
    getRainbowColorList() {
        return [
            cc.color(255, 255, 0),
            cc.color(128, 255, 0),
            cc.color(0, 255, 0),

            cc.color(0, 255, 128),
            cc.color(0, 255, 255),

            cc.color(0, 128, 255),
            cc.color(0, 0, 255),
            cc.color(128, 0, 255),
            cc.color(255, 0, 255),
            cc.color(255, 0, 128),

            cc.color(255, 0, 0),
            cc.color(255, 128, 0),
            cc.color(255, 255, 0),
        ];
    }





    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;
        console.error('initBg')
    }
    playLocalAudio(audioName) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }
}



//未完成功能。
//1.商城购买流程。  不足提示框
//2.商城切换流程。  空提示框
//3.物品使用http请求。

//未确定功能
// 1.所有的家具使用
// 2.所有的衣服使用

