%%%-------------------------------------------------------------------
%%% @author liushl
%%% @doc
%%%     装备收集
%%% @end
%%%-------------------------------------------------------------------
-module(equipment_collect).
-author("liushl").

-include("server.hrl").
-include("equipment.hrl").
-include("goods.hrl").
-include("errcode.hrl").
-include("predefine.hrl").
-include("figure.hrl").
%% API
-export([
    login/2,
    get_attr/1,
    send_collect_info/1,
    check_collect/2,
    active/3
]).

-define(EQUIPMENT_COLLECT_NUM,  7).     %% 激活7件

%% 登陆加载
login(RoleId, Equipment) ->
    LoadData = db_get_collect(RoleId),
    CollectInfo = [
        #equipment_collect{
            key = {Series, Color},
            active = Active,
            collect = util:bitstring_to_term(Collect)
        }
        || [Series, Color, Active, Collect] <- LoadData
    ],
    include_attr(Equipment#equipment{equipment_collect = CollectInfo}).

%% 获得属性
get_attr(Player) ->
    case Player#player_status.equipment of
        #equipment{equipment_collect_attr = Attr} ->
            Attr;
        _ ->
            []
    end.

%% 获得装备收集情况
send_collect_info(Player) ->
    #player_status{
        equipment = #equipment{equipment_collect = EquipmentCollect}
    } = Player,
    [
        {Series, Color, Collect, Active}
        || #equipment_collect{key = {Series, Color}, active = Active, collect = Collect} <- EquipmentCollect
    ].

%% 穿戴装备的时候判断改装备是否需要收集
check_collect(Player, GoodsInfo) ->
    #player_status{
        id = RoleId,
        sid = Sid,
        equipment = Equipment,
        figure = #figure{career = Career}
    } = Player,
    #equipment{
        equipment_collect = EquipmentCollect
    } = Equipment,
    #goods{
        goods_id = GoodsId,
        subtype = SubType,
        color = _Color
    } = GoodsInfo,
    %% 对于新手定制装备收集的时候降低为橙色
    Color = case GoodsId =:= 24291015 orelse GoodsId =:= 24191015 of
        true  ->
            4;
        false ->
            _Color
    end,
    Series = equipment_api:get_equipment_series(GoodsInfo),
    NewEquipmentCollect =
        case check_is_collect(RoleId, EquipmentCollect, Series, Color, SubType) of
            {stop, EquipmentCollect1} ->
                EquipmentCollect1;
            {ok, EquipmentCollect1} ->
                {ok, Bin} = pt_152:write(15219, [Series, Color, GoodsId]),
                lib_server_send:send_to_sid(Sid, Bin),
                EquipmentCollect2 = check_low_color_equipment(RoleId, EquipmentCollect1, Series, Color-1, SubType, Career),
                EquipmentCollect2
        end,
    Player#player_status{equipment = Equipment#equipment{equipment_collect = NewEquipmentCollect}}.

