import { Decorator } from "../Decorator/Decorator";
import Panel from "../views/Panel";
import MItem from "../components/MItem";
import MButton from "../MUI/MButton";
import Net from "../Global/Net";
import { MConfigs } from "../Global/MConfigs";
import { NetUtils } from "../Global/NetUtils";

interface ItemData {
    index: number,
    content: string,
    btnText: string,
    finishFlag: boolean,
    taskCode: string,
    context: TaskPanel
}

@Decorator.ClassName("TaskPanel")
export default class TaskPanel extends Panel {
    public dataGroup: eui.DataGroup;
    public btnClose: MButton;

    onSkinComplete() {
        super.onSkinComplete();
        this.btnClose.onTap(this, () => this.hidePanel());

        this.dataGroup.itemRenderer = class extends MItem {
            public labelNum: eui.Label;
            public labelContent: eui.Label;
            public btnDo: MButton;
            data: ItemData;

            onSkinComplete() {
                this.btnDo.onOnceTap(this, (resume) => {
                    const timestamp = NetUtils.getTimestamp();
                    Net.sendPost(Net.Url.taskComplete, {
                        taskCode: this.data.taskCode,
                        timestamp: timestamp,
                        token: NetUtils.md5(this.data.taskCode + timestamp + "dui88")
                    }, () => {
                        this.data.context.refresh();
                    }, () => { resume() });
                });
            }

            dataChanged() {
                this.labelNum.text = "任务" + this.data.index;
                this.labelContent.text = this.data.content;
                this.btnDo.label = this.data.btnText;
                if (this.data.finishFlag == true) {
                    this.btnDo.enabled = false;
                    this.btnDo.labelDisplay.textColor = 0xbeafad;
                }
            }
        }

        this.refresh();
    }

    public refresh() {
        Net.sendGet(Net.Url.taskData, undefined, (res) => {
            const taskList = res.data.taskList as { taskCode: string, finishFlag: boolean }[]

            let arr: ItemData[] = [];
            for (let i = 0; i < taskList.length; i++) {
                const config = MConfigs.task[taskList[i].taskCode];
                if (typeof config == "undefined") {
                    console.error("task config error");
                    continue;
                }
                arr.push({
                    index: i + 1,
                    content: config.content,
                    taskCode: config.taskCode,
                    finishFlag: taskList[i].finishFlag,
                    btnText: config.btnText,
                    context: this
                });
            }
            this.dataGroup.dataProvider = new eui.ArrayCollection(arr);
        }, () => { this.hidePanel() });
    }
}