// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html
import { ryw_Event } from "../../FrameWork/Event/EventEnum";
import EventMgr from "../../FrameWork/Event/EventMgr";
import User from "../../FrameWork/User/User";
import AppPlatform from "../../FrameWork/Util/AppPlatform";
import Common5 from "../../Platform/th/Common5";
import CommonDefine from "../../Platform/th/CommonDefine";
import TTAPI from "../../Platform/tt/TTAPI";
import ChaoCai from "../GameMethodRes/ChaoCai/ChaoCai";
import YiMaJiang from "../GameMethodRes/YiMaJiang/YiMaJiang";
import JuQingManager from "../JuQingChat/JuQingManager";
import TaskManager, { MainTaskIdEnum } from "../JuQingChat/TaskManager";
import BagManager from "../Manager/BagManager";
import DiaoLuoManager1 from "../Manager/DiaoLuoManager1";
import FangChanManager from "../Manager/FangChanManager";
import InterfaceManager from "../Manager/InterfaceManager";
import LevelUpManager from "../Manager/LevelUpManager";
import MiShuManager from "../Manager/MiShuManager";
import ShipuManager from "../Manager/ShipuManager";
import TanWeiManager from "../Manager/TanWeiManager";
import UserManager from "../Manager/UserManager";
import ZiChanManager from "../Manager/ZiChanManager";

import PrefabManage, { GameType } from "../PrefabManager/PrefabManage";

import StockManager from "../stock/StockManager";

export let AutoShouYiConfig = [
    //城镇
    { money: 200, moneyNode: '收益_下水道', gameTittle: '下水道' },
    { money: 500, moneyNode: '收益_快递站', gameTittle: '快递站' },
    { money: 800, moneyNode: '收益_养殖场', gameTittle: '养殖场' },
    { money: 0, moneyNode: '收益_美食街', gameTittle: '美食街' },
    { money: 2000, moneyNode: '收益_海钓场', gameTittle: '海钓场' },
    { money: 100000, moneyNode: '收益_渔船', gameTittle: '渔船' }, //5
    //市区
    { money: 0, moneyNode: '收益_海洋馆', gameTittle: '海洋馆' },
    { money: 0, moneyNode: '收益_酒楼', gameTittle: '酒楼' },
    { money: 0, moneyNode: '收益_加工厂', gameTittle: '加工厂' },
    { money: 0, moneyNode: '收益_网红基地', gameTittle: '网红基地' },
    { money: 50000, moneyNode: '收益_张氏集团', gameTittle: '张氏集团' },
    { money: 80000, moneyNode: '收益_冶炼厂', gameTittle: '冶炼厂' }, //11
    //隐世
    { money: 120000, moneyNode: '收益_茶场', gameTittle: '茶场' },
    { money: 150000, moneyNode: '收益_礁石区', gameTittle: '礁石区' },
    { money: 180000, moneyNode: '收益_奇珍园', gameTittle: '奇珍园' },
]


const { ccclass, property } = cc._decorator;

@ccclass
export default class MainScene extends cc.Component {



    // LIFE-CYCLE CALLBACKS:
    hour: number = 0;
    min: number = 0;
    saveTime = 0
    time_ = 0
    qipaoTime = 0
    isShowCFHMFail: boolean = false
    maxTime = 3
    isNewDay = false
    autoTime: number = 0;
    onLoad() {
        // let zhuzis = [3730, 3731, 3732, 3733, 3734, 3735, 3736]
        // zhuzis.forEach(element => {
        // BagManager.subBagList(element)  
        // });
        let myWeekDayTime = User.getStatistics("myWeekDayTime")
        if (myWeekDayTime == 0) {
            let time = Date.now() + 7 * 24 * 60 * 60 * 1000
            User.setStatistics("myWeekDayTime", time)
        }
    }

