import Player from "../game/data/udata/Player";
import Main from "../main/Main";
import { GameViewType } from "../main/ViewManage";
import ViewObject from "../main/ViewObject";
import PlotHome from "../plot/PlotHome";
import PlotView from "../plot/PlotView";
import CHttp, { HttpStateType, ReveData } from "../util/CHttp";
import CMath from "../util/CMath";
import HistoryArea from "./HistoryArea";
import Tap_set_Ann from "./Tap_set_Ann";


/**
 * 游戏分区
 */
export interface Zone {
    id: number,
    hardwareId: number,
    name: string,
    rec: boolean,//是否推荐
    inew: boolean,//是否新区
}
/**
 * 历史角色数据
 */
export interface History_Role {
    zoneId: number,
    name: string,
    level: number,
    time: number,//最后登陆的时间
}

/**
 * 选择分区界面
 */
const { ccclass, property } = cc._decorator;

@ccclass
export default class Area extends ViewObject {

    @property(cc.Label)
    mZoneName: cc.Label = null;//服务器名字

    public zones: Array<Zone> = null;

    public roles: Array<History_Role> = null;

    public gameServer: string = null;

    onLoad() {
        this.loadZone();
    }
    start(){
        this.opentap_set_Ann()
    }
    public loadZone() {
        let http = this.main.loginHttp;

        let msg = {
            channel: this.main.profile.mChannel.toString(),
            userId: this.main.userData.id.toString()
        }

        this.main.startLoad();
        http.sendForm('/getZone', msg, (state, reve: any) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                this.zones = reve.zones;
                this.roles = reve.roles;
                this.gameServer = reve.gameServer;

                this.init();
            } else {
                this.main.showTips('网络异常');
            }
        })
    }


    public onclickBack() {
        this.exitDistroy();
    }

    public init() {
        let optZone = this.getOptZone();
        this.setOptZone(optZone);
    }

    public setOptZone(optZone) {
        this.main.userData.zone = optZone;
        this.mZoneName.string = optZone.name
    }

    public getZoneById(id: number) {
        if (this.zones == null) {
            return null;
        }
        for (let i = 0; i < this.zones.length; i++) {
            const element = this.zones[i];
            if (element.id == id) {
                return element;
            }
        }
        return null;
    }

    /**
     * 获取最优化分区
     */
    public getOptZone(): Zone {
        let latelyZone = null;
        //最近玩过的分区
        latelyZone = this.getLatelyZone();
        if (latelyZone) {
            return latelyZone;
        }
        //推荐分区
        latelyZone = this.getRecZone();
        if (latelyZone) {
            return latelyZone;
        }
        //随机一个区
        return this.zones[CMath.getRandom(0, this.zones.length - 1)];;
    }
    /**
     * 获取最近玩过的区
     */
    private getLatelyZone(): Zone {
        if (this.roles == null) {
            return null;
        }
        let latelyRole: History_Role = null;
        for (let i = 0; i < this.roles.length; i++) {
            const element = this.roles[i];
            if (latelyRole == null) {
                latelyRole = element;
            } else {
                if (element.time > latelyRole.time) {
                    latelyRole = element;
                }
            }
        }
        return this.getZoneById(latelyRole.zoneId);
    }
    /**
     * 获取推荐分区
     */
    private getRecZone(): Zone {
        if (this.zones == null) {
            return null;
        }
        let recs = [];
        for (let i = 0; i < this.zones.length; i++) {
            const element = this.zones[i];
            if (element.rec) {
                recs.push(element);
            }
        }
        if (recs.length <= 0) {
            return null;
        }
        return recs[CMath.getRandom(0, recs.length - 1)];
    }
    /**
     * 打开历史登陆的分区
     */
    public openHistoryArea() {
        this.main.startLoad();
        this.main.viewManage.loadFunc(GameViewType.historyArea, (viewObject: ViewObject) => {
            let historyArea = viewObject as HistoryArea;
            historyArea.area = this;
            viewObject.show();
            this.main.stopLoad();
        });
    }

    /**
        * 进入游戏
        */
    public onclickOK() {
        let userData = this.main.userData;
        let optZone = this.main.userData.zone
        let http: CHttp = new CHttp(this.gameServer + '/H' + optZone.hardwareId + '/');
        let msg = {
            channel: this.main.profile.mChannel,
            channelAttr: '测试',
            id: userData.id,
            token: userData.token,
            zoneId: optZone.id
        }
        this.main.startLoad();
        http.token = '08f0656590e33d39021d41714994383d';
        http.sendJson('login', msg, (state, reve: ReveData) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    this.main.player = new Player(reve.data);
                    http.token = this.main.player.role.token;
                    http.id = this.main.player.role.id;
                    http.userId = this.main.userData.id;
                    this.main.gameHttp = http;
                    this.main.gameHttp.unshiftEvent(this.main.player);
                    if (reve.data.isNew) {
                        // if(true){
                        this.openPlot()
                    } else {
                        this.openHome(this.main);
                    }
                } else {
                    this.main.showTips(reve.message);
                }
            } else {
                this.main.showTips('网络异常');
            }
        });
    }

    public openHome(main: Main) {
        main.viewManage.loadFunc(GameViewType.home, (viewObject: ViewObject) => {
            this.__distroyAll();
            let plotHome = viewObject.node.getComponent(PlotHome)
            plotHome.openMenu()
            viewObject.show();
        });
    }
    public openPlot() {
        let main = this.main;
        this.main.viewManage.loadFunc(GameViewType.plot_view, (viewObject: ViewObject) => {
            this.__distroyAll();
            let plotView = viewObject as PlotView;
            plotView.setCloseCallback(() => {
                main.viewManage.loadFunc(GameViewType.home, (viewObject: ViewObject) => {
                    let plotHome = viewObject.node.getComponent(PlotHome)
                    plotHome.exDialog()
                    viewObject.show();
                });
            })
            viewObject.show();
        });
    }

    /**
     * 公告
     */
    public opentap_set_Ann() {
        this.main.viewManage.loadFunc(GameViewType.tap_set_Ann, (viewObject: ViewObject) => {
            viewObject.show();
        });
    }
}