import { ryw_Event } from "../../../FrameWork/Event/EventEnum";
import EventMgr from "../../../FrameWork/Event/EventMgr";
import GameReport from "../../../FrameWork/Report/ZyZyReport";
import User from "../../../FrameWork/User/User";
import AppPlatform from "../../../FrameWork/Util/AppPlatform";
import { DateUtils } from "../../../FrameWork/Util/DateUtils";
import Common5 from "../../../Platform/th/Common5";
import JuQingManager from "../../JuQingChat/JuQingManager";
import TaskManager, { MainTaskDataInfo, MainTaskIdEnum, SubTaskIdEnum } from "../../JuQingChat/TaskManager";
import JuQingQiPao from "../../JuQingGuanQia/JuQingQiPao";
import BagManager, { BagGoodsConfig, GoodsLocalProperty } from "../../Manager/BagManager";
import InterfaceManager from "../../Manager/InterfaceManager";
import UserManager from "../../Manager/UserManager";
import TaskResult from "../../MyRoom/TaskResult";
import NewGuideScript from "../../NewGuide/NewGuideScript";
import PrefabManage, { GameType } from "../../PrefabManager/PrefabManage";
import GameBase from "../../SCommon/GameBase";
import GetAward from "../../SCommon/GetAward";

const { ccclass, property } = cc._decorator;


@ccclass
export default class ShouHuoJiGai extends GameBase {

    @property(cc.Node)
    huoJiaContent: cc.Node = null

    // @property(cc.Node)
    // tankuang: cc.Node = null

    @property(cc.Node)
    singleGoodItem: cc.Node = null

    // @property(cc.Slider)
    // numSlider: cc.Slider = null

    @property(cc.Node)
    maskNode: cc.Node = null

    curSelectKuaiDiIndex: number = 0
    adGoodsId: number = 0
    buyMoney = 0
    buyGoodId = 0
    jifenBili = 5
    maxLeng = 4
    iconNum = 1
    maskGuideNode: cc.Node = null
    _dt1:number = 0
    _dt2:number = 0
    isOpenTimeCount:boolean = false
    timeNum:number = 120
    guangGaoPai:cc.Node = null
    showAdNum = 0; //看广告的次数--免费获得

    onLoad() {
        super.onLoad()

        this.guangGaoPai = this.node.getChildByName('广告牌')
    }

    onDestroy(): void {
        if (cc.isValid(this.maskGuideNode)) {
            this.maskGuideNode.removeFromParent()
            this.maskGuideNode.destroy()
        }
        super.onDestroy()

        EventMgr.emitEvent_custom(ryw_Event.RefreshJuQingDuiHua);
    }

    protected start(): void {
        // GameBaseScript.preLoadRemoteAudio(ChadianConfig);
        this.showAdNum = User.getShowAdNum()
        this.setAdNum()
        this.refrehView(false)
        this.duiHuaInfo()
        // this.refreshGoodsAd()
    }
    
    protected update(dt: number): void {
        this._dt1 += dt
        if(this._dt1 >= 5){
            this._dt1 = 0
            this.guangGaoPai.getComponent(sp.Skeleton).setAnimation(0,'播放',false)
        }
        if(this.isOpenTimeCount){
            this._dt2 += dt
            if(this._dt2 >= 1){
                this._dt2 = 0
                // this.timeNum -= 1
                // if(this.timeNum <= 0){
                //     this.closeTimeCount()
                // }else{
                //     this.showTimeCount()
                // }
            }
        }
    }
    showTimeCount(){
        this.guangGaoPai.getChildByName('btnAddTime').active = false
        this.guangGaoPai.getChildByName('timeNode').active = true
        this.guangGaoPai.getChildByName('timeNode').getChildByName('countTimeStr').getComponent(cc.Label).string = `限时:${DateUtils.formatTime2_custom(this.timeNum)}`
    }
    closeTimeCount(){
        this.isOpenTimeCount = false
        this.timeNum = 120
        this.guangGaoPai.getChildByName('btnAddTime').active = true
        this.guangGaoPai.getChildByName('timeNode').active = false
    }
    duiHuaInfo() {
        let strArr = [
            '面具下的我,想深入了解吗?',
            '小帅哥,需要点什么呢!'
        ]
        let str = this.node.getChildByName('qiPao').getChildByName('qiPao_0').getChildByName('str')
        let ren = this.node.getChildByName('商人')
        let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id
        if (mainId < MainTaskIdEnum.MainTask_1702) {
            str.getComponent(cc.Label).string = strArr[0]
            ren.getComponent(sp.Skeleton).setAnimation(0,'animation',true)
        }else{
            str.getComponent(cc.Label).string = strArr[1]
            ren.getComponent(sp.Skeleton).setAnimation(0,'animation2',true)
        }

        if (mainId == MainTaskIdEnum.MainTask_102) {
            let node = this.node.getChildByName('GuideNode1');
            this.guideView([node]);
        } 
    }