    enterGame() {
        // PrefabManage.loadPrefabByType(GameType.FoShanDianHan)
        // PrefabManage.loadPrefabByType(GameType.DH_41)
        // return
        // PrefabManage.loadPrefabByType(GameType.MainHall, null, ()=>{
        //     this.getServerData()
        // })
        // return
        User.setFirstStepIndex(6000000)
        // TaskManager.setCurTask(MainTaskIdEnum.MainTask_528)
        // User.setCurGameLevelIndex(1)
        // for (let i = 0; i < 18; i++) {
        //     MiShuManager.setMishuLock(i, true, false)
        // }

        // User.setFirstStepIndex(1)
        // let zhuzis = [3709, 3710, 3711, 3712, 3713, 3714]
        // zhuzis.forEach(element => {
        //     BagManager.addBagList({ goodId: element, goodNum: 1 })
        // });
        // PrefabManage.loadPrefabByType(GameType.DH_18)
        // return
        // TaskManager.setCurTask(MainTaskIdEnum.MainTask_503)
        // User.setFirstStepIndex(10000)
        // User.setMishuList([])
        // MiShuManager.setMishuLock(0, true)
        // User.setCurChallengeId(0)
        // BagManager.subBagList(3737, 1)
        // BagManager.subBagList(3703, 1)
        // User.setFirstStepIndex(100)
        // User.setChuShiXieHuiLevel(0)
        // let ziChanData = User.getZiChanData()
        // ziChanData.unLockNum[2] = 0
        // JuQingManager.unLockNewJuQing('WX_5')
        // User.setZiChanData(ziChanData)
        // User.setChuShiXieHuiLevel([-1, -1, -1, -1, -1, -1, -1, -1])
        // User.setCurChallengeId(19)
        // User.setChengJiuReward([0, 0, 0, 0, 0, 0, 0, 0, 0])
        // cc.sys.localStorage.removeItem("货源引导")
        let taskArray = User.getCurTaskId()
        let taskId = taskArray[0]
        let isFinish = taskArray[1]
        if (User.getFirstStepIndex() == 0 || User.getFirstStepIndex() == 1 || User.getFirstStepIndex() == 2) {
            // PrefabManage.loadPrefabByType(GameType.DH_3, null, () => {
            //     this.getServerData()
            // })
            let self = this
            let level = ZYSDK.ZYSDK.getLevel()
            try {
                // 通过调用.then()方法来获取Promise对象的值
                level.then(value => {
                    console.log('Promise对象的值为', value);
                    let level = value
                    if (level) {
                        let def = level[0]
                        console.error(def, level, 'def++++++++++++===')
                        if (def == 1) {
                            PrefabManage.loadPrefabByType(GameType.DH_3, null, () => {
                                this.getServerData()
                            })
                        } else if (def == 2) {
                            PrefabManage.loadPrefabByType(GameType.DH_1, null, () => {
                                self.getServerData()
                            })
                        } else {
                            PrefabManage.loadPrefabByType(GameType.DH_3, null, () => {
                                this.getServerData()
                            })
                        }
                    } else {
                        console.log('正常新用户++++++++++++===')
                        PrefabManage.loadPrefabByType(GameType.DH_3, null, () => {
                            this.getServerData()
                        })
                    }

                }).catch(error => {
                    console.error('发生错误', error);
                    PrefabManage.loadPrefabByType(GameType.DH_3, null, () => {
                        this.getServerData()
                    })
                });
            }
            catch {
                console.error('发生错误2');
                PrefabManage.loadPrefabByType(GameType.DH_3, null, () => {
                    this.getServerData()
                })
            }
        }
        // else if (User.getFirstStepIndex() == 1) {
        //     let self = this
        //     PrefabManage.loadPrefabByType(GameType.DH_2, null, () => {
        //         this.getServerData()
        //     })
        // } else if (User.getFirstStepIndex() == 2) {
        //     let self = this
        //     PrefabManage.loadPrefabByType(GameType.DH_3, null, () => {
        //         this.getServerData()
        //     })
        // } 
        else if (taskId == MainTaskIdEnum.MainTask_501) {
            PrefabManage.loadPrefabByType(GameType.DH_4, null, () => {
                this.getServerData()
            })
        } else if (taskId == MainTaskIdEnum.MainTask_502) {
            PrefabManage.loadPrefabByType(GameType.DH_5, null, () => {
                this.getServerData()
            })
        } else if (taskId == MainTaskIdEnum.MainTask_503 && User.getFirstStepIndex() == 5) {
            PrefabManage.loadPrefabByType(GameType.DH_6, null, () => {
                this.getServerData()
            })
        } else {
            let time0 = Common5.lixianTime / 1000
            let time1 = time0 / 60
            if (time1 >= 10 && User.getRoomGoodStatus() > 5) {
                PrefabManage.loadPrefabByType(GameType.lixianReward, null, (prefab) => {
                    prefab.zIndex = 9
                })
            }


            if (taskId == 0 || taskId == MainTaskIdEnum.MainTask_501) {
                PrefabManage.loadPrefabByType(GameType.MainHall, null, () => {
                    this.getServerData()
                })
            } else {

                PrefabManage.loadPrefabByType(GameType.MainHall, null, () => {
                    this.getServerData()
                })
            }



        }

    }
    start() {
        // PrefabManage.reloadPrefab = new Map()
        // InterfaceManager.initManager()


        // this.scheduleOnce(()=>{
        //     PrefabManage.loadPrefabByType(GameType.WZ_firstLevelSelectView)
        //     // PrefabManage.loadPrefabByType(GameType.ChaoCai, null, (prefabNode) => {
        //     //     prefabNode.getComponent(ChaoCai).initView(1);
        //     // })
        // },3)
        // return
        PrefabManage.reloadPrefab = new Map()
        let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id
        if (mainId != MainTaskIdEnum.MainTask_None && mainId) {
            Common5.TaskBtnState = '任务助手c'
        }

        EventMgr.onEvent_custom(ryw_Event.updateMainTask, (data) => {
            console.log("更新任务+", data)
            let customTaskInfo = data.taskInfo
            if (customTaskInfo && Object.keys(customTaskInfo).length > 0 && customTaskInfo.Id != 0) {
                PrefabManage.loadPrefabByType(GameType.TaskInfoNode, this.node)
            } else {
                //PrefabManage.showTextTips('当前无任务')
            }
        }, this)

        EventMgr.onEvent_custom(ryw_Event.addDay, () => {
            StockManager.refreshAllStocksData(User.getDay(), false)
        }, this)

        if (User.getDay() == 1) {
            StockManager.refreshAllStocksData(1, true)
        }


        this.enterGame()
        this.oldLoad();


        InterfaceManager.initManager()
        AppPlatform.PlatformOnHide(() => {
            Common5.stopMusic()
            User.setLastOnlineTimestamp(new Date().getTime());
            User.saveUserGameData()
            CommonDefine.saveData()
        })


        AppPlatform.PlatformOnShow((res) => {
            console.log('小游戏隐藏PlatformOnShow')
            this.checkAddDesk()
            if (AppPlatform.is_TT_GAME_custom()) {
                console.log(res, "从侧边栏进入游戏 MainScene");
                if (res.launch_from == 'homepage' && res.location == 'sidebar_card') {
                    Common5.isCeBianLanEnter = true
                    EventMgr.emitEvent_custom(ryw_Event.CheckIsEnterFromCeBianLan)
                }
            }
            Common5.playRemoteAudioMusic('sound/common/背景音')
            // if (Common5.isHaveUserName == false) {
            //     if (User.getUserName() == '') {
            //         TTAPI.ttLogin_custom(() => { }, () => { })
            //     }

            // }
        })
        // this.tanchuangBoxJQ()

        this.openBoxTanchuan()
        EventMgr.onEvent_custom(ryw_Event.boxTanChuanEvent, () => {
            this.openBoxTanchuan()
        }, this);

        //PrefabManage.preloadAllPrefab()
        this.checkAddDesk()

        EventMgr.onEvent_custom(ryw_Event.ExitBtnEvent, (prefabName) => {
            console.log(prefabName, '退出prefabName++++===')
            if (prefabName == '') {
                return
            }
            let prefaburl = PrefabManage.getPrefabUrlByName(prefabName)
            if (prefaburl) {
                let prefab2 = Common5.prefabMap.get(prefaburl)
                //cc.assetManager.releaseAsset(prefab2)
                cc.loader.release(prefab2)
                console.error('释放资源——++++++++++===,', prefaburl)
            } else {
                let config = Common5.gameConfig.zmGameConfig
                if (config) {
                    let zmGameConfig = Common5.gameConfig.zmGameConfig
                    if (zmGameConfig) {
                        let deleteUrl = null
                        for (var i = 0; i < zmGameConfig.length; i++) {
                            if (zmGameConfig[i].url && zmGameConfig[i].url.includes(prefabName)) {
                                deleteUrl = zmGameConfig[i].url
                                break
                            }
                        }

                        if (deleteUrl) {
                            let prefab2 = Common5.prefabMap.get(deleteUrl)
                            //cc.assetManager.releaseAsset(prefab2)
                            cc.loader.release(prefab2)
                            console.error('释放文字资源——++++++++++===,', deleteUrl)
                        }
                    }
                }
            }
        }, this)

        cc.loader.loadRes('Json/WenZiGameConfig/WZGameConfig.json', function (err, gameconfig) {
            if (err) {
                console.log(err);
                return;
            }
            Common5.gameConfig = gameconfig.json;
        });
    }