%% 判断是否已经收集
check_is_collect(RoleId, EquipmentCollect, Series, Color, Pos) ->
    Key = {Series, Color},
    case lists:keyfind(Key, #equipment_collect.key, EquipmentCollect) of
        #equipment_collect{collect = CollectInfo} = Info ->
            case lists:member(Pos, CollectInfo) of
                true  ->
                    {stop, EquipmentCollect};
                false ->
                    check_needed(EquipmentCollect, RoleId, Key, Pos, Info)
            end;
        _ ->
            check_needed(EquipmentCollect, RoleId, Key, Pos, #equipment_collect{key = Key})
    end.
%% 判断是否需要收集
check_needed(EquipmentCollect, RoleId, {Series, Color} = Key, Pos, OneCollect) ->
    CollectContent = data_equipment_check:get_collect_content(Series, Color),
    case lists:member(Pos, CollectContent) of
        true  ->
            NewCollect = OneCollect#equipment_collect{collect = [Pos|OneCollect#equipment_collect.collect]},
            save_collect(RoleId, NewCollect),
            NewEquipmentCollect = lists:keystore(Key, #equipment_collect.key, EquipmentCollect, NewCollect),
            {ok, NewEquipmentCollect};
        false ->
            {stop, EquipmentCollect}
    end.

%% 循环判断收集
check_low_color_equipment(_RoleId, EquipmentCollect, _Series, 0, _SubType, _Career) ->
    EquipmentCollect;
check_low_color_equipment(RoleId, EquipmentCollect, Series, Color, SubType, Career) ->
    case check_is_collect(RoleId, EquipmentCollect, Series, Color, SubType) of
        {stop, NewEquipmentCollect} ->
            NewEquipmentCollect;
        {ok, NewEquipmentCollect} ->
            check_low_color_equipment(RoleId, NewEquipmentCollect, Series, Color-1, SubType, Career)
    end.

%% 激活进度：一开始是中间激活2件、4件也会有属性，现在改为激活7件才会激活属性
active(Player, Series, Color) ->
    #player_status{
        id = RoleId,
        equipment = Equipment,
        figure = Figure
    } = Player,
    #equipment{
        equipment_collect = EquipmentCollect
    } = Equipment,
    Key = {Series, Color},
    ActiveNum = ?EQUIPMENT_COLLECT_NUM,  %% 激活7件完成任务
    case lists:keyfind(Key, #equipment_collect.key, EquipmentCollect) of
        #equipment_collect{active = Active} when Active >= ActiveNum ->
            {false, ?ERRCODE(err152_already_active)};
        #equipment_collect{collect = CollectInfo} = OneCollect ->
            Num = erlang:length(CollectInfo),
            case Num >= ActiveNum of
                true  ->
                    NewCollect = OneCollect#equipment_collect{active = ActiveNum},
                    update_collect(RoleId, Series, Color, ActiveNum),
                    NewEquipmentCollect = lists:keystore(Key, #equipment_collect.key, EquipmentCollect, NewCollect),
                    Equipment1 = Equipment#equipment{equipment_collect = NewEquipmentCollect},
                    Equipment2 = include_attr(Equipment1),
                    Player1 = Player#player_status{equipment = Equipment2},
                    Reward  = data_equipment_check:get_full_collect_reward(Series, Color),
                    Player2 = lib_goods_api:send_reward(Player1, Reward, equipment_collect),
                    lib_log_api:log_equipment_collect_reward(
                        [RoleId, Figure#figure.name, Figure#figure.lv, Series, Color, util:term_to_bitstring(Reward), utime:unixtime()]
                    ),
                    Player3 = lib_player:count_player_attribute(Player2),
                    lib_player:send_attribute_change_notify(Player3, ?NOTIFY_ATTR),
                    {true, Player3, ActiveNum};
                false ->
                    {false, ?ERRCODE(err152_collect_condition)}
            end;
        _ ->
            {false, ?ERRCODE(err152_collect_condition)}
    end.

%%calc_next_active(Series, Color, Active) ->
%%    case data_equipment_check:get_collect_num_attr(Series, Color, Active) of
%%        [Base] ->
%%            calc_next_active(Series, Color, Active + 1, Base);
%%        [] ->
%%            calc_next_active(Series, Color, Active + 1, [])
%%    end.
%%calc_next_active(Series, Color, Active, Base) ->
%%    case data_equipment_check:get_collect_num_attr(Series, Color, Active) of
%%        [Base] ->
%%            calc_next_active(Series, Color, Active + 1, Base);
%%        _    ->
%%            Active
%%    end.

%% 统计属性
include_attr(Equipment) ->
    #equipment{
        equipment_collect = EquipmentCollect
    } = Equipment,
    Attr = lists:foldl(
        fun
            (#equipment_collect{key = {Series, Color}, active = Active}, Temp) when Active >= ?EQUIPMENT_COLLECT_NUM ->
                data_equipment_check:get_full_collect_attr(Series, Color) ++ Temp;
            (_, Temp) -> Temp
        end, [], EquipmentCollect
    ),
    Equipment#equipment{
        equipment_collect_attr = util:combine_list(Attr)
    }.

db_get_collect(RoleId) ->
    Sql = io_lib:format(<<"SELECT series,color,active,collect FROM equipment_collect WHERE role_id=~p">>, [RoleId]),
    db:get_all(Sql).

save_collect(RoleId, Collect) ->
    #equipment_collect{
        key = {Series, Color},
        active = Active,
        collect = CollectInfo
    } = Collect,
    Sql = io_lib:format(<<"REPLACE INTO equipment_collect(role_id,series,color,active,collect) VALUES(~p,~p,~p,~p,'~ts')">>,
        [RoleId, Series, Color, Active, util:term_to_bitstring(CollectInfo)]),
    db:execute(Sql).

update_collect(RoleId, Series, Color, Active) ->
    Sql = io_lib:format(<<"UPDATE equipment_collect SET active=~p WHERE role_id=~p and series=~p and color=~p">>,
        [Active, RoleId, Series, Color]),
    db:execute(Sql).