import { GetStartStatusData } from './../../libs/tw/data/game/doStart/GetStartStatusData';
import { GetBuriedData } from './../ctrls/GetBuriedData';
import { Buried } from './../../libs/tw/util/Buried';
import { GFun } from './../../libs/tc/util/GFun';
import { GDispatcher } from './../../libs/tc/util/GDispatcher';

import { ModuleTypes } from './../types/sceneTypes';
import { NetManager } from './../../libs/tw/manager/NetManager';

import { NetName } from './../../libs/tw/enum/NetName';

import { DataManager } from '../../libs/tw/manager/DataManager';
import PanelCtrl from '../ctrls/panelCtrl';
import Loading from '../loading/Loading';
import OppoShareCtrl from '../ctrls/oppoShareCtrl';
import StartScene from './StartScene';



export class TaskRenderer extends eui.Component {
    get TaskList() { return DataManager.ins.getData(NetName.OPPO_QUERYTASKLIST) && DataManager.ins.getData(NetName.OPPO_QUERYTASKLIST).data && DataManager.ins.getData(NetName.OPPO_QUERYTASKLIST).data.task || [] }
    get baseInfo() { return DataManager.ins.getData(NetName.OPPO_JOIN1_INDEX) && DataManager.ins.getData(NetName.OPPO_JOIN1_INDEX).data || null }
    // get skinKey() { return "TaskRenderer" }
    public get groupName() { return 'startscene' }

    public taskInfo
    constructor() {
        super()
        this.skinName = "TaskRendererSkin"
        this.width = 930;
        this.height = 100;
        this.init()

    }

    //     {
    //     "success": "true",
    //         "data": [
    //             {
    //                 "taskId": "1",
    //                 "taskName": "阅读增加抽奖机会",
    //                 "taskDesc": "阅读增加抽奖机会",
    //                 "status": 1,
    //                 "taskUrl": "http: //www.baidu.com",
    //                 "type": 1,
    //                 "dayLimit": 2
    //             }
    //         ]
    // }
    // 初始化任务渲染组件

    init() {
        console.log('renwu', this.TaskList);

        this.TaskList.forEach((task, idx) => {
            if (task.type !== 0) {
                let exposure = GetBuriedData(5, idx + 1)
                NetManager.ins.showLog(exposure)
                let taskItem = new TaskItem(task, idx)
                taskItem.y = idx * 230 + 100
                this.height += 230
                taskItem['todoBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_todoBtn.bind(this, taskItem), this)
                taskItem['completeBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_todoBtn.bind(this, taskItem), this)
                this.addChild(taskItem)
            }
        });

        GDispatcher.addEvent("updateTaskList", this.updateTaskList, this)
    }

    updateTaskList() {
        // 更新任务列表

        for (let i = this.$children.length - 1; i > 0; i--) {
            if (this.arrContain(this.$children, this.$children[i])) {
                this.removeChild(this.$children[i])
            }
        }
        this.TaskList.forEach((task, idx) => {
            if (task.type !== 0) {
                let taskItem = new TaskItem(task, idx)
                taskItem.y = idx * 230 + 100
                this.height += 230
                taskItem['todoBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_todoBtn.bind(this, taskItem), this)
                taskItem['completeBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_todoBtn.bind(this, taskItem), this)
                this.addChild(taskItem)
            }
        });
    }

    async onTap_todoBtn(taskItem) {

        let taskType = taskItem.taskType;
        let exposure = GetBuriedData(5, taskItem.taskIdx + 1)
        NetManager.ins.clickLog(exposure)

        if (this.baseInfo && this.baseInfo.collectStatus == 5) {
            console.log("活动结束");
            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: "活动已结束" })
            return
        }

        switch (taskType) {
            case TaskTypes.Click:
                console.log("点击");
                Loading.instace.show()
                NetManager.ins.complete(() => {
                    Loading.instace.hide()
                    if (taskItem.taskUrl) {
                        //let urlString:string = taskItem.taskUrl;
                        //let taskUrl = urlString.split('=')[1];
                        window.location.href = taskItem.taskUrl;
                        //window['JSCallJava'].analyzeInnerLink(taskUrl);
                        setTimeout(() => {
                            //window.location.reload()
                            this.upDatePanel();
                        }, 1500);
                    } else {
                        this.updateUI()
                    }
                }, taskItem.taskId, taskItem.taskType)
                break;
            case TaskTypes.Focus:
                console.log("关注");
                // Loading.instace.show()
                // NetManager.ins.complete((s) => {
                //     Loading.instace.hide()
                //let urlString:string = taskItem.taskUrl;
                //let taskUrl = urlString.split('=')[1];
                window.location.href = taskItem.taskUrl;
                //window['JSCallJava'].analyzeInnerLink(taskUrl);
                // }, taskItem.taskId, taskItem.taskType)
                break;
            case TaskTypes.Help:
                console.log("助力");
                if (GFun.getIsWxClient()) {
                    //PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'点击右上角，喊好友来集卡吧～'});
                    //PanelCtrl.instance.show(ModuleTypes.WXSHARE_PANEL)
                } else {
                    console.log("开始调用助力方法");
                    OppoShareCtrl.instance.share();
                    PanelCtrl.instance.show(ModuleTypes.WXSHARE_PANEL);
                }
                break;
            case TaskTypes.Url:
                console.log("跳转");
                
                //window['JSCallJava'].analyzeInnerLink(taskItem.taskUrl.split('=')[1]);
                window.location.href = taskItem.taskUrl;
                setTimeout(() => {
                    this.upDatePanel();
                    //window.location.reload()
                }, 1500);
                break;
            case TaskTypes.Write:
                console.log("写稳字");
                PanelCtrl.instance.show(ModuleTypes.WRITE_PANEL, { taskId: taskItem.taskId, taskType: taskType })
                break;
        }

    }

    updateUI() {

        NetManager.ins.getBaseInfo((s) => {
            if (!s) {
                Loading.instace.hide()
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: "更新卡片失败，请稍后重试~" })
                return
            }
            GDispatcher.dispatchEvent("updateCard")
            // 调用任务信息接口更新任务
            NetManager.ins.queryTaskList((ss) => {
                if (!ss) {
                    Loading.instace.hide()
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: "更新任务失败，请稍后重试~" })
                    return
                }

                Loading.instace.hide()
                GDispatcher.dispatchEvent("updateTaskList")

            })
        })
    }

    arrContain(arr: any[], e: any) {
        let mark = false;
        arr.forEach((ee) => {
            if (ee == e) {
                mark = true;
            }
        })

        return mark;
    }

    handleError(result) {
        Loading.instace.hide()
        let { code } = result
        let msg = ""
        switch (code) {
            case "100001":
                msg = "请先登录~"
                break
            case "100101":
                msg = "活动已结束~"
                break
            case "100102":
                msg = "入参错误~"
                break
            case "300401":
                msg = "任务类型错误~"
                break
            case "300402":
                msg = "任务已完成，不需要再操作~"
                break
            default:
                msg = "请尝试再次提交~"
                break
        }

        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: msg })
    }
     upDatePanel(){
        NetManager.ins.queryTaskList((success, result) => {
            if (!success) {
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: result.message })
            }
            NetManager.ins.getBaseInfo((success2, result2) => {
                if (!success2) {
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: result2.message })
                }
                NetManager.ins.getSubscibeState((success3, result3) => {
                    Loading.instace.hide();
                    if (!success3) {
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: result2.message })
                    }
                    let data = { baseinfo: result2.data, taskinfo: result.data, pushstatus: result3.data.status };
                    StartScene.instance.mData = data;
                    StartScene.instance.initUI();
                })

            })
        })
     }
}