    checkAddDesk() {
        let launchScene_custom = AppPlatform.getLaunchOptionsSync_custom().scene;
        let isGetReward = User.getDeskReward()
        //021020,101020,181020,141020,991020

        if (!isGetReward) {
            if (launchScene_custom == '021020' || launchScene_custom == '101020' || launchScene_custom == '181020'
                || launchScene_custom == '141020' || launchScene_custom == '991020') {
                User.setAddDesk(true)
                PrefabManage.loadPrefabByType(GameType.AddDesk)
            }

        }
    }
    oldLoad() {
        this.hour = User.getTimeHour();
        this.min = User.getTimeMin();


        UserManager.onlineTime = User.getOnlineTime()

        this.schedule(() => {
            if (Common5.isVideoAdStopTime) {
                return
            }

            if (UserManager.onlineTime > 30 * 60) {

            } else {
                UserManager.onlineTime++
                User.setOnlineTime(UserManager.onlineTime)
                //EventMgr.emitEvent_custom(ryw_Event.onlimeTimeRun);
            }

            this.min += 5;
            if (this.min >= 60) {
                this.hour += 1;
                this.min = 0;
                //EventMgr.emitEvent_custom(ryw_Event.updateDayOrNight);
            }

            if (Common5.saveTime > 0) {
                Common5.saveTime--
                if (Common5.saveTime < 0) {
                    Common5.saveTime = 0
                }
            }
            if (this.hour >= 24) {
                console.log('又是一天')
                this.hour = 0;
                this.refreshData()
                this.saveData()
                if (!this.isNewDay) {
                    this.isNewDay = true
                }
                UserManager.setCurDay(UserManager.getCurDay() + 1);
                EventMgr.emitEvent_custom(ryw_Event.addDay);
            }
            this.chanye_update();
            this.updateAddShouYi()



            User.setTime(this.hour, this.min);

            this.saveTime++
            if (this.saveTime >= this.maxTime) {
                User.saveUserGameData()
                this.saveTime = 0
            }
        }, 1)
    }
    testSaveBtn() {
        UserManager.sendDataToUrl()
    }
    testReadBtn() {

    }