    guideView(nodeArray) {
        if (this.maskGuideNode == null) {
            PrefabManage.loadPrefabByType(GameType.GuideMskNode, this.node, (prefab) => {
                let guideNodeArray = nodeArray
                this.maskGuideNode = prefab
                let firstNode = guideNodeArray.shift()
                prefab.getComponent(NewGuideScript).setBindNode(firstNode, guideNodeArray)
            })
        } else {
            this.maskGuideNode.active = true
            let guideNodeArray = nodeArray
            let firstNode = guideNodeArray.shift()
            this.maskGuideNode.getComponent(NewGuideScript).setBindNode(firstNode, guideNodeArray)
        }
    }

    refrehView(videoAD) {
        let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        let config = TaskManager.getTaskConfigById(mainTaskInfo.Id)

        let list = User.getShouHuoJiiList()
        console.log(list, 'list++++++==')
        if (list.length == 0) {
            list.length = 0
            let fixGoodList = InterfaceManager.getMangheGoodsListByType('ShouHuoJi', this.maxLeng, videoAD)
            let bianhaoLength = this.maxLeng//this.huojia.children.length
            for (let i = 0; i < bianhaoLength; i++) {
                let obj = {
                    goodId: 0,
                    saveNum: 0
                }
                obj.goodId = fixGoodList[i].goodId
                let goodPro = BagManager.getGoodsProperty(obj.goodId)
                obj.saveNum = goodPro.saveNum
                list[list.length] = obj//fixGoodList[i].goodId
            }
        }

        //采购单中免费的物品必出(走重新刷新逻辑)
        if (config && config.taskCaiGouDan && config.GMGameType == "ShouHuoJi") {
            let caiGouDanArr = Common5.deepClone(config.taskCaiGouDan)
            // let filteredArray = caiGouDanArr.filter(item => !config.GMGoodIdArray.includes(item));

            let tempIndexTab = []
            for (let i = 0; i < list.length; i++) {
                tempIndexTab.push(i)
            }
            for (let i = 0; i < list.length; i++) {
                //剔除掉已经生成的GM物品
                if (config.taskCaiGouDan.indexOf(list[i].goodId) >= 0) {
                    caiGouDanArr.splice(i, 1)
                    tempIndexTab.splice(i, 1)
                    break
                }
            }

            for (let i = 0; i < caiGouDanArr.length; i++) {
                if(BagManager.getBagGoodNums(caiGouDanArr[i]) <= 0){
                    let obj = {
                        goodId: caiGouDanArr[i],
                        saveNum: 1
                    }
                    list[tempIndexTab[i]] = obj
                }
            }
        }

        User.setShouHuoJiiList(list)
        this.refreshContent()
    }

    // refreshGoodsAd() {
    //     this.adGoodsId = null;
    //     this.node.getChildByName('盲盒').active = false;
    //     this.node.getChildByName('bg').getChildByName('暂无').active = false;

    //     let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo();
    //     let config = TaskManager.getTaskConfigById(mainTaskInfo.Id);
    //     if (config && config.GMGameType == "ShouHuoJi" && config.GMGoodIdArray) {
    //         for (const goodsId of config.GMGoodIdArray) {
    //             if (BagManager.getBagGoodNums(goodsId) == 0) {
    //                 this.adGoodsId = goodsId;
    //                 break;
    //             }
    //         }
    //     }
    //     if (this.adGoodsId) {
    //         let goodItem = this.node.getChildByName('盲盒');
    //         goodItem.active = true;
    //         let labName = goodItem.getChildByName('name').getComponent(cc.Label);
    //         let icon = goodItem.getChildByName('icon').getComponent(cc.Sprite);

    //         let goodData = BagManager.getGoodsProperty(this.adGoodsId);
    //         labName.string = goodData.goodName;
    //         // Common5.getSpriteFrameFromBundle("GoodIcon", "icon/" + goodData.goodId, icon);
    //         Common5.setRemoteSpriteFrame(icon, 'GoodIcon/' + goodData.goodId)
    //     } else {
    //         this.node.getChildByName('bg').getChildByName('暂无').active = true;
    //     }
    // }

