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 Common5 from "../../../Platform/th/Common5";
import JuQingManager from "../../JuQingChat/JuQingManager";
import TaskManager, { MainTaskIdEnum } from "../../JuQingChat/TaskManager";
import BagManager from "../../Manager/BagManager";
import UserManager from "../../Manager/UserManager";
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 ShiCaiHuiShou extends GameBase {

    @property(cc.Node)
    foodPrefab: cc.Node = null;     // 食材预制体

    @property(cc.Node)
    foodNodeBox: cc.Node = null;    // 食材盒子

    @property(cc.Node)
    FoodShelves: cc.Node = null;    // 食材货架

    @property(cc.Node)
    moveNode: cc.Node = null; // 食材预制体

    @property(cc.Node)
    tipBox: cc.Node = null; // 食材预制体

    GenerateFoodMaxNumber: number = 100; // 生成食材的最大数量
    GenerateFoodAddNumber: number = 20; // 生成食材的增量
    GenerateFoodProportion: number[] = [0.5, 0.1, 0.4]; // 食材生成比例
    GenerateFoodFrameNumber: number = 3; // 每帧生成食材的数量
    FoodPriceListConfig: number[] = [10000000, 100000000, 50000000]; // 食材价格列表

    maskGuideNode: cc.Node = null;  // 遮罩层
    private foodPool: cc.NodePool = null; // 食材池

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

        EventMgr.emitEvent_custom(ryw_Event.RefreshJuQingDuiHua);
    }

    protected start(): void {
        this.foodPool = new cc.NodePool();
        this.refreshFoods();

        EventMgr.onEvent_custom(ryw_Event.NormalTouchEndCheck, (data_) => {
            this.foodClickCallback(data_.targetNode);
        }, this);
    }

    // 刷新食材
    refreshFoods(isAD: boolean = false) {
        for (const element of this.foodNodeBox.children) {
            element.stopAllActions();
            this.foodPool.put(element);
        }

        let foodDataList = this.generateFoodData(this.GenerateFoodMaxNumber).concat(this.addTaskGoods(isAD));

        this.node.getChildByName('inputBlack').active = true;
        this.generateFood(0, foodDataList);
    }

    // 生成食材数据
    generateFoodData(generateFoodMaxNumber: number) {
        const iconNameConfig = [
            ["菜-包菜", "菜-大白菜", "菜-大葱", "菜-洋葱", "菜-白萝卜", "菜-胡萝卜", "菜-芹菜", "菜-茄子", "菜-西兰花", "菜-黄瓜"],
            ["海-扇贝", "海-海参", "海-生蚝", "海-螃蟹", "海-鱿鱼"],
            ["肉-五花肉", "肉-大火腿", "肉-大闸蟹", "肉-排骨", "肉-牛排", "肉-猪蹄", "肉-鸡翅", "肉-鸡腿", "肉-鸭掌", "肉-鸭腿"]
        ];

        let foodDataList: any[] = [];
        for (let type = 0; type < this.GenerateFoodProportion.length; type++) {
            const MaxNumber = this.GenerateFoodProportion[type] * generateFoodMaxNumber;
            for (let i = 0; i < MaxNumber; i++) {
                let foodinfo: any = {};
                foodinfo.x = Math.floor(Math.random() * 500 - 250);
                foodinfo.y = Math.floor(Math.random() * 300 - 130);
                foodinfo.type = type;
                let iconNameList = iconNameConfig[type];
                foodinfo.icon = iconNameList[Math.floor(Math.random() * iconNameList.length)];
                foodDataList.push(foodinfo);
            }
        }

        foodDataList.sort(function () {
            return 0.5 - Math.random()
        });
        return foodDataList;
    }

    // 添加任务道具
    addTaskGoods(isAD: boolean = false) {
        let taskGoodsList: any[] = [];
        const taskInfo: any = TaskManager.getCurUnLockMainTaskInfo();
        if (taskInfo.Id && taskInfo.Id != MainTaskIdEnum.MainTask_None) {
            const configData = TaskManager.getTaskConfigById(taskInfo.Id);
            if (configData && configData.GMGameType == "ShiCaiHuiShou" && configData.taskCaiGouDan) {
                let list_ = configData.taskCaiGouDan.filter((value, index, self) => {
                    if (configData.GMGoodIdArray) {
                        for (const id of configData.GMGoodIdArray) {
                            if (id == value) return false;
                        }
                    }
                    if (BagManager.getBagGoodNums(value) > 0) {
                        return false;
                    }
                    return true;
                })

                if (isAD && configData.GMGoodIdArray) {
                    for (let id of configData.GMGoodIdArray) {
                        if (BagManager.getBagGoodNums(id) == 0) {
                            list_.push(id);
                            break;
                        }
                    }
                }

                for (let i = 0; i < list_.length; i++) {
                    let foodinfo: any = {};
                    foodinfo.x = Math.floor(Math.random() * 500 - 250);
                    foodinfo.y = Math.floor(Math.random() * 300 - 130);
                    foodinfo.type = 999;
                    foodinfo.icon = list_[i];
                    taskGoodsList.push(foodinfo);
                }
            }
        }
        return taskGoodsList;
    };

    // 生成食材
    generateFood(index: number, foodDataList: any[]) {
        let generateNum = this.GenerateFoodFrameNumber;
        if (index + generateNum >= foodDataList.length) {
            generateNum = foodDataList.length - index;
        }

        for (let i = 0; i < generateNum; i++) {
            let foodNode = this.foodPool.get();
            if (foodNode == null) {
                foodNode = cc.instantiate(this.foodPrefab);
            }
            foodNode.active = true;
            this.foodNodeBox.addChild(foodNode);
            foodNode.setPosition(foodDataList[index].x, foodDataList[index].y);
            foodNode['type'] = foodDataList[index].type;
            if (foodDataList[index].type == 999) {
                foodNode['GoodsId'] = foodDataList[index].icon;
            }
            Common5.getSpriteFrameFromBundle("shicaihuishou", "texture/食材/" + foodDataList[index].icon, foodNode.getComponent(cc.Sprite));
            index++;
        }

        if (index < foodDataList.length) {
            this.scheduleOnce(() => {
                this.generateFood(index, foodDataList);
            }, 0);
        } else {
            this.node.getChildByName('inputBlack').active = false;

            let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo();
            let mainId = mainTaskInfo.Id;
            if (mainId == MainTaskIdEnum.MainTask_204) {
                for (let index = 1; index <= 3; index++) {
                    const element = this.foodNodeBox.children[this.foodNodeBox.childrenCount - index];
                    let guide = cc.instantiate(this.node.getChildByName('引导效果'));
                    element.addChild(guide);
                    guide.active = true;
                    guide.setPosition(0, 0);
                }
            }
        }
    }

    // 添加食材
    addFood(index: number, foodDataList: any[]) {
        let generateNum = this.GenerateFoodFrameNumber;
        if (index + generateNum >= foodDataList.length) {
            generateNum = foodDataList.length - index;
        }

        for (let i = 0; i < generateNum; i++) {
            let foodNode = this.foodPool.get();
            if (foodNode == null) {
                foodNode = cc.instantiate(this.foodPrefab);
            }
            foodNode.active = true;
            this.foodNodeBox.insertChild(foodNode, 0);
            foodNode.setPosition(foodDataList[index].x, foodDataList[index].y);
            foodNode['type'] = foodDataList[index].type;
            Common5.getSpriteFrameFromBundle("shicaihuishou", "texture/食材/" + foodDataList[index].icon, foodNode.getComponent(cc.Sprite));
            index++;
        }

        if (index < foodDataList.length) {
            this.scheduleOnce(() => {
                this.addFood(index, foodDataList);
            }, 0);
        }
    }

    // 食材点击回调
    foodClickCallback(targetNode: cc.Node) {
        if (targetNode['type'] == 999) {
            targetNode.active = false;
            let goodArray = [{ goodId: targetNode['GoodsId'], goodNum: 1 }];
            PrefabManage.loadPrefabByType(GameType.GetAward, null, (prefabNode) => {
                prefabNode.getComponent(GetAward).initView(goodArray, () => {
                    let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
                    let mainId = mainTaskInfo.Id
                    if (mainId == MainTaskIdEnum.MainTask_705) {
                        let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
                        for (const goodId of taskCaiGouDan) {
                            if (BagManager.getBagGoodNums(goodId) == 0) {
                                return;
                            }
                        }
                        TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_705);
                        TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_706);
                    } else if (mainId == MainTaskIdEnum.MainTask_1101) {
                        let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
                        for (const goodId of taskCaiGouDan) {
                            if (BagManager.getBagGoodNums(goodId) == 0) {
                                return;
                            }
                        }
                        TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_1101);
                        TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_1102);
                    } else if (mainId == MainTaskIdEnum.MainTask_1301) {
                        let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
                        for (const goodId of taskCaiGouDan) {
                            if (BagManager.getBagGoodNums(goodId) == 0) {
                                return;
                            }
                        }
                        TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_1301);
                        TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_1302);
                    } else if (mainId == MainTaskIdEnum.MainTask_1703) {
                        let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
                        for (const goodId of taskCaiGouDan) {
                            if (BagManager.getBagGoodNums(goodId) == 0) {
                                return;
                            }
                        }
                        TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_1703);
                        TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_1704);
                    } else if (mainId == MainTaskIdEnum.MainTask_2105) {
                        let taskCaiGouDan = TaskManager.getTaskConfigById(mainId).taskCaiGouDan;
                        for (const goodId of taskCaiGouDan) {
                            if (BagManager.getBagGoodNums(goodId) == 0) {
                                return;
                            }
                        }
                        TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_2105);
                        JuQingManager.unLockNewJuQing('WX_2103');
                        TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_2106);
                    }
                });

            });
        } else {
            let type = targetNode['type'];
            let FoodShelvesNode = this.FoodShelves.children[type];
            let startPos = this.moveNode.convertToNodeSpaceAR(targetNode.convertToWorldSpaceAR(cc.v3(0, 0, 0)));
            let endPos = this.moveNode.convertToNodeSpaceAR(FoodShelvesNode.convertToWorldSpaceAR(cc.v3(0, 0, 0)));

            cc.tween(targetNode)
                .set({ parent: this.moveNode, position: startPos })
                .to(0.5, { position: endPos })
                .call(() => {
                    UserManager.addMoney(this.FoodPriceListConfig[type], FoodShelvesNode);
                    this.checkIsFinish204(UserManager.getCurMoney())
                    this.scheduleOnce(() => {
                        targetNode.stopAllActions();
                        this.foodPool.put(targetNode);
                    });
                    // const incomePopUp = cc.instantiate(this.moveNode.getChildByName('incomePopUp'));
                    // incomePopUp.getComponent(cc.Label).string = "+" + this.FoodPriceListConfig[type] + "元";
                    // cc.tween(incomePopUp)
                    //     .set({ active: true, parent: this.moveNode, position: endPos, opacity: 255 })
                    //     .to(0.3, { position: cc.v3(endPos.x, endPos.y + 50, 0), scale: 1.5 })
                    //     .to(0.2, { position: cc.v3(endPos.x, endPos.y + 100, 0), scale: 1 })
                    //     .to(1, { position: cc.v3(endPos.x, endPos.y + 400, 0), opacity: 0 })
                    //     .removeSelf()
                    //     .start();
                })
                .start();
        }

        if (this.foodNodeBox.childrenCount <= this.GenerateFoodMaxNumber - this.GenerateFoodAddNumber) {
            let foodDataList = this.generateFoodData(this.GenerateFoodAddNumber);
            this.addFood(0, foodDataList);
        }
        //console.log(`this.foodPool:${this.foodPool.size()}`);
    }

    // 刷新食材
    onRefreshFoodsAd() {
        // //Common5.playEffect("sound/按键点击");
        this.node.getChildByName('inputBlack').active = true;
        let tab = {
            onClose: (finish) => {
                if (finish) {
                    User.setShowAdNum(User.getShowAdNum() + 1)
                    Common5.ReportDY("inLevel", `任务${TaskManager.getCurUnLockMainTaskId()}-AD-食材回收刷新食材`)
                    // Common5.ReportDY("inLevel", '食材回收-AD-刷新食材');
                    this.reportKey(() => {
                        GameReport.ADReport('食材回收刷新食材', 1);
                    })
                    this.refreshFoods(true);
                }
                else {
                    this.reportKey(() => {
                        GameReport.ADReport('食材回收刷新食材', 0);
                    })
                    Common5.showTips_custom("广告未观看完");
                }
            }, onFailed: () => { }
        }
        AppPlatform.playVideo_custom(tab);
    }
    checkIsFinish204(money) {
        let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id
        if (mainId == MainTaskIdEnum.MainTask_204) {
            if (money >= 500) {
                this.tipBox.active = true
            }
        }
    }
    qianWangClick() {
        this.tipBox.active = false
        TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_204)
        TaskManager.setCurUnLockMainTaskInfo(MainTaskIdEnum.MainTask_205)

        this.node.removeFromParent()
        this.node.destroy()
    }
}