    //秒赚
    updateAddShouYi() {
        let allshouyi1 = MiShuManager.getAllIncomeMishu()

        // let allshouyi2 = MiShuManager.getAllIncomeDuiyou()
        // let allNum = allshouyi1 + allshouyi2
        let allNum = allshouyi1


        let beishuSP = ShipuManager.getAllShipuInCome()
        // let beishuTW = TanWeiManager.getAllShipuInCome()
        let chenghaoInCome = LevelUpManager.getAllChengHaoinCome() //称号倍数

        let zichan = ZiChanManager.getZiChanBeiShu()
        if (allNum * beishuSP * chenghaoInCome * zichan <= 0) {

        } else {
            let money = allNum * beishuSP * chenghaoInCome * zichan
            EventMgr.emitEvent_custom(ryw_Event.updateMiaoZhuan, money);

            UserManager.addMoney2(allNum * beishuSP * chenghaoInCome * zichan)

        }
    }


    saveData() {
        if (this.isNewDay) {
            CommonDefine.saveData()
        }
    }

    getServerData() {
        // let comSuccesscall = (GameData) => {
        //     this.scheduleOnce(() => {
        //         console.warn('getServerData=====', GameData)
        //         cc.director.loadScene("MainScene");
        //     }, 0.5)
        // }
        CommonDefine.getServerData()
        // if (!AppPlatform.is_TT_GAME_custom()) {
        //     //登录获取
        // } else {
        //     let userID = User.getUserId()
        //     console.error(userID, '读取数据userID')

        //     if (userID == '') {
        //         //读取数据

        //         PrefabManage.showTextTips('存档数据拉取中')
        //         PrefabManage.showLoading2(true)
        //         let onFail = () => {
        //             PrefabManage.showLoading2(false)
        //         }
        //         let onSuccess = (response) => {
        //             console.log(response, '登录成功获取userid++1+=====')
        //             if (response && response.msg == 'OK') {
        //                 User.setUserId(response.openid)
        //                 User.setFirstIn(false);
        //                 console.warn('获取服务器数据完成')
        //                 let comSuccesscall = (GameData) => {


        //                     UserManager.readDataByUrl(GameData)

        //                 }

        //                 let comFailcall = () => {
        //                     PrefabManage.showLoading2(false)
        //                 }
        //                 // CommonDefine.getServerData(comSuccesscall, comFailcall)
        //                 CommonDefine.getServerData(comSuccesscall)
        //             } else {
        //                 PrefabManage.showLoading2(false)
        //             }
        //         }

        //         let appsuccesscall = (code) => {
        //             console.error(code, '没有code获取code22')
        //             CommonDefine.getLoginInfo(code, onFail, onSuccess)
        //         }
        //         let appfailcall = () => {
        //             console.error('appfailcall')
        //             PrefabManage.showLoading2(false)
        //         }
        //         AppPlatform.loginPlatform_custom(appsuccesscall, appfailcall)
        //         console.error('读取数据22')
        //     } else {
        //         console.log('不需要读取数据')
        //     }
        // }
    }