    //初始化快递包裹
    refreshContent() {
        let bianhaoLength = this.maxLeng;
        this.huoJiaContent.removeAllChildren();
        this.huoJiaContent.destroyAllChildren();

        for (let i = 0; i < bianhaoLength; i++) {
            let _node = cc.instantiate(this.singleGoodItem);
            _node.active = true;
            _node.parent = this.huoJiaContent;
            // this.huoJiaContent.children[i].on(cc.Node.EventType.TOUCH_START, this.touchStartNode, this);
        }
        this.refreshItemList();
    }

    // 刷新快递列表
    refreshItemList() {
        let taskCaiGouDan = [];
        let taskInfo: any = TaskManager.getCurUnLockMainTaskInfo();
        if (taskInfo && taskInfo.Id != MainTaskIdEnum.MainTask_None) {
            let config = TaskManager.getTaskConfigById(taskInfo.Id);
            if (config && config.taskCaiGouDan) {
                taskCaiGouDan = config.taskCaiGouDan;
            }
        }

        let fixGoodList = User.getShouHuoJiiList();
        for (let i = 0; i < fixGoodList.length; i++) {
            let goodItem = this.huoJiaContent.children[i];
            let goodData = this.getDatabyGoodId(fixGoodList[i].goodId);
            let goodIcon = goodItem.getChildByName('goodIcon').getComponent(cc.Sprite);
            let goodName = goodItem.getChildByName('goodName').getComponent(cc.Label);
            let goodPrice = goodItem.getChildByName('goodPrice').getComponent(cc.Label);
            let btnBuy = goodItem.getChildByName('btnBuy')

            // Common5.getSpriteFrameFromBundle("GoodIcon", "icon/" + goodData.goodId, icon);
            Common5.setRemoteSpriteFrame(goodIcon, 'GoodIcon/' + goodData.goodId)
            goodName.string = goodData.goodName;
            goodPrice.string = `售价:${Common5.getNumberChangeHanzi(goodData.priceNum)}`;
            if(this.isOpenTimeCount){
                goodPrice.string = `售价:0`;
                btnBuy.getChildByName("免费").active = true
            }
            btnBuy.attr({ index: i, goodDataId: goodData.goodId, goodPriceNum: goodData.priceNum });

            goodItem.getChildByName('taskTip').active = false;
            if (taskCaiGouDan.indexOf(fixGoodList[i].goodId) >= 0) {
                if (BagManager.getBagGoodNums(fixGoodList[i].goodId) <= 0) {
                    goodItem.getChildByName('taskTip').active = true;
                }
            }
        }
    }

    getDatabyGoodId(goodid) {
        let fixGoodList = InterfaceManager.getFixGoodListByIndex()
        for (let value of fixGoodList) {
            if (value.goodId == goodid) {
                return value
            }
        }
        for (let value of BagGoodsConfig) {
            if (value.goodId == goodid) {
                return value
            }
        }
    }

    // touchStartNode(event) {
    //     this.showBuyBox(event.target)
    // }

    getUserListValue(goodId) {
        let list = User.getShouHuoJiiList()
        let valueData = null
        for (let i = 0; i < list.length; i++) {
            if (list[i].goodId == goodId) {
                valueData = list[i]
            }
        }

        return valueData
    }

    

    // showRaffle() {
    //     const raffleNode = this.node.getChildByName('raffleView');
    //     raffleNode.active = true;
    //     const click = raffleNode.getChildByName('点击');
    //     click.active = true;
    // }

