var params = require('./params.js');

var http = require('./http.js');

var jybms_url = params.jybms_url;

function login(login_name, callBack, login_password = 123456) {
    var url =
        jybms_url + '/GetDateServices.asmx/loginSystem?LoginName=' + login_name + '&LoginPassword=' + login_password + '&LoginType=USER&language=en&ISMD5=0&timeZone=+08&apply=APP';
    uni.request({
        header: {
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        url: url,
        method: 'GET',
        success: function (res) {
            if (res.data.success != 'false' && res.data.errorCode == 200) {
                callBack(res.data);
            }
        }
    });
}

function bmsRefresh(macid, callBack) {
    login(macid, (loginInfo) => {
        var url = jybms_url + '/GetDataService.aspx?method=SupplyBatteryInfo&work=6&cmd=BMS_REFRESH&macid=' + macid;
        uni.request({
            header: {
                'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            url: url,
            method: 'GET',
            success: (res) => {
                callBack(loginInfo);
            }
        });
    });
}

function bmsState(macid, callBack) {
    bmsRefresh(macid, (loginInfo) => {
        var url = jybms_url + '/GetDateServices.asmx/GetDate?method=BMSrealTimeState&mds=' + loginInfo.mds + '&macid=' + macid;
        uni.request({
            header: {
                'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            url: url,
            method: 'GET',
            success: function (res) {
                if (res.data.success != 'false' && res.data.errorCode == 200) {
                    callBack(res.data.data);
                }
            }
        });
        setTimeout(() => {
            uni.request({
                header: {
                    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                url: url,
                method: 'GET',
                success: function (res) {
                    if (res.data.success != 'false' && res.data.errorCode == 200) {
                        callBack(res.data.data);
                    }
                }
            });
        }, 5000);
    });
}

module.exports = {
    bmsState: bmsState
};
