const Api = require('../net/Api');
const DWTool = require("../utils/DWTool");

cc.Class({
    extends: cc.Component,

    properties: {
        questNode: cc.Node,
        questFrames: {
            tooltip: '任务图标',
            default: [],
            type: [cc.SpriteFrame],
        },
        questBtns: [cc.Node],
        giftNode: {
            tooltip: '奖励图标节点',
            default: null,
            type: cc.Node
        },
        giftCounts: {
            tooltip: '奖励数量',
            default: null,
            type: cc.Label
        },
        giftFrames: {
            tooltip: '奖励图片素材',
            default: [],
            type: [cc.SpriteFrame]
        },
        questTitle: {
            tooltip: '任务标题',
            default: null,
            type: cc.Label
        },
        questDetail: {
            tooltip: '任务内容',
            default: null,
            type: cc.Label
        },
        questAct: {
            tooltip: '活跃度奖励',
            default: null,
            type: cc.Label
        }
    },

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

    },

    start () {

    },

    init (parent, task, questIndex) {
        this.parent = parent
        this.quest = parent.quest
        this.task = task
        this.questIndex = questIndex
        this.questBtns[task.state].active = true

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

        // 设置任务标题
        this.questTitle.string = task.title

        // 设置任务说明内容
        this.questDetail.string = task.desc

        // 设置任务活跃度奖励
        this.questAct.string = `活跃度 + ${task.degree}`

        // 设置任务奖励类型及数量
        this._setGift()
    },

    /**
     * 设置任务奖励类型及数量
     */
    _setGift () {
        let _count = 0
        let _type = ''
        let _sprite = null

        this.giftMap.forEach((value, index) => {
            if(this.task[value] > 0) {
                _count = this.task[value]
                _type = value
                _sprite = this.giftFrames[index]
            }
        })

        this.giftNode.getComponent('cc.Sprite').spriteFrame = _sprite
        this.giftCounts.string = `x ${DWTool.coinParseNoFixed(_count)}`
    },

    /**
     * 领取按钮点击
     */
    handleGiftBtn () {
        Api.httpPost({
            url: "/daily/getDailyTaskReward",
            data: {
                id: this.task.id
            },
            success: (res) => {
            // 更新全局userInfo
            this.quest.updateUserInfo(this.task.coin, this.task.diamond, this.task.ticket)

        // 领取成功，更新状态
        this.parent.updateStatus(this.task)
        this.questBtns[this.task.state].active = false;
        this.questBtns[2].active = true;

        // 显示领取奖品动画
        this.quest.showActGift({
            ticket: this.task.ticket,
            diamond: this.task.diamond,
            coin: this.task.coin
        })
    },
        fail: () => {
            // 领取失败

        }
    })
    }
});
