import { _decorator, Component, Label, Node, Sprite } from 'cc';
import { base_ui } from '../../fw/base_ui';
import { tools } from '../../tools';
import { userDataManager } from '../../manager/userDataManager';
import { bag_list_item_data } from '../../data';
import { ClientEvent } from '../../lib/clientEvent';
import { config } from '../../config';
import { http } from '../../http';
import { uiManager } from '../../manager/uiManager';
const { ccclass, property } = _decorator;

@ccclass('bag_avatar_preview')
export class bag_avatar_preview extends base_ui {
    @property(Node) img_avatar:Node = null
    @property(Node) img_avatar_border:Node = null
    @property(Node) lab_name:Node = null
    @property(Node) btn_close:Node = null
    @property(Node) btn_true:Node = null
    @property(Node) lab_true:Node = null
    private m_data:bag_list_item_data = null
    private m_true_cb = null
    start() {
        this.onButtonListen(this.btn_close, ()=>{
            this.close()
        })
        this.onButtonListen(this.btn_true, ()=>{
            this.requestSetAvatar()
        })
    }

    initView(data:bag_list_item_data, true_cb) {
        this.m_data = data
        this.m_true_cb = true_cb
        tools.loadRemoteImg(userDataManager.user_data.avatarUrl, (d)=>{
            this.img_avatar.getComponent(Sprite).spriteFrame = d.sf
        })
        if(data.icon && data.icon.length>0) {
            tools.loadRemoteImg(data.icon, (d)=>{
                this.img_avatar_border.getComponent(Sprite).spriteFrame = d.sf
            })
        }
        this.lab_name.getComponent(Label).string = data.name
        if(data.usage_status==1) {
            this.lab_true.getComponent(Label).string = '已 装 扮'
        } else {
            this.lab_true.getComponent(Label).string = '装    扮'
        }
    }

    private requestSetAvatar() {
        if(this.m_data.usage_status==1) {
            return
        }
        uiManager.Instance().showLoading()
        let opt = {'item_id':this.m_data.item_id}
        http.post(config.API.user_update_photo_frame_img, opt, (err,data)=>{
            uiManager.Instance().hideLoading()
            if(!err){
                let d = JSON.parse(data)
                if(d.code===config.status.SUCCESS){
                    userDataManager.user_data.avatar_id = this.m_data.item_id
                    userDataManager.user_data.photo_frame_img = this.m_data.icon
                    ClientEvent.dispatchEvent(config.UI_EVENT.UPDATE_USER_INFO)
                    uiManager.showToast('相框已装扮')
                    this.m_true_cb  && this.m_true_cb()
                    this.close()
                }
            }
        })
    }
}

