import { _decorator, Component, EditBox, Node } from 'cc';
import { tools } from '../tools';
import { http } from '../http';
import { config } from '../config';
import { uiManager } from '../manager/uiManager';
const { ccclass, property } = _decorator;

@ccclass('zb_login_view')
export class zb_login_view extends Component {
    @property(Node) editbox_account: Node = null;
    @property(Node) editbox_password: Node = null;
    @property(Node) btn_login: Node = null;
    
    private m_login_cb: Function = null;

    start() {
        this.btn_login.on(Node.EventType.TOUCH_END, ()=> {
            if(this.m_login_cb != null) {
                this.loginAction((data)=> {
                    this.close()
                    this.m_login_cb(data)
                })
            }
        },this)
    }

    initView(loginCallback:Function) {
        this.m_login_cb = loginCallback
    }

    private loginAction(callback: Function) {
        let account_string = this.editbox_account.getComponent(EditBox).string
        account_string = tools.trimLeftAndRightblank(account_string)

        let password_string = this.editbox_password.getComponent(EditBox).string
        password_string = tools.trimLeftAndRightblank(password_string)

        if (account_string == '') {
            console.log('请输入账号')
            return
        }
        if (password_string == '') {
            console.log('请输入密码')
            return
        }

        let request_data = {'account': account_string, 'password': password_string}
        uiManager.Instance().showLoading()
        http.post(config.API.zb_login, request_data, (err,d)=> {
            console.log('主播登录=',d)
            uiManager.Instance().hideLoading()
            if (!err) {
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){
                    let openid = nd.content.openid
                    if (openid == "" || openid == null || openid == undefined) {
                        console.log('获取主播id失败')
                    } else {
                        callback && callback(nd.content)
                    }
                } else {
                    console.log(nd['message'])
                }
            }
        })
    }

    private close() {
        this.node.active = false
    }
}

