%%-----------------------------------------------------------------------------
%% @Module  :       lib_treasure_evaluation.erl
%% @Author  :       hyh
%% @Email   :       huyihao@suyougame.com
%% @Created :       2018-06-11
%% @Description:    幸运鉴宝
%%-----------------------------------------------------------------------------

-module(lib_treasure_evaluation).

-include("treasure_evaluation.hrl").
-include("custom_act.hrl").
-include("server.hrl").
-include("errcode.hrl").
-include("predefine.hrl").
-include("language.hrl").
-include("common.hrl").
-include("def_fun.hrl").

-export ([
    login_te/1,
    get_te_lucky_choose_num/5,
    set_lucky_num/4,
    player_daily_check/1,
    all_daily_check/0,
    gm_te_lucky_num/4,
    sql_treasure_evaluation/2,
    get_reward_list/3,
    get_te_all_cfg/0,
    reload_file/0
    ]).

login_te(Ps) ->
    #player_status{
        id = RoleId
    } = Ps,
    ReSql = io_lib:format(?SelectTreasureEvaluationInfoSql, [RoleId]),
    case db:get_all(ReSql) of
        [] ->
            TEStatus = #te_status{};
        SqlList ->
            TEList = [begin
                [_RoleId, SubType, ChooseBigRewardId, LuckyNum, Time] = SqlInfo,
                #te_info{
                    sub_type = SubType,
                    choose_big_reward_id = ChooseBigRewardId,
                    lucky_num = LuckyNum,
                    time = Time
                }
            end||SqlInfo <- SqlList],
            TEStatus = #te_status{
                te_list = TEList
            }
    end,
    Ps#player_status{
        te_status = TEStatus
    }.

%% 获取选择的大奖id和幸运值
%% return :: {ChooseBigRewardId, LuckyNum, NewTEStatus}
%% ChooseBigRewardId :: 选择的大奖id
%% LuckyNum :: 幸运值
get_te_lucky_choose_num(RoleId, SubType, Stime, Etime, TEStatus) ->
    #te_status{
        te_list = TEList
    } = TEStatus,
    case lists:keyfind(SubType, #te_info.sub_type, TEList) of
        false ->
            NeedReplace = true,
            ChooseBigRewardId = 1,
            LuckyNum = 0,
            NewTime = utime:unixtime();
        TEInfo ->
            #te_info{choose_big_reward_id = TChooseBigRewardId, lucky_num = TLuckyNum, time = Time} = TEInfo,
            case Time >= Stime andalso Time < Etime of
                true -> %% 本次活动数据
                    NeedReplace = false,
                    ChooseBigRewardId = TChooseBigRewardId,
                    LuckyNum = TLuckyNum,
                    NewTime = Time;
                false -> %% 旧活动数据
                    NeedReplace = true,
                    ChooseBigRewardId = 1,
                    LuckyNum = 0,
                    NewTime = utime:unixtime()
            end
    end,
    NewTEInfo = #te_info{sub_type = SubType, choose_big_reward_id = ChooseBigRewardId, lucky_num = LuckyNum, time = NewTime},
    ?IF(NeedReplace, sql_treasure_evaluation(RoleId, NewTEInfo), skip),
    NewTEList = lists:keystore(SubType, #te_info.sub_type, TEList, NewTEInfo),
    NewTEStatus = TEStatus#te_status{te_list = NewTEList},
    {ChooseBigRewardId, LuckyNum, NewTEStatus}.

sql_treasure_evaluation(RoleId, TEInfo) ->
    #te_info{
        sub_type = SubType,
        choose_big_reward_id = ChooseBigRewardId,
        lucky_num = LuckyNum,
        time = Time
    } = TEInfo,
    ReSql = io_lib:format(?ReplaceTreasureEvaluationInfoAllSql, [RoleId, SubType, ChooseBigRewardId, LuckyNum, Time]),
    db:execute(ReSql).

set_lucky_num(Ps, BigRewardId, LuckyNum, SubType) ->
    #player_status{
        id = RoleId,
        te_status = TEStatus
    } = Ps,
    #te_status{
        te_list = TEList
    } = TEStatus,
    case lists:keyfind(SubType, #te_info.sub_type, TEList) of
        false ->
            NewTEInfo = #te_info{
                sub_type = SubType,
                choose_big_reward_id = BigRewardId,
                lucky_num = LuckyNum
            };
        TEInfo ->
            NewTEInfo = TEInfo#te_info{
                choose_big_reward_id = BigRewardId,
                lucky_num = LuckyNum
            }
    end,
    sql_treasure_evaluation(RoleId, NewTEInfo),
    NewTEList = lists:keystore(SubType, #te_info.sub_type, TEList, NewTEInfo),
    NewTEStatus = TEStatus#te_status{
        te_list = NewTEList
    },
    NewPs = Ps#player_status{
        te_status = NewTEStatus
    },
    NewPs.

