%%%--------------------------------------
%%% @Module  : lib_login
%%% @Author  : xyao
%%% @Email   : jiexiaowen@gmail.com
%%% @Created : 2011.06.14
%%% @Description:注册登录
%%%--------------------------------------
-module(lib_login).
-export([
        get_role_list/2,
        get_roles_attr/2,               %% 得到帐号全部角色的属性
        create_role/9,
        delete_role/2,
        get_player_login_by_id/1,
        update_login_data/4,
        log_all_online/2
    ]).
-include("sql_player.hrl").
-include("sql_goods.hrl").
-include("scene.hrl").
-include("def_goods.hrl").
-include("server.hrl").
-include("predefine.hrl").
-include("figure.hrl").
-include("common.hrl").
-include("role.hrl").
-include("activitycalen.hrl").
-include("def_fun.hrl").

%% 取得指定帐号的角色列表
get_role_list(Accid, AccName) ->
    %% 得到帐号全部角色的属性
    RoleList = get_roles_attr(Accid, AccName),
    F = fun([Id, Status, NickName, Sex, Lv, Career, Realm, Turn, RegTime]) ->
            case lib_role:get_role_show(Id)  of
                #ets_role_show{figure=Figure}->
                   skip;
                _->
                    LvModel = lib_goods_util:get_lv_model(Id, Career, Sex, Turn, Lv),
                    {FashionModelList, _WearFashion} = lib_fashion:get_equip_fashion_list(Id, Career),
                    Turn = transform:get_turn_from_db(Id),
                    ProfilePhotoId = lib_player:get_player_photo_id(Id),
                    Figure = #figure{
                        id = Id,
                        name=NickName,
                        sex=Sex,
                        lv=Lv,
                        career=Career,
                        realm=Realm,
                        lv_model = LvModel,
                        fashion_model = FashionModelList,
                        turn = Turn,
                        profile_photo_id = ProfilePhotoId
                    }
            end,
            [Status, Figure, RegTime]
    end,
    %% 返回角色列表.
    case RoleList of
        List when is_list(List) ->
            [F(Elem)||Elem<-List];
        _ ->
            []
    end.

%% 根据帐号查找所有角色信息
get_roles_attr(Accid, AccName) ->
    db:get_all(io_lib:format(?sql_role_list, [Accid, AccName])).

%% 根据id查找账户名称
get_player_login_by_id(Id) ->
    db:get_row(io_lib:format(?sql_player_login_by_id, [Id])).

%% 更新登陆需要的记录
update_login_data(Id, Ip, Time, OnlineFlag) ->
    db:execute(io_lib:format(?sql_update_login_data, [Time, util:ip2bin(Ip), OnlineFlag, Id])).

%% 创建角色
create_role(AccId, AccName, Name, _Realm, _Career, _Sex, IP, Source, Default) ->
    %% 职业
    Career = case _Career of
        ?SWORDSMAN -> ?SWORDSMAN;
        ?KNIGHT -> ?KNIGHT;
        ?MAGE -> ?MAGE;
        ?GUNNER -> ?GUNNER;
        _ -> ?SWORDSMAN
    end,

    %% 性别
    Sex = case _Sex of
        ?MALE -> ?MALE;
        _ -> ?FEMALE
    end,

    %% 阵营
    Realm = case _Realm of
        ?REALM_KUNLUN  -> ?REALM_KUNLUN;
        ?REALM_XUANDU  -> ?REALM_XUANDU;
        ?REALM_PENGLAI -> ?REALM_PENGLAI;
        _ -> 0
    end,

    %% 默认参数
    {SceneId, X, Y} = lib_scene:get_create_role_position(),
    Lv = 1,
    Hp = 9000,
    Mp = 9000,
    CellNum = data_goods:get_location_size(?GOODS_LOC_BAG),
    StorageNum = data_goods:get_location_size(?GOODS_LOC_STORAGE),

    SourceLenValid = util:check_length(Source, 50),
    Source2 = case SourceLenValid of
        false -> "";
        true  -> Source
    end,

    Time = utime:unixtime(),
    SerId = config:get_server_id(),
    IsDefault = ?IF(Default =:= 0, 0, 1),
    case catch mod_player_create:get_new_id() of
        Id when is_integer(Id) ->
            PlayerLoginSql  = io_lib:format(?sql_insert_player_login_one,
                [Id, AccId, AccName, Time, util:ip2bin(IP), Source2, SerId]),
            PlayerHighSql   = io_lib:format(?sql_insert_player_high_one, [Id]),
            PlayerLowSql    = io_lib:format(?sql_insert_player_low_one, [Id, Name, Sex, Lv, Career, Realm, IsDefault]),
            PlayerStateSql  = io_lib:format(?sql_insert_player_state_one, [Id, SceneId, X, Y, Hp, Mp]),
            PlayerAttrSql   = io_lib:format(?sql_insert_player_attr_one, [Id, CellNum, StorageNum]),
            F = fun() ->
                    db:execute(PlayerLoginSql),
                    db:execute(PlayerHighSql),
                    db:execute(PlayerLowSql),
                    db:execute(PlayerStateSql),
                    db:execute(PlayerAttrSql),
                    true
            end,
            case db:transaction(F) of
                true  -> Id; %% sql执行成功
                Error ->
                    ?ERR("~p ~p Error:~p~n", [?MODULE, ?LINE, Error]),
                    0
            end;
        Error ->
            ?ERR("~p ~p Error:~p~n", [?MODULE, ?LINE, Error]),
            0
    end.