// 任务项
export class TaskItem extends eui.Component {

    public todoBtn: eui.Button;
    public completeBtn: eui.Button;
    public taskNameTxt: eui.Label;
    public taskDescTxt: eui.Label;
    public taskImg: eui.Image;


    taskType: TaskTypes = TaskTypes.Click
    taskIcon: string;
    taskId: number;
    taskName: string = "";
    taskDesc: string = "";
    taskStatus: number = TaskStatus.Complete;
    taskUrl: string = ""
    taskDayLimit: number = 0;
    taskIdx: number = 0

    // get skinKey() { return "TaskItem" }
    public get groupName() { return 'startscene' }

    constructor(data, idx) {
        super()

        this.skinName = "TaskItemSkin"
        this.taskId = data.taskId
        this.taskIdx = idx;
        this.taskName = data.taskName
        this.taskUrl = data.taskUrl
        this.taskDesc = data.taskDesc
        this.taskIcon = data.icon
        this.taskDayLimit = data.dayLimit
        // 任务类型：0-关注公众号 1-开发者跳转 2-开发者点击 3-写稳字 4-助力

        switch (data.type + "") {
            case "0":
                this.taskType = TaskTypes.Focus
                break;
            case "1":
                this.taskType = TaskTypes.Url
                break;
            case "2":
            default:
                this.taskType = TaskTypes.Click
                break;
            case "3":
                this.taskType = TaskTypes.Write
                break;
            case "4":
                this.taskType = TaskTypes.Help
                break;
        }

        // 任务状态：0 - 未完成 1 - 已完成
        switch (data.status + "") {
            case "0":
            default:
                this.taskStatus = TaskStatus.ToDo
               if(this.taskType == TaskTypes.Help && GFun.getIsWxClient()){
                this.todoBtn.visible = false;
                this.completeBtn.visible = false;
               }else{
                this.todoBtn.visible = true;
                this.completeBtn.visible = false;
               }
           
                break;
            case "1":
                this.taskStatus = TaskStatus.Complete
                if(this.taskType == TaskTypes.Help){
                    this.todoBtn.visible = false;
                    this.completeBtn.visible = false;
                }else{
                    this.todoBtn.visible = false;
                    this.completeBtn.visible = true;
                }

                break;
        }


        this.taskNameTxt.text = this.taskName;
        this.taskDescTxt.text = this.taskDesc;
        if (this.taskIcon) {
            this.taskImg.source = this.taskIcon;
        }


    }


}



// 1	浏览指定页面（帖子 / 话题 / 模块 / 商品等）	点击跳转按钮就完成
// 2	评论指定数量帖子	访问接口
// 3	点赞指定数量帖子	访问接口
// 4	指定话题下发帖	访问接口
// 5	关注指定数量的用户	访问接口
// 6	参与指定活动	点击跳转按钮就完成
// 7	观看视频	点击跳转按钮就完成
// 任务类型：0-关注公众号 1-开发者跳转 2-开发者点击 3-写稳字 4-助力
export enum TaskTypes {
    Focus,
    Url,
    Click,
    Write,
    Help
}


// 任务状态：0 - 未完成 1 - 已完成
export enum TaskStatus {
    ToDo,
    Complete
}