// 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 Common5 from "../../Platform/th/Common5";
import List from "../../Platform/th/List";
import UiBase from "../GameBase/UiBase";
import TaskManager, { MainTaskIdEnum } from "../JuQingChat/TaskManager";
import LevelUpManager from "../Manager/LevelUpManager";
import MiShuManager from "../Manager/MiShuManager";
import ShipuManager from "../Manager/ShipuManager";
import ZiChanManager from "../Manager/ZiChanManager";
import NewGuideScript from "../NewGuide/NewGuideScript";
import PrefabManage, { GameType } from "../PrefabManager/PrefabManage";
import MishuItem from "./MishuItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MishuGame extends UiBase {

    @property(cc.Label)
    label: cc.Label = null;

    @property(List)
    listM: List = null; //秘书

    @property(List)
    listD: List = null; //队友

    // LIFE-CYCLE CALLBACKS:
    @property(cc.Label)
    allShouyiMS: cc.Label = null;
    @property(cc.Label)
    allShouyiDY: cc.Label = null;

    // onLoad () {}
    dataListD = []
    dataListM = []

    dialogIndex: number = 0;
    duihuakuang1: cc.Node;
    duihuakuang2: cc.Node;
    selectIndex: number = 0;
    chatConfig = [
        { effectUrl: 'DH/MainHall/sound/招募助理可以增加秒赚收益哦', delayTime: 2.35, str: '招募助理可以增加秒赚收益哦', posi: 'qipao2' },
        { effectUrl: 'DH/MainHall/sound/等级越高秒赚收益越高,升级助理到10级可以招募下一个助理哦', delayTime: 5.3, str: '等级越高秒赚收益越高,升级助理到10级可以招募下一个助理哦', posi: 'qipao2' },
        { effectUrl: 'DH/MainHall/sound/等级越高,增加的秒赚收益越多哦!', delayTime: 3, str: '等级越高,增加的秒赚收益越多哦!', posi: 'qipao2' },
        { effectUrl: 'DH/MainHall/sound/哥哥,将助理升级到20级后可以获得点击收益加成哦!', delayTime: 3, str: '哥哥,将助理升级到20级后可以获得点击收益加成哦!', posi: 'qipao2' },
    ]

    start() {
        EventMgr.onEvent_custom(ryw_Event.changeScene, () => {
            console.log('changeScene++=MishuGame')
            this.node.removeFromParent()
            this.node.destroy()
        }, this)

        MiShuManager.initManager()
        this.scheduleOnce(() => {
            this.setListM()
        }, 0.1)

        this.refreshShouyi()
        EventMgr.onEvent_custom(ryw_Event.mishuLevelUp, () => {
            this.refreshShouyi()
            this.checkDuiyouPoint()

            let index = User.getFirstStepIndex()
            if (index == 11) {
                // this.showQiPao(this.chatConfig[2])
                User.setFirstStepIndex(12)
            }
            this.refreshUpNum()
        }, this)


        EventMgr.onEvent_custom(ryw_Event.mishuLock, () => {
            this.refreshShouyi()
            this.checkDuiyouPoint()


            this.refreshUpNum()
        }, this)

        this.scheduleOnce(() => {
            PrefabManage.preloadPrefabByType(GameType.MishuReward)
        }, 1.0)

        this.checkFinishTask()
        EventMgr.onEvent_custom(ryw_Event.exitMishuReward, () => {
            this.checkFinishTask()
            let index = User.getFirstStepIndex()
            if (index == 10) {
                User.setFirstStepIndex(11)
                let nodeArray = [this.node.getChildByName('guideBtn')]
                this.guideView(nodeArray, false, 0)
                this.showQiPao(this.chatConfig[1])
                Common5.ReportDY("inLevel", "任务" + TaskManager.getCurUnLockMainTaskId() + '-引导升级秘书');
            }
        }, this)

        let index = User.getFirstStepIndex()
        let isNeedGuide = cc.sys.localStorage.getItem("首次非引导主动进秘书界面") ?? 0
        if (index == 10) {
            Common5.ReportDY("inLevel", "任务" + TaskManager.getCurUnLockMainTaskId() + '-引导招募秘书');
            let nodeArray = [this.node.getChildByName('guideBtn')]
            this.guideView(nodeArray, false, 0)
            this.showQiPao(this.chatConfig[0])
        } else if (!isNeedGuide) {
            cc.sys.localStorage.setItem("首次非引导主动进秘书界面", '1')
            let nodeArray = [this.node.getChildByName('guideBtn')]
            this.guideView(nodeArray, false, 0)
            this.showQiPao(this.chatConfig[3])
        }
        // let nodeArray = [this.node.getChildByName('guideBtn')]
        // this.guideView(nodeArray, false, 150)
        // this.showQiPao(this.chatConfig[1])

        Common5.loadRemoteAudioEffect('sound/diandiandian/20级音效')

        this.checkDuiyouPoint()
        this.guideTask()
        this.refreshUpNum()

    }

    closeUiView(): void {
        // let zhuanpan = User.getZhuanPanFree()
        // if (zhuanpan) {
        //     PrefabManage.loadPrefabByType(GameType.MultipleIncome)
        // }
        User.setFirstStepIndex(1000)
        EventMgr.emitEvent_custom(ryw_Event.My_Guide)
        this.node.removeFromParent()
        this.node.destroy()

    }

    guideTask() {
        // let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        // let mainId = mainTaskInfo.Id
        // if (mainId == MainTaskIdEnum.MainTask_514 && User.getFirstStepIndex() == 7) {
        //     User.setFirstStepIndex(8)
        //     let node = this.node.getChildByName('guideBtn2')
        //     this.guideView([node], true, 100)
        // }
    }

    checkDuiyouPoint() {
        // let point = this.node.getChildByName('队友红点')
        // let haveRed = MiShuManager.getDuiyouRedPoint()
        // point.active = haveRed

    }

    guideView(nodeArray, isPlayAnim = true, opacity = -1) {
        PrefabManage.loadPrefabByType(GameType.GuideMskNode, this.node.getChildByName("蒙版父节点"), (prefab) => {
            //prefab.zIndex = 199
            if (!isPlayAnim) {
                prefab.getComponent(NewGuideScript).setCanPlayAnim(isPlayAnim)
            }
            if (opacity != -1) {
                prefab.getComponent(NewGuideScript).setOpacityMaskNode(opacity)

            }
            let guideNodeArray = nodeArray
            let firstNode = guideNodeArray.shift()
            prefab.getComponent(NewGuideScript).setBindNode(firstNode, guideNodeArray)


        })
    }


    checkFinishTask() {
        let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id
        // if (mainId == MainTaskIdEnum.MainTask_514) {
        //     let isLock = MiShuManager.getIsLock(18) //班的多
        //     if (isLock == false) {
        //         TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_514)
        //         TaskManager.setCurTask(MainTaskIdEnum.MainTask_515)
        //         PrefabManage.loadPrefabByType(GameType.BoxTipNode, null, (prefab) => {
        //             prefab.getComponent('BoxTipScript').setViewData(1, `回家接收巡夜人小队制式装备`, () => {
        //                 PrefabManage.loadPrefabByType(GameType.MyRoom)
        //             })
        //             prefab.getComponent('BoxTipScript').setBtnStr('回家接收')
        //             prefab.getComponent('BoxTipScript').setCloseBtnView(false)
        //         })
        //     }

        // } else if (mainId == MainTaskIdEnum.MainTask_525) {
        //     let isLock = MiShuManager.getIsLock(20) //送得快
        //     if (isLock == false) {
        //         TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_525)
        //         TaskManager.setCurTask(MainTaskIdEnum.MainTask_526)
        //         this.node.removeFromParent()
        //         this.node.destroy()
        //     }

        // } else if (mainId == MainTaskIdEnum.MainTask_532) {
        //     let isLock = MiShuManager.getIsLock(24) //钱多发
        //     if (isLock == false) {
        //         TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_532)
        //         this.node.removeFromParent()
        //         this.node.destroy()
        //     }

        // }
    }

    onListMGridRender(item: cc.Node, idx: number) {
        //item.getComponent(ListItem).title.getComponent(cc.Label).string = this.data[idx] + '';

        let config = this.dataListM[idx]
        // console.log(config)
        let danItem: MishuItem = item.getComponent('MishuItem')
        danItem.setViewDate(config, true)
    }


    onListDGridRender(item: cc.Node, idx: number) {

        let config = this.dataListD[idx]
        let danItem: MishuItem = item.getComponent('MishuItem')
        danItem.setViewDate(config, false)

    }



    pxmsBtnClick() {
        //Common5.playEffect("sound/按键点击")
        //fix me
        let num = MiShuManager.getUnLockMishuNum()
        if (num >= 10) {
            PrefabManage.loadPrefabByType(GameType.MishuPeixun, null, (prefab) => {
                prefab.getComponent('MishuPeiXun').setViewDate('Mishu')
            })
        } else {
            PrefabManage.showTextTips('拥有10个助理后可解锁')
        }


    }


    pxduiyouBtnClick() {
        //Common5.playEffect("sound/按键点击")
        //fix me
        let num = MiShuManager.getUnLockDuiyouNum()

        if (num >= 6) {
            PrefabManage.loadPrefabByType(GameType.MishuPeixun, null, (prefab) => {
                prefab.getComponent('MishuPeiXun').setViewDate('Duiyou')
            })
        } else {
            PrefabManage.showTextTips('拥有6个队友后可解锁')
        }

    }

    chooseClickEvent(event, data) {
        //Common5.playEffect("sound/按键点击")
        if (data == 'listM') {


            this.listM.node.active = true

            this.listD.node.active = false
            this.label.string = '助理升级到20级可获得点击加成'
            this.node.getChildByName('mishuPeixunNode').active = true

            this.node.getChildByName('duiyouPeixunNode').active = false

            this.setListM()
        } else if (data == 'listD') {


            this.listM.node.active = false

            this.listD.node.active = true
            this.label.string = '队友升级到20级可获得点击加成'

            this.node.getChildByName('mishuPeixunNode').active = false

            this.node.getChildByName('duiyouPeixunNode').active = true


            this.setListD()
        }

        this.refreshShouyi()
    }

    refreshShouyi() {
        let allshouyi1 = MiShuManager.getAllIncomeMishu()
        this.allShouyiMS.string = Common5.getNumberChangeHanzi(allshouyi1) + ''

        let allshouyi2 = MiShuManager.getAllIncomeDuiyou()
        this.allShouyiDY.string = Common5.getNumberChangeHanzi(allshouyi2) + ''

    }

    refreshUpNum() {
        let mishuList = User.getMishuList()
        // let mishuNum = 0
        // for (let i = 0; i < mishuList.length; i++) {
        //     if (!mishuList[i].isLock) {
        //         mishuNum++
        //     }
        // }
        // this.node.getChildByName("秘书数量").getComponent(cc.Label).string = `${MiShuManager.getAllMishuNum()}`
        // this.node.getChildByName("秒赚收益").getComponent(cc.Label).string = `${MiShuManager.getAllIncomeMishuMiaoZhuan()}`

        // let beishuSP = ShipuManager.getAllShipuInCome()
        // let zichan = ZiChanManager.getZiChanBeiShu()
        // let fanbei = User.getShouyiFanbeiNum()
        // let chenghaoInCome = LevelUpManager.getAllChengHaoinCome() //称号倍数
        // this.node.getChildByName("秒赚收益总加成").getComponent(cc.Label).string = `${Math.floor((beishuSP * zichan * fanbei * chenghaoInCome)) * 100}%`

        // let allNum = MiShuManager.getAllIncomeMishu()
        // let mzNum = Math.floor(allNum * beishuSP * chenghaoInCome * zichan) //秒赚收益
        // this.node.getChildByName("秒赚总收益").getComponent(cc.Label).string = `${Common5.getNumberChangeHanzi(mzNum)}/秒`
    }
    setListM() {
        let content = this.listM.node.getChildByName('mask').getChildByName('content')
        content.removeAllChildren()
        content.destroyAllChildren()
        let content2 = this.listD.node.getChildByName('mask').getChildByName('content')
        content2.removeAllChildren()
        content2.destroyAllChildren()

        let mishuList = User.getMishuList()
        this.dataListM = []
        for (let n = 0; n < mishuList.length; n++) {

            this.dataListM.push(mishuList[n]);


        }
        this.listM.numItems = this.dataListM.length;


        let index = MiShuManager.getMishuLockIndex()
        this.listM.scrollTo(index)

    }

    setListD() {
        let content = this.listM.node.getChildByName('mask').getChildByName('content')
        content.removeAllChildren()
        content.destroyAllChildren()
        let content2 = this.listD.node.getChildByName('mask').getChildByName('content')
        content2.removeAllChildren()
        content2.destroyAllChildren()
        let duiyouList = User.getDuiyouList()

        let taskDate = User.getCurTaskId()
        if (taskDate[0] >= MainTaskIdEnum.MainTask_532) {
            this.dataListD = []
            for (let n = 0; n < duiyouList.length; n++) {
                this.dataListD.push(duiyouList[n]);
            }
            this.listD.numItems = this.dataListD.length;
            //修改把钱多发移到前面

        } else {
            this.dataListD = []
            for (let n = 0; n < duiyouList.length - 1; n++) {
                this.dataListD.push(duiyouList[n]);
            }
            this.listD.numItems = this.dataListD.length;
        }

        let index = MiShuManager.getDuiyouLockIndex()
        if (index >= 18) {
            index = index - 18
        }
        this.listD.scrollTo(index)

        //MainTask_532

    }
    // update (dt) {}

    // 展示气泡
    showQiPao(curLog, func?, aniFunc?) {
        //cc.audioEngine.stopAllEffects();
        if (curLog != null && curLog != undefined && typeof (curLog) == "number") {
            curLog = this.chatConfig[curLog]
        }
        // if (!curLog) {
        //     return
        // }

        if (curLog.effectUrl && curLog.effectUrl.length > 0) {
            Common5.playRemoteAudioEffect(curLog.effectUrl);
            // Common5.playEffectCustom("GameRes", curLog.effectUrl);
        }

        let string_ = curLog.str
        let qiPaoPos_ = curLog.posi ?? curLog.qiPaoPos
        let delayTime_ = curLog.delayTime ?? curLog.delay

        if (aniFunc) {
            aniFunc()
        }

        if (qiPaoPos_ != '-1') {
            let node = this.node.getChildByName('qipao');
            let qiPao = node.getChildByName(qiPaoPos_);
            qiPao.stopAllActions()
            this.showDialogStr(string_, qiPao.getChildByName("str"))
            // qiPao.getChildByName("str").getComponent(cc.Label).string = string_
            qiPao.active = true
            // let scale = qiPao.scale
            qiPao.scale = 0
            cc.tween(qiPao)
                .to(0.2, { scale: 1 / this.node.scale })
                .delay(delayTime_)
                .call(() => {
                    qiPao.active = false;
                })
                .start();
        } else {
            let chatLog = this.node.getChildByName('chatLog')
            chatLog.active = true
            if (curLog.endStr) {
                chatLog.getChildByName("str").getComponent(cc.Label).string = curLog.endStr
            } else {
                if (this.selectIndex == 1) {
                    chatLog.getChildByName("str").getComponent(cc.Label).string = curLog.str1
                } else {
                    chatLog.getChildByName("str").getComponent(cc.Label).string = string_
                }
            }
            //this.showDialogStr(string_, chatLog.getChildByName("str"))
            chatLog.stopAllActions()
            cc.tween(chatLog)
                .delay(delayTime_)
                .call(() => {
                    chatLog.active = false;
                })
                .start();
        }

        this.scheduleOnce(() => {
            func && func();
        }, delayTime_ + 0.2);
    }

    // 逐字显示
    showDialogStr(str, dialogStr, finishFunc?) {
        let curStr = ""
        let curIndex = 0
        let callFunc = () => {
            curStr += str[curIndex++]
            dialogStr.getComponent(cc.Label).string = curStr
            if (curIndex >= str.length) {
                finishFunc && finishFunc()
            }
        }
        this.schedule(callFunc, 0.05, str.length - 1);
    }

    // 展示点击说话
    showClickDialog(curLog, func?, aniFunc?) {
        let text = curLog.str;
        if (text.length > 7) {
            text = curLog.str.slice(0, 6) + '...';
        }
        let dialog = this.node.getChildByName('对话框');
        dialog.getChildByName('lab').getComponent(cc.Label).string = text;
        dialog.active = true;
        this["_clickDialog"] = curLog;
        this["_clickDialogCallback"] = func;
        this["_clickDialogAniCallback"] = aniFunc;

        this.duihuakuang1 = dialog

        if (curLog.str1) {
            let text = curLog.str1;
            if (text.length > 7) {
                text = curLog.str1.slice(0, 6) + '...';
            }
            let node = cc.instantiate(dialog)
            node.name = "第二个选择"
            this.node.addChild(node)
            let position = dialog.position.clone()
            position.y += dialog.getContentSize().height
            node.setPosition(position)
            node.getChildByName('lab').getComponent(cc.Label).string = text;

            this.duihuakuang2 = node
        }
    }

    // 点击展示对话
    onClickShowDialog(event) {
        let target = event.target;
        target.active = false;
        if (this.duihuakuang1) {
            this.duihuakuang1.active = false
        }
        if (this.duihuakuang2) {
            this.duihuakuang2.active = false
        }

        if (target.name == "第二个选择") {
            this.selectIndex = 1
        } else {
            this.selectIndex = 0
        }

        let clickDialog = this["_clickDialog"];
        let clickDialogCallback = this["_clickDialogCallback"];
        let clickDialogAniCallback = this["_clickDialogAniCallback"];
        if (clickDialog) {
            this.showQiPao(clickDialog, () => {
                clickDialogCallback && clickDialogCallback();
            }, clickDialogAniCallback);
        }
    }
}