%% 删除角色 - 暂时无用
delete_role(Pid, Accname) ->
    Sql = lists:concat(["select id from player_login where id=",Pid ," and accname='",Accname,"'"]),
    case db:get_one(Sql) of
        null -> false;
        Id ->
            db:execute(lists:concat(["delete from `player_login` where id = ", Id])),
            db:execute(lists:concat(["delete from `player_high` where id = ", Id])),
            db:execute(lists:concat(["delete from `player_low` where id = ", Id])),
            true
    end.

%% 记录在线时长，大于1分钟的写入数据库中
log_all_online(Ps, LogoutTime) ->
    %% 下线时间减去上一次登录时间
    #player_status{id = RoleId, last_login_time = LastLoginTime} = Ps,
    OnlineTime = LogoutTime - LastLoginTime,
    %% 今日零时
    Date = utime:unixtime({today, LogoutTime}),
    if
        OnlineTime < 60 -> skip;
        true ->
            case lib_player_record:role_func_check_exist(RoleId, ?FUNC_TYPE_MIDNIGHT_LOG, _DefaultEtsId = 1) of
                true ->
                    lib_player_record:role_func_check_delete(RoleId, ?FUNC_TYPE_MIDNIGHT_LOG),
                    NeedLogLastDay = true;
                _ ->
                    NeedLogLastDay = false
            end,
            case utime:is_today(LastLoginTime) of
                true ->
                    OnlineTime1 = OnlineTime;
                    % LastLoginTime1 = LastLoginTime;
                _ -> %% 在线跨天了,只记今日部分
                    OnlineTime1 = max(0, round(LogoutTime - Date))
                    % LastLoginTime1 = Date
            end,
            SQL = <<"insert into `log_all_online`(player_id, online_time, log_time, logout_time, last_login_time, day)
            values (~p, ~p, ~p, ~p, ~p, ~p)">>,
            db:execute(SQL, [RoleId, OnlineTime1, LogoutTime, LogoutTime, LastLoginTime, Date]),
            case NeedLogLastDay of
                true ->
                    %% 昨日截止时间戳
                    LastDateEnd = Date - 1,
                    %% 昨日零时
                    LastDate = utime:unixtime({today, LastDateEnd}),
                    %% 昨日在线时长
                    if LastLoginTime > LastDate ->
                            LastOnlineTimeCount = LastDateEnd - LastLoginTime;
                        true ->
                            LastOnlineTimeCount = LastDateEnd - LastDate
                    end,
                    SQL1 = <<"insert into `log_all_online`(player_id, online_time, log_time, logout_time, last_login_time, day) values (~p, ~p, ~p, ~p, ~p, ~p)">>,
                    db:execute(SQL1, [RoleId, LastOnlineTimeCount, LastDateEnd, 0, LastLoginTime, LastDate]),
                    ok;
                _ ->
                    ok
            end
    end.
