import User from "../../FrameWork/User/User";
import Common5 from "../../Platform/th/Common5";
import CccGame from "../../WenZiRes/WordGame/gameComScript/CccGame/CccGame";
import GameBaseScript from "../GameRoomRes/GameBaseScript";
import TaskManager, { MainTaskIdEnum } from "../JuQingChat/TaskManager";
import UserManager from "../Manager/UserManager";
import NewGuideScript from "../NewGuide/NewGuideScript";
import PrefabManage, { GameType } from "../PrefabManager/PrefabManage";
import GetAward from "../SCommon/GetAward";
import DHBase from "./DHBase";
import selectButtons from "./selectButtons";
import taskState from "./taskState";
const { ccclass, property, disallowMultiple, menu } = cc._decorator;

@ccclass
@disallowMultiple()
@menu('对话剧情/DH_18')
export default class DH_18 extends DHBase {
    chatConfig = [
        { effectUrl: 'DH/DH_18/sound/汉升哥哥,我这个样子你喜欢吗?', delayTime: 4.19, str: '汉升哥哥,我这个样子你喜欢吗?', posi: 'qipao2' },
        { effectUrl: 'DH/DH_18/sound/汉升哥哥,你是喜欢这种清纯的吗?', delayTime: 3.75, str: '汉升哥哥,你是喜欢这种清纯的吗?', posi: 'qipao2' },
        { effectUrl: 'DH/DH_18/sound/汉升哥哥,原来你喜欢这种,是吗?', delayTime: 4.53, str: '汉升哥哥,原来你喜欢这种,是吗?', posi: 'qipao2' },
    ]

    @property(sp.Skeleton)
    nvzhu: sp.Skeleton = null

    @property(cc.Node)
    m_bg: cc.Node = null
    @property(cc.Node)
    MoveNodes: cc.Node = null
    curScheduleIndex: number = 0;
    curNvZhuScheduleIndex: number = 0;

    start() {
        Common5.playRemoteAudioMusic("remotesound/effect/轻快-10秒", true)
        Common5.preLoadRemoteAudioByChatConfig(this.chatConfig);
        super.start();
        this.continueStory();
        // this.scheduleOnce(() => {
        //     PrefabManage.preloadPrefabByType(GameType.DH_189)
        // })
    }