    chanye_update() {
        //黄金渔夫倒计时
        if (User.getHuangjinGouTime() > 0) {
            User.updateHuangjinGouTime()
        }
        //自动点击
        let autoClickTime = User.getAutoClickTime()
        let shouyiFanbeiTime = User.getShouyiFanbeiTime()

        if (autoClickTime > 0) {
            if (autoClickTime > 0) {
                autoClickTime--
                User.setAutoClickTime(autoClickTime)
            }

            //收益翻倍
            EventMgr.emitEvent_custom(ryw_Event.autoTimeEvent);
        }

        if (shouyiFanbeiTime > 0) {
            if (shouyiFanbeiTime > 0) {
                shouyiFanbeiTime--
                if (shouyiFanbeiTime <= 0) {
                    this.showBoxTips()
                    User.setShouyiFanbeiNum(1)
                    //收益刷新
                    EventMgr.emitEvent_custom(ryw_Event.MultipleIncomeEvent)
                }
                User.setShouyiFanbeiTime(shouyiFanbeiTime)
            }
            //收益翻倍
            EventMgr.emitEvent_custom(ryw_Event.autoTimeEvent);
        }

        FangChanManager.refreshFangChanIncome()
    }

    showBoxTips() {
        let num = User.getShouyiFanbeiNum()
        PrefabManage.loadPrefabByType(GameType.ShouYiEndTip, null, (prefab) => {
            prefab.getComponent('BoxTipScript').setViewData(2, `${num}倍收益已结束,您可以选择延时五分钟或者重新抽取`, () => {
                PrefabManage.loadPrefabByType(GameType.MultipleIncome)
            }, () => {
                Common5.ReportDY("inLevel", "收益翻倍-AD-倒计时延时" + num);
                User.setShouyiFanbeiNum(num)
                let time = User.getShouyiFanbeiTime()
                User.setShouyiFanbeiTime(time + 5 * 60)
                //收益刷新
                EventMgr.emitEvent_custom(ryw_Event.MultipleIncomeEvent)
            })
            prefab.getComponent('BoxTipScript').setBtnStr('重新抽取', '延 时')
            prefab.getComponent('BoxTipScript').setCloseBtnView(true)
        })
    }