    // 检测任务是否完成
    checkTaskFinish() {
        let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id

        if (mainId == MainTaskIdEnum.MainTask_102) {
            let isHave3001 = (BagManager.getBagGoodNums(3057) > 0)
            if (isHave3001) {
                TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_102)
                TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_103)
                JuQingManager.unLockNewJuQing('WX_102')
                let successFunc = () => {
                    this.node.removeFromParent()
                    this.node.destroy()
                    JuQingManager.openJuQingOrChat('WX')
                }
                PrefabManage.loadPrefabByType(GameType.TaskResult, null, (prefabNode) => {
                    prefabNode.getComponent(TaskResult).initView1(5, true, successFunc)
                })
            }
        } else if (mainId == MainTaskIdEnum.MainTask_205) {

            let isHave3002 = (BagManager.getBagGoodNums(3002) > 0)
            let isHave3031 = (BagManager.getBagGoodNums(3031) > 0)
            let isHave3032 = (BagManager.getBagGoodNums(3032) > 0)
            let isHave3033 = (BagManager.getBagGoodNums(3033) > 0)
            // let isHave3034 = (BagManager.getBagGoodNums(3034) > 0)
            if (isHave3002 && isHave3031 && isHave3032 && isHave3033) {
                TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_205)
                JuQingManager.unLockNewJuQing('WX_202')
                TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_206)
            }
        } else if (mainId == MainTaskIdEnum.MainTask_403) {
            let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
            let IsFinish = true;
            for (const goodId of taskCaiGouDan) {
                if (BagManager.getBagGoodNums(goodId) == 0) {
                    IsFinish = false;
                    break;
                }
            }
            if (IsFinish) {
                TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_403);
                TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_404);
                User.setRoomBtnIndex(4);
            }
        } 
        // else if (mainId == MainTaskIdEnum.MainTask_605) {
        //     let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
        //     let IsFinish = true;
        //     for (const goodId of taskCaiGouDan) {
        //         if (BagManager.getBagGoodNums(goodId) == 0) {
        //             IsFinish = false;
        //             break;
        //         }
        //     }
        //     if (IsFinish) {
        //         TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_605);
        //         TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_606);
        //         User.setRoomBtnIndex(1);
        //     }
        // } 
        else if (mainId == MainTaskIdEnum.MainTask_710) {
            let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
            let IsFinish = true;
            for (const goodId of taskCaiGouDan) {
                if (BagManager.getBagGoodNums(goodId) == 0) {
                    IsFinish = false;
                    break;
                }
            }
            if (IsFinish) {
                TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_710);
                TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_711);
            }
        } else if (mainId == MainTaskIdEnum.MainTask_1408) {
            let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
            let IsFinish = true;
            for (const goodId of taskCaiGouDan) {
                if (BagManager.getBagGoodNums(goodId) == 0) {
                    IsFinish = false;
                    break;
                }
            }
            if (IsFinish) {
                TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_1408);
                TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_1409);
                User.setRoomBtnIndex(0);
            }
        } else if (mainId == MainTaskIdEnum.MainTask_1306) {
            let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
            let IsFinish = true;
            for (const goodId of taskCaiGouDan) {
                if (BagManager.getBagGoodNums(goodId) == 0) {
                    IsFinish = false;
                    break;
                }
            }
            if (IsFinish) {
                TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_1306);
                JuQingManager.unLockNewJuQing('WX_1302')
                TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_1307);
            }
        } else if (mainId == MainTaskIdEnum.MainTask_1904) {
            let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
            let IsFinish = true;
            for (const goodId of taskCaiGouDan) {
                if (BagManager.getBagGoodNums(goodId) == 0) {
                    IsFinish = false;
                    break;
                }
            }
            if (IsFinish) {
                TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_1904);
                TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_1905);
                User.setRoomBtnIndex(0);
            }
        }
    }


    //展示气泡
    showQiPao(curLog, func?) {
        console.log("curLog==", curLog)
        if (!curLog) {
            console.log("xxxxxx")
            return;
        }
        let string_ = curLog.str
        let qiPaoPos_ = curLog.qiPaoPos

        if (qiPaoPos_ != -1) {
            if (curLog.effectUrl && curLog.effectUrl.length > 0) {
                Common5.playRemoteAudioEffect(curLog.effectUrl);
            }

            let node = this.node
            let qiPao = node.getChildByName("qiPao").getChildByName("qiPao_" + qiPaoPos_);
            let effect = node.getChildByName("声效").getChildByName("声效" + qiPaoPos_);
            qiPao.stopAllActions()
            this.showDialogStr(string_, qiPao.getChildByName("str"))
            // qiPao.getChildByName("str").getComponent(cc.Label).string = string_
            qiPao.active = true
            qiPao.scale = 0
            effect.active = true
            cc.tween(qiPao)
                .to(0.2, { scale: 1 })
                .delay(curLog.delay)
                .call(() => {
                    qiPao.active = false;
                    effect.active = false;
                    if (func) {
                        func();
                    }
                })
                .start();
        }
        else {
            let qiPao = this.node.getChildByName("dh_qiPao")
            qiPao.getComponent(JuQingQiPao).initView(curLog, func)
        }
    }

    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.07, str.length - 1)
    }
    showBuyBox(target) {

        let goodId = target.goodDataId

        this.buyGoodId = goodId
        this.node.getChildByName('buyBox').active = true


        let spr = this.node.getChildByName('buyBox').getChildByName("spr").getComponent(cc.Sprite)
        let priceLab = this.node.getChildByName('buyBox').getChildByName("priceLab").getComponent(cc.Label)

        // Common5.getSpriteFrameFromBundle("GoodIcon", "icon/" + goodId, kuaiDiXiang);
        Common5.setRemoteSpriteFrame(spr, 'GoodIcon/' + goodId)
        let goodData = BagManager.getGoodsDesc(goodId)

        if(this.isOpenTimeCount){
            priceLab.string = '售价:0'
        }else{
            priceLab.string = '售价:' + Common5.getNumberChangeHanzi(goodData.priceNum) + ''
        }
        
        this.node.getChildByName('buyBox').getChildByName("nameLab").getComponent(cc.Label).string = goodData.goodName
        this.node.getChildByName('buyBox').getChildByName("descLab").getComponent(cc.Label).string = goodData.descStr
    }
    onCloseBuyBoxClick() {
        this.node.getChildByName('buyBox').active = false
    }
    onBuyBtnClick(event){
        let priceNum = event.target.goodPriceNum
        if(this.isOpenTimeCount){
            this.buyMoney = 0
        }else{
            this.buyMoney = priceNum
        }

        if (UserManager.getCurMoney() - this.buyMoney * this.iconNum >= 0) {
            this.showBuyBox(event.target)
        } else {
            this.node.getChildByName('notEnoughMoneyBox').active = true
            this.buyGoodId = event.target.goodDataId
        }
        
    }
    onCloseNotEnoughBox(){
        this.node.getChildByName('notEnoughMoneyBox').active = false
    }
    onNotEnoughBoxBuy(){
        let tab = {
            onClose: (finish) => {
                if (finish) {
                    Common5.ReportDY("inLevel", '杂货铺-AD-豪横购买');
                    this.onCloseNotEnoughBox()
                    this.buyMoney = 0
                    this.onOpenBtnClick()
                }
                else {
                    Common5.showTips_custom("广告未观看完");
                }
            },
            onFailed: () => { }
        }
        AppPlatform.playVideo_custom(tab);
    }
    onOpenBtnClick() {
        // Common5.playEffect("sound/按键点击")
        // this.reportKey(() => {
        //     GameReport.BtnsReport('兑换')
        // })

        // this.buyGoodId = event.target.goodDataId
        UserManager.subMoney(this.buyMoney * this.iconNum);

        let list = User.getShouHuoJiiList();
        for (let i = 0; i < list.length; i++) {
            if (list[i].goodId == this.buyGoodId) {
                list[i].saveNum -= this.iconNum;
                if (list[i].saveNum <= 0) {
                    let fixGoodList = InterfaceManager.getMangheGoodsListByType('ShouHuoJi', 1, false);
                    // console.log('fixGoodList==',fixGoodList)
                    let obj = {
                        goodId: 0,
                        saveNum: 0
                    }
                    obj.goodId = fixGoodList[0].goodId;
                    let goodPro = BagManager.getGoodsProperty(obj.goodId);
                    obj.saveNum = goodPro.saveNum;
                    list[i] = obj;
                }
            }
        }
        // console.log('this.buyGoodId==',this.buyGoodId)
        // console.log('list==',list)

        
        let bagConfig: GoodsLocalProperty = {
            goodId: this.buyGoodId,
            goodNum: this.iconNum,
        }
        BagManager.addBagList(bagConfig);
        PrefabManage.showTextTips('购买成功!');

        // this.tankuang.active = false;
        this.refreshItemList();
        this.checkTaskFinish();
        this.node.getChildByName('buyBox').active = false
    }
    onBtnAddTimeClick(){
        let tab = {
            onClose: (finish) => {
                if (finish) {
                    Common5.ReportDY("inLevel", '杂货铺-AD-加时2分钟');
                    // this.isOpenTimeCount = true
                    this.showAdNum++
                    this.setAdNum()
                    this.refreshItemList();
                    // this.timeNum = 120
                    // this.showTimeCount()
                }
                else {
                    Common5.showTips_custom("广告未观看完");
                }
            },
            onFailed: () => { }
        }
        AppPlatform.playVideo_custom(tab);
    }

    setAdNum() {
        if (this.showAdNum >= 3) {
            this.showAdNum = 3
            this.node.getChildByName("广告牌").getChildByName("btnAddTime").active = false
            this.node.getChildByName("广告牌").getChildByName("buytips").active = true
            this.isOpenTimeCount = true
        }
        User.setShowAdNum(this.showAdNum)
        let lab = this.node.getChildByName("广告牌").getChildByName("btnAddTime").getChildByName("lab")
        lab.getComponent(cc.Label).string = `免费获得(${this.showAdNum}/3)`
    }
}