// demoLoginDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "demo.h"
#include "demoLoginDlg.h"
#include "afxdialogex.h"
#include "HwmSdkAgent.h"
#include "demoTools.h"

// demoLoginDlg 对话框

IMPLEMENT_DYNAMIC(demoLoginDlg, CDialogEx)

demoLoginDlg::demoLoginDlg(CWnd* pParent /*=NULL*/)
    : CDialogEx(IDD_LOGIN_DIALOG, pParent)
{

}

demoLoginDlg::~demoLoginDlg()
{
}

void demoLoginDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_EDIT_ACCOUNT, m_loginAccountEdit);
    DDX_Control(pDX, IDC_EDIT_PASSWORD, m_loginPwdEdit);
    DDX_Control(pDX, IDC_CHECK_IS_USE_CODE_LOGIN, m_isTokenLoginCheck);
}


BEGIN_MESSAGE_MAP(demoLoginDlg, CDialogEx)
    ON_BN_CLICKED(IDC_BUTTON_LOGIN, &demoLoginDlg::OnBnClickedButtonLogin)
END_MESSAGE_MAP()


// demoLoginDlg 消息处理程序

BOOL demoLoginDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // 从配置文件读取上次登录帐号
    CString loginAccount = _T("");
    CTools::getIniConfigParam(_T("LoginConfig"), _T("account"), loginAccount);
    m_loginAccountEdit.SetWindowText(loginAccount);

    return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

/**
* 登录处理
*/
int demoLoginDlg::Login()
{
    //获取界面填入的信息
    m_loginAccountEdit.GetWindowText(m_loginAccount);
    m_loginPwdEdit.GetWindowText(m_loginPwd);

    //参数转换
    string account = CTools::UNICODE2UTF(m_loginAccount.GetString());
    string password = CTools::UNICODE2UTF(m_loginPwd.GetString());

    int ret;
    //判断是否token登录
    if (m_isTokenLoginCheck.GetCheck())
    {
        //组装入参结构体
        hwmsdkagent::HwmAccountAndTokenAuthInfo loginParam{};

        strncpy_s(loginParam.account, account.c_str(), HWM_MAX_ACCOUNT_LEN);
        strncpy_s(loginParam.token, password.c_str(), HWM_MAX_TOKEN_LEN);
        //调用登录接口
        ret = hwmsdkagent::LoginByToken(&loginParam);
        memset(&loginParam, 0, sizeof(hwmsdkagent::HwmAccountAndTokenAuthInfo));
    }
    else
    {
        //组装入参结构体
        hwmsdkagent::HwmLoginInfo loginParam{};
      
        strncpy_s(loginParam.accountAndPasswordAuthInfo.account, account.c_str(), HWM_MAX_ACCOUNT_LEN);
        strncpy_s(loginParam.accountAndPasswordAuthInfo.password, password.c_str(), HWM_MAX_PASSWORD_LEN);
        loginParam.authType = hwmsdkagent::HWM_AUTH_TYPE_ACCOUNT_AND_PASSWORD;
        //调用登录接口
        ret = hwmsdkagent::Login(&loginParam);
        memset(&loginParam, 0, sizeof(hwmsdkagent::HwmLoginInfo));
    }
    password.assign(password.length(), '\0');

    return ret;
}

void demoLoginDlg::OnBnClickedButtonLogin()
{
    int ret = Login();
    if (hwmsdk::HWM_COMMON_SUCCESS != ret)
    {
        CTools::OutputRetStr("Login error");
    }
    else
    {
        //登录接口调用成功后将登录信息保存到配置文件，下次启动读取
        CTools::writeIniConfigParam(_T("LoginConfig"), _T("account"), m_loginAccount);
        //关闭当前窗口
        OnOK();
    }
}
