import { Rectangle } from '../../engine/2d/math/Rectangle';

import { Tool } from "../Tools";
import { Button } from "../../engine/2d/ui/Button";
import { MouseEvent } from "../../engine/2d/events/MouseEvent";
import { Panel } from "../../module/views/Panel";
import { RES } from "../../module/RES";
import { Sprite } from "../../engine/2d/display";
import { Graphics } from '../../engine/2d/graphics';
import { layers } from '../../module/views/layers';
import Tween from '../../engine/tween/Tween';
import { sendTbNet, TbNetName } from '../TaoBaoNet';
import { showWaiting, hideWaiting, showPanel, showToast } from '../../module/ctrls';
import { Texture } from '../../engine/2d/texture';
import { GDispatcher } from '../../engine/2d/events';
import { TaskCompletePanel } from './TaskCompletePanel';
import { TaskType, getTools } from '../commonNet';



interface TaskData {
    taskName: TaskType,
    isComplete: boolean,
    taskDrawStatus: number
}

const flushTaskEvent = "flushTaskEvent";

/**
 * 任务弹框，还没好
 */
export class TaskPanel extends Panel {
    get groupNames() { return ["taskPanel"] }

    closeBtn: Button;

    [TaskType.doFollowShop]: CusButton;
    [TaskType.doInvite]: CusButton;
    [TaskType.doCollect]: CusButton;
    [TaskType.doOrder]: CusButton;

    //为了toast提示：成功完成下单任务，可领取道具大礼包
    toShowMsg: number;

    initUi() {
        //底部适配,原先都是居中的，
        this.y = (layers.stageHeight - 1624) / 2
        //背景
        this.addChild(Tool.addSprite("taskPanelBg.png")).position.set(0, 1624 - 1075);
        //关闭按钮
        this.closeBtn = new Button(RES.getRes("comCloseBtn.png"));
        this.closeBtn.position.set(681, 870);
        this.addChild(this.closeBtn);
        //四个按钮，先默认状态，然后start里刷任务接口
        this[TaskType.doFollowShop] = this.addChild(new CusButton(TaskType.doFollowShop))
        this[TaskType.doFollowShop].position.set(561, 1022);
        this[TaskType.doCollect] = this.addChild(new CusButton(TaskType.doCollect))
        this[TaskType.doCollect].position.set(561, 1022 + 153);
        this[TaskType.doInvite] = this.addChild(new CusButton(TaskType.doInvite))
        this[TaskType.doInvite].position.set(561, 1022 + 153 * 2);
        this[TaskType.doOrder] = this.addChild(new CusButton(TaskType.doOrder))
        this[TaskType.doOrder].position.set(561, 1022 + 153 * 3);

    }

    //动画重写，从下往上
    showAni() {
        var oriY = this.y;
        this.y += this.getLocalBounds().height;
        Tween.get(this)
            .to({ y: oriY }, 500)
    }

    start(data) {
        super.start();
        //监听任务回来的事件
        GDispatcher.addEvent(flushTaskEvent, this.updateTask, this)
        //刷新任务数据
        this.flushTask();
    }
    updateTask() {
        this.flushTask();
        //获取道具数量，更新道具数量
        getTools();
    }
    async flushTask() {
        showWaiting();
        var list = await getTaskList().catch(() => { });//加了catch,后面逻辑继续走
        hideWaiting();
        if (!list) return
        //修改按钮状态
        for (var i = 0; i < list.length; i++) {
            var l = list[i];
            //未完成!l.isComplete
            if (l.taskDrawStatus == 0) {
                this[l.taskName].canGetStatus = false;
                this[l.taskName].enabled = true;
                if (l.taskName == TaskType.doOrder) this.toShowMsg = 1//标记是没完成的
            }
            //三个状态，到时确认
            else if (l.taskDrawStatus == 1) {//待领取状态
                this[l.taskName].canGetStatus = true;
                this[l.taskName].enabled = true;
                //额外判断下单，原先是1，且待领取状态，
                if (l.taskName == TaskType.doOrder && this.toShowMsg === 1) {
                    this.toShowMsg = 2;
                    showToast("成功完成下单任务，可领取道具大礼包")
                }
            }
            else if (l.taskDrawStatus == 2) {//已领取状态
                this[l.taskName].enabled = false;
            }

        }
    }



