import { _decorator, Component, Label, Node, Sprite } from 'cc';
import { base_ui } from '../../fw/base_ui';
import { dataManager } from '../../manager/dataManager';
import { tools } from '../../tools';
import { exchange_car_success } from './exchange_car_success';
import { http } from '../../http';
import { config } from '../../config';
import { GameManager } from '../../GameManager';
const { ccclass, property } = _decorator;

@ccclass('exchange_car_view')
export class exchange_car_view extends base_ui {
    @property(Node) bg_view:Node = null
    @property(Node) bg_public_bg:Node = null
    @property(Node) lab_name:Node = null
    @property(Node) img_car_bg:Node = null
    @property(Node) img_sp:Node = null
    @property(Node) img_car:Node = null
    @property(Node) lab_current_count:Node = null
    @property(Node) lab_total_count:Node = null
    @property(Node) btn_exchange:Node = null

    @property(Node) success_view:Node = null

    private m_car_id:number = 0
    private m_cb = null

    start() {
        this.onButtonListen(this.bg_public_bg, ()=>{
            this.close()
        })
        this.onButtonListen(this.btn_exchange, ()=>{
            this.requestExchangeCar()
        })
    }

    initView(data, cb) {
        this.m_cb = cb
        this.m_car_id = data.car_id
        let car_item = dataManager.getUserCarInfo(data.car_id)
        this.lab_name.getComponent(Label).string = car_item.name
        tools.loadRemoteImg(car_item.background_cover, (d)=>{
            this.img_car_bg.getComponent(Sprite).spriteFrame = d.sf
        })
        tools.loadRemoteImg(data.sp_icon, (d)=>{
            this.img_sp.getComponent(Sprite).spriteFrame = d.sf
        })
        this.img_car.getComponent(Sprite).spriteFrame = dataManager.getUserRankCarSf(car_item.id,-1)
        this.lab_current_count.getComponent(Label).string = `${data.sp_count}` 
        this.lab_total_count.getComponent(Label).string = `/${car_item.unlock_points}` 

        if(data.sp_count>=car_item.unlock_points) {
            this.btn_exchange.active = true
        } else {
            this.btn_exchange.active = false
        }
    }

    private requestExchangeCar() {
        GameManager.requestExchangeCar(this.m_car_id, ()=>{
            this.bg_view.active = false
            this.success_view.active = true
            this.success_view.getComponent(exchange_car_success).initView(this.m_car_id, ()=>{
                this.close()
                this.m_cb && this.m_cb()
            })
        },true)
    }
}

