import { Panel } from "../../module/views/Panel";
import { layers } from "../../module/views/layers";
import { sendTbNet, TbNetName } from "../TaoBaoNet";
import { GDispatcher } from "../Main";
import { G_EVENT } from "../common/G_EVENT";
import { getCurrentScene, hideWaiting, showToast, showWaiting } from "../../module/ctrls";
import { Item } from "../../module/views/Item";
import { Tools } from "../Tools";
import { RES } from "../../module/RES";
import Tween = FYGE.Tween;
import Ease = FYGE.Ease;
import Button = FYGE.Button;
import ScrollList = FYGE.ScrollList;
import Sprite = FYGE.Sprite;
import TextField = FYGE.TextField;
import MouseEvent = FYGE.MouseEvent;

// 任务类型（invites 、member、follow、browseGoods、orderGoods）
export enum TaskType {
    member = "member",
    follow = "follow",
    invites = "invites",
    orderGoods = "orderGoods",
    browseGoods = "browseGoods",
}

interface TaskData {
    /**
     * 任务类型
     */
    taskType: TaskType,
    /**
     * 加入会员的链接
     */
    value?: string,
    /**
     * 奖励的体力值
     */
    rewards: number
    /**
     * 当前完成次数
     */
    todayCompleteTimes: number
    /**
     * 需要完成次数
     */
    times: number
    /**
     * 待领取体力值
     */
    waitReceive: number
}

const taskItemData = {
    [TaskType.member]: {
        key: TaskType.member,
        title: '加入会员',
        desc: '加入会员得${rewards}体力'
    },
    [TaskType.follow]: {
        key: TaskType.follow,
        title: '关注店铺',
        desc: '关注店铺得${rewards}体力'
    },
    [TaskType.invites]: {
        key: TaskType.invites,
        title: '邀请好友(${done}/${total})',
        desc: '每邀请一个好友，可获得${rewards}体力'
    },
    [TaskType.orderGoods]: {
        key: TaskType.orderGoods,
        title: '完成下单(${done}/${total})',
        desc: '完成下单即可获得${rewards}体力'
    },
    [TaskType.browseGoods]: {
        key: TaskType.browseGoods,
        title: '每日浏览商品(${done}/${total})',
        desc: '浏览指定商品即可获得${rewards}体力'
    },
}

export class TaskPanel extends Panel {
    get groupNames() {
        return ["TaskPanel"]
    }

    get skinName() {
        return "TaskPanel"
    }

    private scroll: ScrollList;

    public showAni() {
        if (this.isShowing) return;
        this.isShowing = true;
        this.y = layers.stageHeight + this.height;
        Tween.get(this)
            .to({y: 80 - layers.stageOffsetY}, 500, Ease.quartOut)
            .call(() => {
                this.isShowing = false;
            });
    }

    closeBtn: Button;

    initUi() {
        this.scroll = this.addChild(new ScrollList(
            TaskItem,
            700, 180,
            700, 878
        ));
        this.scroll.position.set(25, 670);
    }

    start(data) {
        super.start();
        this.updateTask();
    }

    public updateTask() {
        showWaiting();
        sendTbNet(TbNetName.getTaskList, {},
            (success, res) => {
                hideWaiting();
                if (!success) return;
                console.log(res);

                for (let i = res.data.length - 1; i >= 0; i--) {
                    const v = res.data[i];
                    if ((v.taskType == TaskType.member || v.taskType == TaskType.follow)
                        && v.status == 3) {
                        res.data.splice(i, 1);
                    }
                }
                console.log(res.data);

                // this.scroll.view.children.length = 0;
                this.scroll.updateData(res.data, true);

            }
        );
    }

    initEvents() {
        super.initEvents();
        GDispatcher.addEventListener(G_EVENT.ON_SHOW, this.updateTask, this);
        GDispatcher.addEventListener(G_EVENT.UPDATE_TASK, this.updateTask, this);
    }

    removeEvents() {
        super.removeEvents();
        GDispatcher.removeEventListener(G_EVENT.ON_SHOW, this.updateTask, this);
        GDispatcher.removeEventListener(G_EVENT.UPDATE_TASK, this.updateTask, this);
    }
}

class TaskItem extends Item {

    private icon: Sprite;
    private title: TextField;
    private desc: TextField;

    private getBtn: Button;
    private taskBtn: Button;

    data: any;