    protected update(dt: number): void {
        let autoClickTime = User.getAutoClickTime()
        if (autoClickTime > 0) {
            this.autoTime += dt
            if (this.autoTime >= 0.24) {
                this.autoTime = 0
                //收益翻倍点击动作
                EventMgr.emitEvent_custom(ryw_Event.autoTimeEvent);
            }
        }

    }

    refreshData() {

    }

    openBoxTanchuan() {

        let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id




    }


    tanchuangBoxJQ() {
        let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id
        if (mainId == MainTaskIdEnum.MainTask_520) {
            PrefabManage.loadPrefabByType(GameType.BoxTipNode, null, (prefab) => {
                prefab.getComponent('BoxTipScript').setViewData(1, '到废弃基地探寻真相', () => {
                    PrefabManage.loadPrefabByType(GameType.FeiQiJiDi1)
                })
                prefab.getComponent('BoxTipScript').setBtnStr('确定')
                prefab.getComponent('BoxTipScript').setCloseBtnView(false)
                prefab.zIndex = 99
            })
        } else if (mainId == MainTaskIdEnum.MainTask_534) {
            PrefabManage.loadPrefabByType(GameType.BoxTipNode, null, (prefab) => {
                prefab.getComponent('BoxTipScript').setViewData(1, '到异能研究所进行接收', () => {
                    PrefabManage.loadPrefabByType(GameType.YanJiuSuo)
                })
                prefab.getComponent('BoxTipScript').setBtnStr('确定')
                prefab.getComponent('BoxTipScript').setCloseBtnView(false)
                prefab.zIndex = 99
            })
        } else if (mainId == MainTaskIdEnum.MainTask_536) {
            // PrefabManage.loadPrefabByType(GameType.BoxTipNode, null, (prefab)=>{
            //     prefab.getComponent('BoxTipScript').setViewData(1,'回家融合五行源石', ()=>{
            //         PrefabManage.loadPrefabByType(GameType.WuXingYuanShi)
            //     })
            //     prefab.getComponent('BoxTipScript').setBtnStr('确定')
            //     prefab.getComponent('BoxTipScript').setCloseBtnView(false)
            //     prefab.zIndex = 99
            // })
        }



    }


    ceshiJuQing() {
        // const target = event.target;
        // target.active = false;

        // let UserHeTong = User.getUserHeTong()
        // UserHeTong.buyJiTuan = true
        // User.setUserHeTong(UserHeTong)
        // PrefabManage.addUnlockGameName(GameType.ChaChang)
        // PrefabManage.addUnlockGameNameSG(GameType.HuangJinYuFu)
        // User.setXiaoYanZhanChangStatus(5)
        // User.setDaoyeIndex(1)

        User.setFirstStepIndex(9)
        User.setMyLevel(500)
        User.setRoomGoodStatus(16)
        User.setCurChallengeId(25)
        TaskManager.setCurTask(MainTaskIdEnum.MainTask_515)



    }
}