player_daily_check(Ps) ->
    #player_status{
        id = RoleId,
        te_status = TEStatus
    } = Ps,
    #te_status{
        te_list = TEList
    } = TEStatus,
    F = fun(TEInfo, {SqlStrList1, NewTEList1}) ->
        #te_info{
            sub_type = SubType
        } = TEInfo,
        case lib_custom_act_util:get_act_cfg_info(?CUSTOM_ACT_TYPE_TREASURE_EVALUATION, SubType) of
            [] ->
                IfDelete = 1;
            #custom_act_cfg{clear_type = ClearType} ->
                case lib_custom_act_api:is_open_act(?CUSTOM_ACT_TYPE_TREASURE_EVALUATION, SubType) of
                    false ->
                        IfDelete = 1;
                    true ->
                        case ClearType of
                            1 ->
                                 IfDelete = 0;
                            _ ->
                                IfDelete = 1
                        end
                end
        end,
        case IfDelete of
            1 ->
                SqlStr = io_lib:format("(`role_id` = ~p and `sub_type` = ~p)", [RoleId, SubType]),
                {[SqlStr|SqlStrList1], NewTEList1};
            _ ->
                {SqlStrList1, [TEInfo|NewTEList1]}
        end
    end,
    {SqlStrList, NewTEList} = lists:foldl(F, {[], []}, TEList),
    case SqlStrList of
        [] ->
            skip;
        _ ->
            SqlList = ulists:list_to_string(SqlStrList, "or"),
            ReSql = io_lib:format(?DeleteTreasureEvalutionInfoAllSql, [SqlList]),
            db:execute(ReSql)
    end,
    NewTEStatus = TEStatus#te_status{
        te_list = NewTEList
    },
    NewPs = Ps#player_status{
        te_status = NewTEStatus
    },
    NewPs.

all_daily_check() ->
    case db:get_all(?SelectTreasureEvaluationInfoAllSql) of
        [] ->
            skip;
        SqlList ->
            F = fun(SqlInfo, SqlStrList1) ->
                [RoleId, SubType, _ChooseBigRewardId, _LuckyNum] = SqlInfo,
                case lib_custom_act_util:get_act_cfg_info(?CUSTOM_ACT_TYPE_TREASURE_EVALUATION, SubType) of
                    [] ->
                        IfDelete = 1;
                    #custom_act_cfg{clear_type = ClearType} ->
                        case lib_custom_act_api:is_open_act(?CUSTOM_ACT_TYPE_TREASURE_EVALUATION, SubType) of
                            false ->
                                IfDelete = 1;
                            true ->
                                case ClearType of
                                    1 ->
                                        IfDelete = 0;
                                    _ ->
                                        IfDelete = 1
                                end
                        end
                end,
                case IfDelete of
                    1 ->
                        SqlStr = io_lib:format("(`role_id` = ~p and `sub_type` = ~p)", [RoleId, SubType]),
                        [SqlStr|SqlStrList1];
                    _ ->
                        SqlStrList1
                end
            end,
            SqlStrList = lists:foldl(F, [], SqlList),
            case SqlStrList of
                [] ->
                    skip;
                _ ->
                    SqlList1 = ulists:list_to_string(SqlStrList, "or"),
                    ReSql = io_lib:format(?DeleteTreasureEvalutionInfoAllSql, [SqlList1]),
                    db:execute(ReSql)
            end
    end.

gm_te_lucky_num(RoleId, BigRewardId, LuckyNum, SubType) ->
    lib_player:apply_cast(RoleId, ?APPLY_CAST_SAVE, ?NOT_HAND_OFFLINE, lib_treasure_evaluation, set_lucky_num, [BigRewardId, LuckyNum, SubType]).


%% ==================
%% 筛选出符合条件的奖励
%% ==================
%% 通用奖励格式
get_reward_list(?REWARD_TYPE_NORMAL, _Career, GoodsList) -> GoodsList;

%% 指定职业奖励格式
get_reward_list(?REWARD_TYPE_CAREER, Career, GoodsList) when is_list(GoodsList) ->
    case lists:keyfind(Career, 1, GoodsList) of
        {Career, LastGoodsList} ->
            LastGoodsList;
        _ ->
            []
    end;

get_reward_list(_RewardType, _Career, GoodsList) -> GoodsList.

%% ==================
%% 获取配置
%% ==================
get_te_all_cfg() ->
    MainIds = data_treasure_evaluation:get_all_main_id(),
    WeightIds = data_treasure_evaluation:get_all_weight_id(),
    F1 = fun({MainRewardId, RewardId}) ->
        MainCfg = data_treasure_evaluation:get_te_main_reward_con(MainRewardId, RewardId),
        #te_main_reward_con{
            main_reward_id = MainRewardId, reward_id = RewardId, image_str = ImageStr, power = Power, kind_id = KindId,
            image_id = ImageId, attr_list = AttrList, reward_type = RewardType, goods_list = GoodsList, weight = Weight
        } = MainCfg,
        {
            MainRewardId, RewardId, util:term_to_string(ImageStr), Power, KindId, ImageId, util:term_to_string(AttrList),
            RewardType, util:term_to_string(GoodsList), Weight
        }
    end,
    MainCfgs = lists:map(F1, MainIds),
    F2 = fun({MainRewardId, RewardId}) ->
        WeightCfg = data_treasure_evaluation:get_te_weight_con(MainRewardId, RewardId),
        #te_reward_weight_con{
            main_reward_id = MainRewardId, reward_id = RewardId, reward_type = RewardType,
            goods_list = GoodsList, weight = Weight
        } = WeightCfg,
        {MainRewardId, RewardId, RewardType, util:term_to_string(GoodsList), Weight}
    end,
    WeightCfgs = lists:map(F2, WeightIds),
    pt_331:write(33159, [MainCfgs, WeightCfgs]).

reload_file() ->
    {ok, Bin} = get_te_all_cfg(),
    lib_server_send:send_to_all(Bin).