    constructor() {
        super();
    }

    public initUi(data?) {
        this.addChild(Tools.getSprite('task_item_bg.png'));
        this.icon = this.addChild(new Sprite());
        this.icon.position.set(25, 30);

        this.title = this.addChild(Tools.getText(
            '关注店铺', 30, '#df5942'
        ));
        this.title.bold = true;
        this.title.position.set(146, 46);

        this.desc = this.addChild(Tools.getText(
            '加入会员得x体力', 24, '#666666'
        ));
        this.desc.bold = true;
        this.desc.position.set(145, 92);

        this.getBtn = this.addChild(new Button(RES.getRes('task_get_btn.png')));
        this.taskBtn = this.addChild(new Button(
            RES.getRes(`去完成.png`),
            RES.getRes(`去完成.png`),
            RES.getRes(`去完成灰.png`)
        ));

        this.getBtn.position.set(501, 43);
        this.taskBtn.position.set(501, 43);

        this.getBtn.addEventListener(MouseEvent.CLICK, this.clickGet, this);
        this.taskBtn.addEventListener(MouseEvent.CLICK, this.clickTask, this);

    }

    public initData(id: number, data: any) {
        if (id < 0 || !data) return;

        this.data = data;

        const {
            rewards,
            taskType,
            completeTimes,
            waitReceive,
            todayCompleteTimes,
            times,
            status,
        } = data;

        this.icon.texture = RES.getRes(`${taskType}_icon.png`);
        this.title.text = taskItemData[taskType].title
            .replace('${done}', todayCompleteTimes)
            .replace('${total}', times);
        this.desc.text = taskItemData[taskType].desc
            .replace('${rewards}', rewards);

        this.taskBtn.changeTexture(
            RES.getRes(`${taskType}_btn_en.png`),
            RES.getRes(`${taskType}_btn_en.png`),
            RES.getRes(`${taskType}_btn_dis.png`)
        );

        if (+status == 2) {
            this.getBtn.visible = true;
            this.taskBtn.visible = false;
        } else if (+status == 3) {
            this.getBtn.visible = false;
            this.taskBtn.visible = true;
            this.taskBtn.enabled = false;
        } else if (+status == 1) {
            this.getBtn.visible = false;
            this.taskBtn.visible = true;
            this.taskBtn.enabled = true;
        }

    }

    private clickGet() {
        this.getBtn.mouseEnable = false;
        sendTbNet(TbNetName.receiveTaskRewards, {taskType: this.data.taskType},
            (success, res) => {
                this.getBtn.mouseEnable = true;
                if (!success) return;
                showToast(`任务完成，体力值+${res.data.power}！`);
                Tools.propInfo.power += res.data.power;
                getCurrentScene().updateScene();
                GDispatcher.dispatchEvent(G_EVENT.UPDATE_TASK);
            }
        );
    }

    private clickTask() {
        switch (this.data.taskType) {
            case TaskType.member:
                sendTbNet(TbNetName.navigateToOutside, {url: this.data.url});
                break;
            case TaskType.browseGoods:  // 浏览商品
                sendTbNet(TbNetName.navigateTo, {
                    url: '/pages/goodsPage/goodsPage?taskType=browseGoods&itemIds=' + this.data.itemIds
                });
                break;
            case TaskType.follow:
                GDispatcher.removeAllEventListenerByType(TbNetName.favorShop);
                sendTbNet(TbNetName.favorShop, {},
                    (fs, fr) => {
                        if (!fs) return;
                        sendTbNet(TbNetName.doFollowTask, {taskType: this.data.taskType},
                            (cs, cr) => GDispatcher.dispatchEvent(G_EVENT.UPDATE_TASK)
                        );
                    }, true
                );
                break;
            case TaskType.invites:
                sendTbNet(TbNetName.addStats, {type: 'invite'}, () => {
                }, true);
                sendTbNet(TbNetName.showSharePanel, {openId: Tools.globalData.openId}, () => {
                }, true);
                break;
            case TaskType.orderGoods:
                /// TODO 修改跳到店铺首页 2020.10.14
                // sendTbNet(TbNetName.navigateTo, {
                //     url: '/pages/goodsPage/goodsPage?taskType=orderGoods&itemIds=' + this.data.itemIds
                // });
                sendTbNet(TbNetName.navigateToOutside, {url: 'https://popmart.m.tmall.com'});
                break;
        }
    }

}