    initEvents() {
        this.onClick(this.closeBtn, this.onClick_closeBtn, this)
    }

    onClick_closeBtn() {
        this.hidePanel();
    }

    removeEvents() {
        this.removeClick(this.closeBtn, this.onClick_closeBtn, this)
        GDispatcher.removeEvent(flushTaskEvent, this.updateTask, this)
    }

}

function getTaskList(): Promise<TaskData[]> {
    return new Promise((resolve, reject) => {
        sendTbNet(
            TbNetName.getTaskList,
            { activityId: Tool.globalData.activityId },
            (s, res) => {
                if (s) {
                    resolve(res.data.list)
                } else {
                    reject(null);
                }
            }
        )
    })
}

/**
 * 3种状态的按钮
 * 除了邀请没有disable，其他都一样
 */
class CusButton extends Button {
    private type: TaskType
    private _canGetStatus: boolean;
    get canGetStatus() {
        return this._canGetStatus
    }
    set canGetStatus(value) {
        this._canGetStatus = value;
        var t: [Texture, Texture] = getTexture(this.type)
        if (value) {//能领取时换图
            t = [RES.getRes("lingqujiangli.png"), t[1]]
        }
        this.changeTexture(t[0], t[0], t[1])
    }
    constructor(type: TaskType) {
        var t = getTexture(type)
        super(t[0], t[0], t[1])
        this.type = type;
        //事件统一写吧
        this.addEventListener(MouseEvent.CLICK, this.onClick, this)
    }

    onClick() {
        if (this.canGetStatus) {//能领取，发接口
            showWaiting();
            sendTbNet(
                TbNetName.getToolsByType,
                { activityId: Tool.globalData.activityId, taskName: this.type },
                (s, res) => {
                    hideWaiting();
                    if (s) {
                        showPanel(TaskCompletePanel, { type: this.type, num: res.data.inviteSuccessCount })
                        GDispatcher.dispatchEvent(flushTaskEvent)
                    }
                }
            )
        } else {//发对应任务方法
            //都弄个延时
            this.mouseEnable = false;
            setTimeout(() => { this.mouseEnable = true; }, 1000)
            switch (this.type) {
                case TaskType.doFollowShop:
                    sendTbNet(
                        TbNetName.navigateToOutside,
                        { url: "" },//关注店铺路径路径待写
                        () => { },
                        true
                    )
                    break;
                case TaskType.doCollect:
                    sendTbNet(
                        TbNetName.navigateTo,
                        { url: '/pages/collectGoods/collectGoods' },//收藏页面路径待写
                        () => { },
                        true
                    );
                    break;
                case TaskType.doInvite:
                    sendTbNet(
                        TbNetName.invite,
                        undefined,
                        () => { },
                        true
                    );
                    break;
                case TaskType.doOrder:
                    sendTbNet(
                        TbNetName.navigateTo,
                        { url: '/pages/orderGoods/orderGoods' },//下单页面路径待写
                        () => { },
                        true
                    );
                    break;
            }
            if (this.type == TaskType.doFollowShop) {//关注店铺
                sendTbNet(TbNetName.favorShop, {}, () => {
                    GDispatcher.dispatchEvent(flushTaskEvent)
                }, true)
            }
            else if (this.type == TaskType.doCollect || this.type == TaskType.doOrder) {
                //都需要添加事件，回来时，派发事件刷任务接口
                let fun = () => {
                    GDispatcher.removeEvent(TbNetName.returnGame, fun, this)
                    GDispatcher.dispatchEvent(flushTaskEvent)
                }
                GDispatcher.addEvent(TbNetName.returnGame, fun, this)
            }
        }
    }



}

function getTexture(type: TaskType): [Texture, Texture] {
    var tup: Texture, tdis: Texture;
    switch (type) {
        case TaskType.doFollowShop:
            tup = RES.getRes("quguanzhu.png")
            tdis = RES.getRes("yiguanzhu.png")
            break;
        case TaskType.doCollect:
            tup = RES.getRes("qushoucang.png")
            tdis = RES.getRes("yilingqu.png")
            break;
        case TaskType.doInvite:
            tup = RES.getRes("quyaoqing.png")
            break;
        case TaskType.doOrder:
            tup = RES.getRes("quxiadan.png")
            tdis = RES.getRes("yilingqu.png")
            break;
    }
    return [tup, tdis];
}