var reGameStates = require('GameStates');
var AConfig = require('../Config');

//全局数据类
cc.Class({
    extends: cc.Component,
    properties: {
        //记录全部道路的index
        GameData_highwayIndex: {
            default: [],
            type: [cc.Integer],
            visible: false,
            serializable: false,
        },

        //记录建筑物存储的信息
        GameData_buildings: {
            default: [],
            visible: false,
            serializable: false,
        },
        HighWayPrefabs: cc.Prefab,
        //MyMapNode
        //建筑物的节点
        BuildingsParent: {
            default: null,
            type: cc.Node,
        },
        ManageUI: {
            default: null,
            type: cc.Node,
        },

        GameVersion: {
            default: -1,
            type: cc.Integer,
        },

        //读取数据
        readData: {
            default: null,
            visible: false,
        }

    },
    onLoad() {
        //初始化GameData全局变量
        GlobalD.GameData = this;
        this.GameConfig();
    },
    start() {
        this._tiledMap = GlobalD.TiledMap._tiledMap;

        //老铁 请选择 游戏模式
        //true 每次进入清除数据模式
        //false 正常带网络存档模式
        this.isDebugMode(false);

        // return;
    },
    //设置游戏模式
    isDebugMode: function (b) {
        if (b) {
            // 清除
            this.onClearAllData();
            this.getData();
        } else {
            // 正常游戏
            this.getData();
        }
    },



    getData: function () {

        //如果开局没有读取到网络数据，就这里初始化
        if (userData.readData == null) {
            // cc.log("本地数据：", cc.sys.localStorage.getItem('userdata'));
            let userdata = cc.sys.localStorage.getItem('userdata');
            if (userdata) {
                this.readData = JSON.parse(userdata);
            }
            this.Init();
            this.InitSceneInfo();
        } else {
            this.readData = userData.readData;
            // cc.log('读取到数据？：', this.readData)

            this.Init();
            this.InitSceneInfo();

        }

    },


    GameConfig() {
        this.AddBuildingCost = 5;
        this.RemoveBuildingCost = 5;
    },
    InitSceneInfo() {
        //根据顺序生成
        //初始化道路
        this.onSpawnHighway();
        //初始化时间ui
        cc.find("GameNode/ManageTimer").getComponent('ManageTimer').Init();
        //初始化金钱ui
        cc.find("GameNode/ManageGolden").getComponent('ManageGolden').InitManageGlodenUI();
        // //初始化地图物件
        // cc.find("GameNode/ManageMap").getComponent('ManageMap').InitManageMap();
        GlobalD.TiledMap.onInitSolid();

        //初始化生成房屋
        this.ManageUI.getComponent('ManageBuildings').InitBuildings();
        //初始化生成人物
        cc.find('GameNode/ManageWorker').getComponent('ManageWorker').InitWorkerAI();

        let _BFirstLoadGame = this.readData ? this.readData.BFirstLoadGame : false;
        //初始化新手教学
        GlobalD.ManageTask.InitTask(_BFirstLoadGame);

        this.ManageUI.getComponent('ManageUI').Init();

        // 自动存储数据
        this.AutoSaveData = function () {
            this.pushData();
        };
        this.schedule(this.AutoSaveData, 5);
    },
    //InitData
    Init: function () {

        // let BFirstLoadGame = parseInt(cc.sys.localStorage.getItem('BFirstLoadGame'));
        let _BFirstLoadGame = this.readData ? this.readData.BFirstLoadGame : false;
        //date
        this.GameYear = 0;
        this.GameMonth = 0;
        this.GameDay = 0;
        this.GameDate = '0000/00/01';

        this.Golden = 2000;
        this.Diamond = 100;
        this.WorkerLV = 0;
        this.WorkerNum = 0;
        this.CharacterInfoArray = [];
        this.WorkerCapacity = 5;

        this.TerritoryStateArray = [1, 1, 1, 1, 1, 1, 1, 1];//测试，全开地图
        // this.BuildingStateArray = [
        //     0, //公路
        //     0,  //路铲
        //     1,  //拆迁
        //     1,  //农舍
        //     0,  //单元楼
        //     0,  //别墅
        //     1,  //农田
        //     0, //伐木场
        //     0, //矿坑
        //     0, //加工厂
        //     1, //便利店
        //     0, //鲜花店
        //     0, //甜品店
        //     0, //汉堡店
        //     0, //咖啡店
        //     0, //洋装店
        //     0, //酒吧
        //     1, //绿化带
        //     0, //喷泉
        //     0, //游乐场
        //     0, //医院
        //     0,//警察局
        //     0];//银行
        this.BuildingStateArray = [
            1, //公路
            1,  //路铲
            1,  //拆迁
            1,  //农舍
            1,  //单元楼
            1,  //别墅
            1, //农田
            1,//伐木场
            1, //矿坑
            1, //加工厂
            1,//冷饮摊
            1,//贩卖机
            1,//面包房
            1,//早餐车
            1, //饮茶店
            1,//点心店
            1, //美食店
            1,//西餐厅
            1, //花店
            1, //美发店
            1,//洋装店
            1, //珠宝店
            1, //电影院
            1,//路灯
            1, //绿化带
            1, //花坛
            1,//喷泉
            1, //警察局
            1,//游乐场
            1,  //蓝色城堡
            1 //粉色城堡
        ];
        this.BuildingLockStateArray = [
            1, //公路
            1,  //路铲
            1,  //拆迁
            1,  //农舍
            0,  //单元楼
            0,  //别墅
            1, //农田
            0,//伐木场
            0, //矿坑
            1, //加工厂
            0,//冷饮摊
            0,//贩卖机
            0,//面包房
            0,//早餐车
            0, //饮茶店
            0,//点心店
            0, //美食店
            0,//西餐厅
            0, //花店
            0, //美发店
            0,//洋装店
            0, //珠宝店
            0, //电影院
            1,//路灯
            1, //绿化带
            1, //花坛
            0,//喷泉
            0, //警察局
            0,//游乐场
            0,  //蓝色城堡
            0 //粉色城堡
        ];
        // this.BuildingLockStateArray = [
        // 1, //公路
        // 1, //路铲
        // 1,  //拆迁
        // 1,  //农舍
        // 1,  //单元楼
        // 1,  //别墅
        // 1, //农田
        // 1,//伐木场
        // 1,//矿坑
        // 1, //加工厂
        // 1,//便利店
        // 1,//鲜花店
        // 1,//甜品店
        // 1, //汉堡店
        // 1,//咖啡店
        // 1, //洋装店
        // 1, //酒吧
        // 1, //绿化带
        // 1,//喷泉
        // 1,//游乐场
        // 0, //医院
        // 0,//警察局
        // 0];//银行
        this.BuildingNumArray = [
            0, //公路
            0,  //路铲
            0,  //拆迁
            4,  //农舍
            1,  //单元楼
            1,  //别墅
            4, //农田
            1,//伐木场
            1, //矿坑
            2, //加工厂
            2,//冷饮摊
            1,//贩卖机
            1,//面包房
            1,//早餐车
            1, //饮茶店
            1,//点心店
            1, //美食店
            1,//西餐厅
            1, //花店
            1, //美发店
            1,//洋装店
            1, //珠宝店
            1, //电影院
            1,//路灯
            1, //绿化带
            1, //花坛
            1,//喷泉
            1, //警察局
            1,//游乐场
            1,  //蓝色城堡
            1  //粉色城堡
        ];
        // this.BuildingNumArray = [
        // 0, //公路
        // 0,  //路铲
        // 0, //拆迁
        // 10,  //农舍
        // 10, //单元楼
        // 10, //别墅
        // 10,  //农田
        // 10, //伐木场
        // 10, //矿坑
        // 10, //加工厂
        // 10, //便利店
        // 9, //鲜花店
        // 8, //甜品店
        // 7,//汉堡店
        // 6,//咖啡店
        // 5,//洋装店
        // 4, //酒吧
        // 10, //绿化带
        // 10,//喷泉
        // 10, //游乐场
        // 0, //医院
        // 0, //警察局
        // 0];//银行

        //钻石消耗默认值
        this.DiamondNumArray = AConfig.DiamondArray;
        // cc.log('钻石消耗默认值',this.DiamondNumArray);
        this.EveryDayRewardsArray = [0, 0, 0, 0, 0, 0, 0];

        this.LastTimeEveryDayRewardsDate = '0000/00/00';
        this.LastTimeLuckDate = '0000/00/00';

        this.FoodTradeState = 1;
        this.WoodTradeState = 1;
        this.MineralTradeState = 1;
        //转盘分享给钻石金币
        this.shareGive = [200, 5];

        //签到分享给钻石金币
        this.signInGive = [200, 5];
        //每个月 给的 低保
        this.EveryGive = [500, 10];

        //公共分享
        this.publicGive = [200, 50];

        //每天抽奖次数
        this.LotteryTimes = 10;

        if (_BFirstLoadGame) {

            // cc.log('初始化网络数据');
            //读取日期数据
            this.GameYear = this.readData.GameYear;
            this.GameMonth = this.readData.GameMonth;
            this.GameDay = this.readData.GameDay;

            //读取金币
            this.Golden = this.readData.Golden;


            //读取钻石
            this.Diamond = this.readData.Diamond;
            // cc.log('this.readData.Diamond', this.readData.Diamond);
            //读取工人等级
            this.WorkerLV = this.readData.WorkerLV;
            //工人数量
            this.WorkerNum = this.readData.WorkerNum;
            //工人容量
            this.WorkerCapacity = this.readData.WorkerCapacity;
            this.GameDate = this.readData.GameDate;
            this.LastTimeEveryDayRewardsDate = this.readData.LastTimeEveryDayRewardsDate;
            this.LastTimeLuckDate = this.readData.LastTimeLuckDate;
            this.EveryDayRewardsArray = this.readData.EveryDayRewardsArray.split('_');
            this.TerritoryStateArray = this.readData.TerritoryStateArray.split('_');
            //面板状态
            this.BuildingStateArray = this.readData.BuildingStateArray.split('_');
            this.BuildingLockStateArray = this.readData.BuildingLockStateArray.split('_');
            this.BuildingNumArray = this.readData.BuildingNumArray.split('_');
            this.DiamondNumArray = this.readData.DiamondNumArray.split('_');
            this.FoodTradeState = this.readData.FoodTradeState;
            this.WoodTradeState = this.readData.WoodTradeState;
            this.MineralTradeState = this.readData.MineralTradeState;

            //工人工作信息
            this.CharacterInfoArray = this.readData.characterInfoArray;
            //道路数据
            this.GameData_highwayIndex = this.readData.highwayIndex;

            //建筑物数据
            this.GameData_buildings = this.readData.buildingsInfo;

            this.LotteryTimes = this.readData.LotteryTimes;
            //任务
            task.TaskIconCountClick = this.readData.TaskIconCountClick;
            //测试5W
            // this.PlusDiamond(50000);
        }
    },

    //GET / SET /Plus
    GetGameDate: function () {
        return this.GameDate;
    },
    SetGameDate: function (num) {
        this.GameDate = num;
    },
    PlusGameDate: function (num) {
        this.GameDate += num;
    },
    GetGolden: function () {
        return parseInt(this.Golden);
    },
    GetGoldenCallBack(_CallBack) {
        if (_CallBack)
            _CallBack({ resGolden: parseInt(this.Golden) });
    },
    SetGolden: function (Num) {
        let LastMoney = this.Golden;
        this.Golden = Num;
        let CurrentMoney = Num;
        this.ManageUI.getComponent('ManageUI').GoldenChangeCallBack(this.GetGolden(), LastMoney, CurrentMoney);
    },
    PlusGolden: function (Num) {
        if (this.Golden + Num < 0) {
            this.SetGolden(0);
        }
        else {
            this.SetGolden(this.Golden + Num);
        }
        // task.task50W();
    },
    GetDiamond: function () {
        return parseInt(this.Diamond);
    },
    SetDiamond: function (num) {
        let LastMoney = this.Diamond;
        this.Diamond = num;
        let CurrentMoney = num;
        this.ManageUI.getComponent('ManageUI').DiamondChangeCallBack(this.GetDiamond(), LastMoney, CurrentMoney);
    },
    PlusDiamond: function (num) {
        if (this.Diamond + num < 0) {
            this.SetDiamond(0);
        }
        else {
            this.SetDiamond(this.Diamond + num);
        }
    },
    GetWorkerLV: function () {
        return parseInt(this.WorkerLV);
    },
    SetWorkerLV: function (num) {
        this.WorkerLV = num;
    },
    PlusWorkerLV: function (num) {
        this.WorkerLV += num;
    },
    GetWorkerNum: function () {
        return parseInt(this.WorkerNum);
    },
    SetWorkerNum: function (num) {
        this.WorkerNum = num;
    },
    PlusWorkerNum: function (num) {
        this.WorkerNum += num;
    },
    GetLastTimeEveryDayRewardsDate: function () {
        return this.LastTimeEveryDayRewardsDate;
    },
    //获取转盘 时间
    GetLastTimeLuckDate: function () {
        return this.LastTimeLuckDate;
    },
    //设置转盘时间
    SetLastTimeLuckDate: function (DateString) {
        this.LastTimeLuckDate = DateString;
    },
    SetLastTimeEveryDayRewardsDate: function (DateString) {
        this.LastTimeEveryDayRewardsDate = DateString;
    },

    //工人信息数组
    GetWorkerCharacterInfoArray: function () {
        return this.CharacterInfoArray;
    },
    SetWorkerCharacterInfoArray: function (item) {
        this.CharacterInfoArray = item;
    },

    /*** */
    GetWorkerCapacity: function () {
        return parseInt((this.WorkerCapacity));
    },
    SetWorkerCapacity: function (num) {
        this.WorkerCapacity = num;
    },
    PlusWorkerCapacity: function (num) {
        this.WorkerCapacity += num;
    },
    GetTerritoryStateArray: function () {
        return this.TerritoryStateArray;
    },
    SetTerritoryStateArray: function (aTerritoryStateArray) {
        this.TerritoryStateArray = aTerritoryStateArray;
    },
    PlusTerritoryStateArray: function (Item) {
        this.TerritoryStateArray.push(Item);
    },
    GetBuildingStateArray: function () {
        return this.BuildingStateArray;
    },
    SetBuildingStateArray: function (aBuildingStateArray) {
        this.BuildingStateArray = aBuildingStateArray;
    },
    PlusBuildingStateArray: function (Item) {
        this.BuildingStateArray.push(Item);
    },
    GetBuildingLockStateArray: function () {
        return this.BuildingLockStateArray;
    },
    SetBuildingLockStateArray: function (aArray) {
        this.BuildingLockStateArray = aArray;
    },
    PlusBuildingLockStateArray: function (Item) {
        this.BuildingLockStateArray.push(Item);
    },

    GetBuildingNumArray: function () {
        return this.BuildingNumArray;
    },
    SetBuildingNumArray: function (aBuildingNumArray) {
        this.BuildingNumArray = aBuildingNumArray;
    },
    PlusBuildingNumArray: function (Item) {
        this.BuildingNumArray.push(Item);
    },
    //操作钻石数据
    GetDiamondNumArray: function () {
        return this.DiamondNumArray;
    },
    SetDiamondNumArray: function (aDiamondNumArray) {
        this.DiamondNumArray = aDiamondNumArray;
    },
    GetEveryDayRewardsArray: function () {
        return this.EveryDayRewardsArray;
    },
    SetEveryDayRewardsArray: function (aArray) {
        this.EveryDayRewardsArray = aArray;
    },
    PlusEveryDayRewardsArray: function (Item) {
        this.EveryDayRewardsArray.push(Item);
    },
    GetFoodTradeState: function () {
        return parseInt((this.FoodTradeState));
    },
    SetFoodTradeState: function (num) {
        this.FoodTradeState = num;
    },
    PlusFoodTradeState: function (num) {
        this.FoodTradeState += num;
    },
    GetWoodTradeState: function () {
        return parseInt((this.WoodTradeState));
    },
    SetWoodTradeState: function (num) {
        this.WoodTradeState = num;
    },
    PlusWoodTradeState: function (num) {
        this.WoodTradeState += num;
    },
    GetMineralTradeState: function () {
        return parseInt((this.MineralTradeState));
    },
    SetMineralTradeState: function (num) {
        this.MineralTradeState = num;
    },
    PlusMineralTradeState: function (num) {
        this.MineralTradeState += num;
    },
    GetLotteryTimes: function () {
        return parseInt((this.LotteryTimes));
    },
    SetLotteryTimes: function (num) {
        this.LotteryTimes = num;
    },
    PlusLotteryTimes: function (num) {
        this.LotteryTimes += num;
    },


    //初始化道路
    onSpawnHighway() {
        // 获取InitPoint层
        let InitPos = this._tiledMap.getLayer('InitPoint');
        InitPos.enabled = false;

        //    //道路数据
        //    highwayIndex: this.GameData_highwayIndex,
        //    allHighwayStylesAndIndex: GlobalD.game.AllHighwayStylesAndIndex,
        // var highwayTemp = cc.sys.localStorage.getItem('highway');

        //创建公路数据
        if (this.readData) {
            //保存到内存中
            this.GameData_highwayIndex = this.readData.highwayIndex;
            //先赋值道路的对象数组
            let _AllHighwayAIndex = GlobalD.game.AllHighwayStylesAndIndex = this.readData.allHighwayStylesAndIndex;

            //获取最后建造公路的层级
            this.HighwayLayer = this._tiledMap.getLayer('Highway');
            for (let i = 0; i < _AllHighwayAIndex.length; i++) {
                let highwayTemp = cc.instantiate(this.HighWayPrefabs);
                highwayTemp.parent = this.HighwayLayer.node;
                let tiledTile = highwayTemp.addComponent('TiledTile');
                let _tiledPos = GlobalD.TiledMap.analyticalIndexData(_AllHighwayAIndex[i].highwayInfoIndex);
                tiledTile.x = _tiledPos.x;
                tiledTile.y = _tiledPos.y;
                //地图设置可行走区域公路设置
                AStar.setMapSolid(_tiledPos.x, _tiledPos.y, 0);


                // _buildId ==0 是公路
                let _buildId = 0;
                let occupyTemp = cc.v2(_buildId, _AllHighwayAIndex[i].highwayInfoIndex);
                GlobalD.game.OccupyArray.push(occupyTemp);

                highwayTemp.getComponent('HighwayInfo').onChangeHighwayStyles(_AllHighwayAIndex[i].highwayInfoType);

            }
        } else {
            //如果用户没有存储数据
            //根据InitPoint 的数据，创建初始化的地图数据 的初始化数据

            this.HighwayLayer = this._tiledMap.getLayer('Highway');
            for (var i = 0; i < 32; i++) {
                //去除中间两条路
                if (i == 16 || i == 17) continue;
                for (var j = 0; j < 32; j++) {
                    let tilesPos = cc.v2(i, j);

                    if (InitPos.getTileGIDAt(tilesPos)) {


                        let index = GlobalD.TiledMap.getIndex(tilesPos);
                        this.GameData_highwayIndex.push(index);

                        let highwayTemp = cc.instantiate(this.HighWayPrefabs);
                        highwayTemp.parent = this.HighwayLayer.node;
                        let tiledTile = highwayTemp.addComponent('TiledTile');
                        tiledTile.x = tilesPos.x;
                        tiledTile.y = tilesPos.y;
                        // cc.log('onSpawnHighway2');
                        //地图设置可行走区域公路设置
                        AStar.setMapSolid(tilesPos.x, tilesPos.y, 0);
                        // _buildId ==0 是公路
                        let _buildId = 0;
                        let occupyTemp = cc.v2(_buildId, index);
                        GlobalD.game.OccupyArray.push(occupyTemp);

                        let tile = InitPos.getTiledTileAt(tilesPos.x, tilesPos.y, true);

                        let _MoveType = reGameStates.HighwayType.moveX;
                        // if (tile.gid == 15) {
                        //     _MoveType = reGameStates.HighwayType.moveX;
                        // } else 
                        if (tile.gid == 16) {
                            _MoveType = reGameStates.HighwayType.moveY;
                        } else if (tile.gid == 11) {
                            _MoveType = reGameStates.HighwayType.ZebraCrossingX;
                        } else if (tile.gid == 12) {
                            _MoveType = reGameStates.HighwayType.ZebraCrossingY;
                        }
                        // return;
                        //更换公路样式
                        GlobalD.game.onCreateDifferentRoadStyles({
                            _buildId: _buildId,
                            _highwayType: _MoveType,
                            _roadIndex: index,
                            _hightwayNode: highwayTemp
                        });
                    }
                }
            }
        }
        //外面的两条路
        let initRoad = this._tiledMap.getLayer('Road');
        initRoad.enabled = false;
        for (var i = 16; i < 18; i++) {
            for (var j = 0; j < 32; j++) {
                let tilesPos = cc.v2(i, j);
                // cc.log('road tilesPos',tilesPos)
                if (initRoad.getTileGIDAt(tilesPos)) {
                    let index = GlobalD.TiledMap.getIndex(tilesPos);
                    this.GameData_highwayIndex.push(index);
                    let highwayTemp = cc.instantiate(this.HighWayPrefabs);
                    highwayTemp.parent = this.HighwayLayer.node;
                    let tiledTile = highwayTemp.addComponent('TiledTile');
                    tiledTile.x = tilesPos.x;
                    tiledTile.y = tilesPos.y;
                    // cc.log('initRoad');
                    //地图设置可行走区域公路设置
                    AStar.setMapSolid(tilesPos.x, tilesPos.y, 0);
                    let _buildId = 0;
                    let occupyTemp = cc.v2(_buildId, index);
                    GlobalD.game.OccupyArray.push(occupyTemp);
                    //更换公路样式
                    // if (j >= 25 && j <= 27 || j >= 19 && j <= 21 || j >= 9 && j <= 11)
                    //     highwayTemp.getComponent('HighwayInfo').onChangeHighwayStyles(reGameStates.HighwayType.none);
                    // else
                    //     highwayTemp.getComponent('HighwayInfo').onChangeHighwayStyles(reGameStates.HighwayType.moveY);

                }
            }
        }
    },

    //清除所有的数据
    onClearAllData() {
        this.unschedule(this.AutoSaveData);
        //任务索引
        cc.sys.localStorage.removeItem('userdata');

        //跳回登录场景
        // cc.director.loadScene('Login');
    },
    //保存数据请求
    pushData: function () {
        // cc.log(this.EveryDayRewardsArray);
        var datas = {
            version: this.GameVersion,
            BFirstLoadGame: 1,//只要push数据，就证明已经开始第一次游戏了
            //时间
            GameYear: this.GameYear,
            GameMonth: this.GameMonth,
            GameDay: this.GameDay,

            Golden: this.Golden,
            Diamond: this.Diamond,
            WorkerLV: this.WorkerLV,
            WorkerNum: this.WorkerNum,
            WorkerCapacity: this.WorkerCapacity,
            GameDate: this.GameDate,
            LastTimeEveryDayRewardsDate: this.LastTimeEveryDayRewardsDate,
            LastTimeLuckDate: this.LastTimeLuckDate,
            EveryDayRewardsArray: this.EveryDayRewardsArray.join('_'),
            TerritoryStateArray: this.TerritoryStateArray.join('_'),
            //面板状态
            BuildingStateArray: this.BuildingStateArray.join('_'),
            BuildingLockStateArray: this.BuildingLockStateArray.join('_'),
            BuildingNumArray: this.BuildingNumArray.join('_'),
            DiamondNumArray: this.DiamondNumArray.join('_'),
            FoodTradeState: this.FoodTradeState,
            WoodTradeState: this.WoodTradeState,
            MineralTradeState: this.MineralTradeState,

            LotteryTimes: this.LotteryTimes,

            //工人工作信息
            characterInfoArray: this.CharacterInfoArray,
            //道路数据
            highwayIndex: this.GameData_highwayIndex,
            allHighwayStylesAndIndex: GlobalD.game.AllHighwayStylesAndIndex,
            //建筑物数据
            buildingsInfo: this.GameData_buildings,
            //任务
            TaskIconCountClick: task.TaskIconCountClick
        }
        var data = [];
        data["openid"] = userData.openId;
        data["userdata"] = JSON.stringify(datas);

        //保存用户数据到本地
        cc.sys.localStorage.setItem('userdata', JSON.stringify(datas));

        return;
        // console.log("提交的数据是", datas);
        httpUtils.Post(httpUtils.setUserData, data, function (resData) {
            let _userData = resData.data.userdata;
            let _JsonData = JSON.parse(_userData);
            // console.log("push成功", resData, _JsonData);

            if (resData.code == 0) {
                // this.getText.string = data.data.userdata;
            }

        }.bind(this), function (resData) {
            // console.log("失败", resData);
        }.bind(this));
    },

});
