const Api = require('../net/Api');
const DWTool = require("../utils/DWTool");
const itemList = require('../data/item');
const GameModule = require("../utils/GameModule");
const GameNotificationKey = require('../utils/GameEnum').GameNotificationKey;

cc.Class({
    extends: cc.Component,

    properties: {
        questNode: cc.Node,
        questFrames: {
            tooltip: '任务图标',
            default: [],
            type: [cc.SpriteFrame],
        },
        questBtns: [cc.Node],
        starNode: {
            tooltip: '星星节点',
            default: [],
            type: [cc.Node]
        },
        starFrames: {
            tooltip: '星星图片素材',
            default: [],
            type: [cc.SpriteFrame]
        },
        progressLabel: {
            tooltip: '奖励数量',
            default: null,
            type: cc.Label
        },
        progressBar: cc.ProgressBar,
        questTitle: {
            tooltip: '任务标题',
            default: null,
            type: cc.Label
        },
        qusetMsg: {
            tooltip: '任务说明',
            default: null,
            type: cc.Label
        }
    },

    onLoad () {
        this.giftMap = ['diamond', 'coin', 'ticket']
    },

    start () {

    },

    init (parent, tasks, sn, questIndex) {
        this.parent = parent
        this.quest = parent.quest
        this.tasks = tasks
        this.questIndex = questIndex
        sn = this.sn = parseInt(sn)

        // 设置当前任务图标
        this.questNode.getComponent('cc.Sprite').spriteFrame = this.questFrames[this.questIndex]

        // 设置当前任务等级内容
        this._setTaskItem(sn)
    },

    _setTaskItem (sn) {
        let task = this.task = this.tasks.find(n => {
            if(sn == 0) {
            return n.sn == 1
        } else {
            return n.sn == sn
        }
    })
        if(sn == 5 && task.status == 2) {
            this._setMaxItem()
        } else {
            let level = sn == 0 ? 0 : sn - 1
            let nameLevelMap = ['I', 'II', 'III', 'IV', 'V']

            // 设置当前任务标题
            this.questTitle.string = `${task.name}(${nameLevelMap[level]})`

            // 设置当前任务说明内容
            this.qusetMsg.string = task.msg.replace('${num}', task.totalAimValue)

            // 设置当前任务星级
            this._setStarLevel(level)

            // 设置任务阶段进度条
            let aimValue = task.aimValue > task.totalAimValue ? task.totalAimValue : task.aimValue
            this._setProgress(aimValue, task.totalAimValue)

            this.giftItem = Object.assign({
                itemCount: task.itemCount
            }, itemList.find(n => {
                return n.id == task.itemId
            }))

            // 设置任务领取按钮
            this._setGiftBtn(task.status)
        }
    },

    _setMaxItem () {
        let task = this.tasks[4]

        // 设置当前任务标题
        this.questTitle.string = `${task.name}(V)`

        // 设置当前任务说明内容
        this.qusetMsg.string = task.msg.replace('${num}', task.totalAimValue)

        // 设置当前任务星级
        this._setStarLevel(5)

        // 设置任务阶段进度条
        let aimValue = task.aimValue > task.totalAimValue ? task.totalAimValue : task.aimValue
        this._setProgress(aimValue, task.totalAimValue)

        // 设置任务领取按钮
        this._setGiftBtn(2)
    },

    /**
     * 领取按钮点击
     */
    handleGiftBtn () {
        Api.httpPost({
            url: "/task/gain.do",
            data: {
                taskId: this.task.taskId,
                sn: this.task.sn
            },
            success: (res) => {

                if (res.clickMt) {
                    if (GameModule.userInfo.perpetualClickMt != parseFloat(res.clickMt)) {
                        GameModule.userInfo.perpetualClickMt = parseFloat(res.clickMt);
                        GameEvent.fire(GameNotificationKey.UpBuildingLevel);
                    }
                }

                if (res.mt) {
                    if (GameModule.userInfo.perpetualMt != parseFloat(res.mt)) {
                        GameModule.userInfo.perpetualMt = parseFloat(res.mt);
                        GameModule.userInfo.refreshSecondText();
                    }
                }

            let updatRes = {
                coin: 0,
                diamond: 0,
                ticket: 0
            }
            if(this.giftItem.id == 10001) {
                updatRes.coin = this.giftItem.itemCount;
            }

            if(this.giftItem.id == 10002) {
                updatRes.diamond = this.giftItem.itemCount;
            }

            if(this.giftItem.id == 10003) {
                updatRes.ticket = this.giftItem.itemCount;
            }

            // 更新全局userInfo
            this.quest.updateUserInfo(updatRes.coin, updatRes.diamond, updatRes.ticket)

            // 显示领取奖品动画
            let showFrame = this.giftItem.giftFrame;
            let showText = `${this.giftItem.name} x ${this.giftItem.itemCount}`
            this.quest.showMainGift(showFrame, showText)

            // 领取成功，更新当前按钮状态到下一阶段
            if(this.sn < 5) {
                this.sn += 1
                this._setTaskItem(this.sn)
            } else {
                this._setMaxItem()
            }
        },
            fail: () => {
                // 领取失败
            }
        })
    },

    /**
     * 设置任务领取状态按钮
     * @param {number} status 任务状态[0 : 未完成, 1 : 完成可领取, 2 : 完成已领取]
     */
    _setGiftBtn (status) {
        // console.log(this.giftItem);

        this.questBtns.forEach(n => {
            n.active = false
        })

        let btn
        // 根据状态选择按钮
        switch (status) {
            case 0:
                btn = this.questBtns[1]
                break;
            case 1:
                btn = this.questBtns[0]
                break;
            case 2:
                btn = this.questBtns[2]
                break;
            default:
                break;
        }

        btn.active = true

        // 设置图标和数量
        if(status != 2) {
            if (this.giftItem.picId) {
                DWTool.loadResSpriteFrame(`./textures/item/${this.giftItem.picId}`)
                    .then((spriteFrame) => {
                    let countNode = cc.find('/count_label', btn)
                    let spriteNode = cc.find('/sprite', btn)

                    this.giftItem.giftFrame = spriteFrame

                    countNode.getComponent('cc.Label').string = `${DWTool.coinParseNoFixed(this.giftItem.itemCount)}`
                    spriteNode.getComponent('cc.Sprite').spriteFrame = spriteFrame
                }).catch((err) => {
                    console.log(err);
                });
            }
        }
    },

    /**
     * 设置任务阶段进度条
     * @param {number} current 当前值
     * @param {number} total 阶段总值
     */
    _setProgress (current, total) {
        let _progress = (current / total).toFixed(1)
        // console.log(_progress);
        this.progressBar.progress = _progress
        this.progressLabel.string = `${current} / ${total}`
    },

    /**
     * 设置当前任务星级
     * @param {number} level 星级
     */
    _setStarLevel (level) {
        this.starNode.forEach((node, index) => {
            if(index < level) {
            node.getComponent('cc.Sprite').spriteFrame = this.starFrames[1]
        } else {
            node.getComponent('cc.Sprite').spriteFrame = this.starFrames[0]
        }
    })
    }
});