    // 继续剧情
    continueStory() {
        this.scheduleOnce(() => {
            PrefabManage.preloadPrefabByType(GameType.DH_19)
        })
        let nvzhuFunc = () => {
            if (this.curScheduleIndex >= 6) {
                if (this.curNvZhuScheduleIndex == 0) {
                    this.nvzhu.setAnimation(0, "女主职场裙", true)
                    this.showQiPao(this.chatConfig[0], null, () => {
                        // this.nanzhu.setAnimation(0, "说话", true)
                    });
                } else if (this.curNvZhuScheduleIndex == 1) {
                    this.nvzhu.setAnimation(0, "女主可爱裙", true)
                    this.showQiPao(this.chatConfig[1], null, () => {
                        // this.nanzhu.setAnimation(0, "说话", true)
                    });
                } else {
                    this.nvzhu.setAnimation(0, "女主礼服", true)
                    this.showQiPao(this.chatConfig[2], null, () => {
                        // this.nanzhu.setAnimation(0, "说话", true)
                    });
                }
                this.curNvZhuScheduleIndex++
            }
        }
        let chadianNodeList = this.m_bg.getChildByName('chadianNodeList').children;
        let moneys = this.m_bg.getChildByName('钞票');
        moneys.active = true;
        for (let index = 0; index < moneys.childrenCount; index++) {
            const element = moneys.children[index];
            let callFuncs = this.onNodeTouchMoreCheckEvent(element, chadianNodeList);
            callFuncs.setSuccessListener((data_) => {
                let checkNode = data_.targetNode.checkNode;
                switch (checkNode.name) {
                    case '贫穷床':
                        Common5.playRemoteAudioEffect("remotesound/effect/游戏点击音效")
                        checkNode.active = false;
                        this.m_bg.getChildByName('豪华床').active = true;
                        break;
                    case '破旧床头柜':
                        Common5.playRemoteAudioEffect("remotesound/effect/游戏点击音效")
                        checkNode.active = false;
                        this.m_bg.getChildByName('床头柜').active = true;
                        break;
                    case '破旧的吊灯':
                        Common5.playRemoteAudioEffect("remotesound/effect/游戏点击音效")
                        checkNode.active = false;
                        this.m_bg.getChildByName('豪华灯').active = true;
                        break;
                    // case '破旧的柜子_':
                    //     checkNode.active = false;
                    //     this.m_bg.getChildByName('柜子').active = true;
                    //     break;
                    case '破旧的电视柜':
                        Common5.playRemoteAudioEffect("remotesound/effect/游戏点击音效")
                        checkNode.active = false;
                        this.m_bg.getChildByName('电视柜').active = true;
                        break;
                    case '贫穷窗户':
                        Common5.playRemoteAudioEffect("remotesound/effect/游戏点击音效")
                        checkNode.active = false;
                        this.m_bg.getChildByName('豪华窗户').active = true;
                        break;
                    case '背景':
                        Common5.playRemoteAudioEffect("remotesound/effect/游戏点击音效")
                        checkNode.active = false;
                        this.m_bg.getChildByName('豪华背景').active = true;
                        break;
                    case '女主1':
                        Common5.playRemoteAudioEffect("remotesound/effect/游戏点击音效")
                        nvzhuFunc()
                        break;
                    case '女主2':
                        Common5.playRemoteAudioEffect("remotesound/effect/游戏点击音效")
                        nvzhuFunc()
                        break;
                    case '女主3':
                        Common5.playRemoteAudioEffect("remotesound/effect/游戏点击音效")
                        nvzhuFunc()
                        break;
                    default:
                        break;
                }
                this.curScheduleIndex++;
                if (this.curScheduleIndex == 6) {
                    Common5.playRemoteAudioMusic("remotesound/effect/暧昧-10秒", true)
                    PrefabManage.loadPrefabByType(GameType.selectButtons, this.node, (node) => {
                        let strs = ['拖动钱给苏瑶买衣服换装', '直接收回来']
                        let actives = [true, true]
                        let funcs = [
                            () => {
                                this.m_bg.getChildByName('chadianNodeList').getChildByName("女主1").active = true
                            },
                            () => {
                                this.goTask()
                                UserManager.addMoney(3000000000, this.node)
                            },
                        ]
                        let isvideo = [true, false]
                        node.getComponent(selectButtons).init(strs, actives, funcs, isvideo)
                        node.getComponent(selectButtons).setTitle('钱还有剩余,你选择:')
                    })
                } else if (this.curScheduleIndex == 7) {
                    this.m_bg.getChildByName('chadianNodeList').getChildByName("女主2").active = true
                } else if (this.curScheduleIndex == 8) {
                    this.m_bg.getChildByName('chadianNodeList').getChildByName("女主3").active = true
                }

                if (this.curScheduleIndex >= 9) {
                    this.goTask()
                }
                callFuncs.closeTouchEvent();
            });
        }

        // this.nanzhu.setAnimation(0, "待机", true)
        // const dialogEvents = [
        //     (func) => {
        //         this.runBg(0, 3, this.MoveNodes.getChildByName("男主"), () => {
        //             func()
        //         })
        //     },
        //     (func) => {
        //         this.showQiPao(this.chatConfig[this.dialogIndex++], func, () => {
        //             this.nanzhu.setAnimation(0, "说话", true)
        //         });
        //     },
        // ]
        // const dialogCallFunc = (logEvents: any[]) => {
        //     logEvents.shift()(() => {
        //         if (logEvents.length > 0) {
        //             dialogCallFunc(logEvents);
        //         } else {
        //             // PrefabManage.loadPrefabByType(GameType.GetAward, null, (prefabNode) => {
        //             //     let goods = [{ goodId: 1733, goodNum: 1 }];
        //             //     prefabNode.getComponent(GetAward).initView(goods, () => {
        //             //         // TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_530)
        //             //         // User.setRoomGoodStatus("DH_189")
        //             //         // UserManager.clearAndaddStructureFlash("cf_FengRenYuan")
        //             //     });
        //             // });
        //             // TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_202)
        //             // TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_203)
        //             // this.node.destroy()
        //         }
        //     });
        // }
        // dialogCallFunc(dialogEvents);
    }

    goTask() {
        this.curScheduleIndex = 0;
        TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_519)
        TaskManager.setCurTask(MainTaskIdEnum.MainTask_520)
        // PrefabManage.showTextTips("装修成功")
        UserManager.subMoney(10000000000)
        PrefabManage.loadPrefabByType(GameType.taskState, this.node, (node) => {
            node.getComponent(taskState).showSuccess("装修成功", () => {
                PrefabManage.showBlackGuoDu(() => {
                    PrefabManage.loadPrefabByType(GameType.DH_19)
                    this.node.removeFromParent()
                    this.node.destroy()
                })
            })
        })
    }

    guideView(nodeArray, opacity = -1) {
        PrefabManage.loadPrefabByType(GameType.GuideMskNode, this.node, (prefab) => {
            // prefab.zIndex = 199
            let guideNodeArray = nodeArray
            let firstNode = guideNodeArray.shift()
            prefab.getComponent(NewGuideScript).setBindNode(firstNode, guideNodeArray)
            if (opacity != -1) {
                prefab.getComponent(NewGuideScript).setOpacityMaskNode(opacity)
            }
        })
    }

    runBg(time, scale, endnode, callFunc) {
        cc.tween(this.m_bg)
            .to(time, { scale: scale })
            .start()
        cc.tween(this.m_bg)
            .sequence(
                cc.tween().to(time, { position: cc.v2(-endnode.position.x * scale, -endnode.position.y * scale) }),
                cc.tween().call(() => {
                    callFunc()
                })
            )
            .start()
    }

    /**
         * 节点触摸多碰撞事件注册
         * @param emitTarget 触发节点
         * @param checkNodeArray 触碰节点数组
         * @param emitAttr 触发节点绑定参数
         * @param moveNode 触摸移动时的父节点
         * @returns 回调函数集合
        */
    public onNodeTouchMoreCheckEvent(
        emitTarget: cc.Node,
        checkNodeArray: cc.Node[],
        emitAttr: any = {},
        moveNode: cc.Node = null
    ) {
        //成功回调事件
        let successCallback: (data_: any) => void = null;
        //失败回调事件
        let failCallback: (data_: any) => void = null;

        //触摸开始
        let touchStartNode = (event) => {
            let target = event.target;
            console.log('touchStartNode', target.zIndex);
            if (target['_touchListener']) {
                target['_touchListener'].setSwallowTouches(true);
            }
            Common5.playEffect("点击音效");
            target['saveWorldPos'] = target.convertToWorldSpaceAR(cc.Vec2.ZERO);
        };

        //触摸移动
        let touchMoveNode = (event) => {
            let target = event.target

            if (moveNode) {
                target.parent = moveNode;
            }
            let posi = event.getLocation()//世界坐标
            posi = target.parent.convertToNodeSpaceAR(posi)
            target.setPosition(posi)
        };

        //触摸结束
        let touchEndNode = (event) => {
            let target = event.target;
            if (target['_touchListener']) {
                target['_touchListener'].setSwallowTouches(false);
            }

            let checkNode = null;
            let checkNodeArray = target.checkNodeArray;
            for (let iterator of checkNodeArray) {
                // if (this.SpecilalShowNode) {
                //     if (iterator == this.SpecilalShowNode) {
                //         if (iterator.active && Common5.checkContainsNode(iterator, target)) {
                //             checkNode = iterator;
                //             break;
                //         }
                //     }
                // } else {
                if (iterator.active && Common5.checkContainsNode(iterator, target)) {
                    checkNode = iterator;
                    break;
                }
                // }

            }
            if (checkNode) {
                target.active = false;
                checkNode.active = false;
                target['checkNode'] = checkNode;
                if (successCallback) {
                    successCallback({ targetNode: target });
                }
            } else {
                if (failCallback) {
                    failCallback({ targetNode: target });
                }
            }

            if (target.recoveposi) {
                cc.tween(target)
                    .to(0.2, { position: target.parent.convertToNodeSpaceAR(target['saveWorldPos']) })
                    .set({ parent: target.recoveparent, position: target.recoveposi })
                    .start();
            }
        };

        //注册触摸事件
        emitTarget['checkNodeArray'] = checkNodeArray;
        emitTarget['recoveposi'] = emitTarget.getPosition();
        emitTarget['recoveparent'] = emitTarget.parent;
        emitTarget.attr(emitAttr);
        emitTarget.on(cc.Node.EventType.TOUCH_START, touchStartNode)
        emitTarget.on(cc.Node.EventType.TOUCH_MOVE, touchMoveNode)
        emitTarget.on(cc.Node.EventType.TOUCH_CANCEL, touchEndNode)
        emitTarget.on(cc.Node.EventType.TOUCH_END, touchEndNode)

        //回调函数集合
        let retFuncGroup = {
            /**设置完成后的事件监听 */
            setSuccessListener: (callback: (data_: any) => void) => {
                successCallback = callback;
            },
            /**设置失败后的事件监听 */
            setFailListener: (callback: (data_: any) => void) => {
                failCallback = callback;
            },
            /**关闭触摸事件 */
            closeTouchEvent: () => {
                emitTarget.off(cc.Node.EventType.TOUCH_START, touchStartNode);
                emitTarget.off(cc.Node.EventType.TOUCH_MOVE, touchMoveNode);
                emitTarget.off(cc.Node.EventType.TOUCH_CANCEL, touchEndNode);
                emitTarget.off(cc.Node.EventType.TOUCH_END, touchEndNode);
                successCallback = null;
                failCallback = null;
            }
        };

        return retFuncGroup;
    }
}