%% ---------------------------------------------------------------------------
%% @doc    游戏服务器提供给php后台调用的API
%% @author hek
%% @since  2016-11-14
%% @deprecated
%% ---------------------------------------------------------------------------
-module (lib_php_api).
-include("mail.hrl").
-include("common.hrl").
-include("server.hrl").
-export ([
          nofity_pay/1                      %% 通知充值入账游戏服务器
         , reload_custom_act_cfg/0          %% 额外定制活动热更之后后台调用接口
         , modify_guild_name/2              %% 修改公会名字
         , modify_announce/2                %% 修改公会公告
         , disband_guild/1                  %% 解散公会

         , realese_upload_player_picture/1  %%
         , forbid_upload_player_picture/1   %%
         , delete_player_picture/1          %%

         , set_goods_expired_time/3         %% 设置物品有效期
         , gm_repair_role_lv/3              %% 设置玩家的等级
         , gm_del_task/2                    %% 删除玩家已接任务
         , clear_dun_enter_count/2          %% 清理副本进入次数
         , gm_reset_daily/1                 %% 手动清理日常12|4点
         , reload_gm_type/1                 %% 刷新gm身份
         , client_remote_debug/2            %% 客户端远程调试指令
         , check_multi_team/0
         , gm_sync_limit_goal_tool/0        %% 修复限时目标目标为1任务为4的数据进度
         , gm_repair_limit_goal_status/0    %% 修复已达到完成限时目标1任务4进度但没完成的玩家数据
         , gm_update_guild_lv/4             %% 修复公会建筑等级

         , release_battle_status/1          %% 释放竞技场战斗状态
         , gm_repair_rank_equip/0           %% 修复装备榜数据
         , send_tar_role_mail/3             %% 指定玩家指定物品列表
         , php_send_sys_mail_to_all/9       %% 根据玩家条件发放指定邮件
         , php_send_sys_mail_to_all/11

         , notice_msg/3                     %% 后台通知客户端更新并附言

         , get_online_num/0                  %% 获得在线玩家数量
         ]).

-include("def_module.hrl").

%% 通知充值入账游戏服务器
nofity_pay(PlayerId) ->
    lib_recharge_api:nofity_pay(PlayerId),
    ok.

%% 额外定制活动热更之后后台调用接口
reload_custom_act_cfg() ->
    lib_custom_act_api:reload_custom_act_cfg(),
    ok.

%% 后台修改公会名字
modify_guild_name(GuildId, GuildName) ->
    lib_guild_api:modify_guild_name_by_gm(GuildId, GuildName).

%% 后台修改公会公告
modify_announce(GuildId, Announce) ->
    lib_guild_api:modify_announce_by_gm(GuildId, Announce).

%% 后台强制解散公会
%% 需满足公会的解散条件
disband_guild(GuildId) ->
    lib_guild_api:disband_guild_by_gm(GuildId).

%% 允许玩家上传头像
%% @param IdList [Id, Id|...] 玩家列表
realese_upload_player_picture(IdListStr) ->
    IdList = util:string_to_term(IdListStr),
    lib_player:update_player_picture_lim(IdList, 0).

%% 禁止玩家上传头像
%% @param IdList [Id, Id|...] 玩家列表
forbid_upload_player_picture(IdListStr) ->
    IdList = util:string_to_term(IdListStr),
    lib_player:update_player_picture_lim(IdList, 1).

%% 删除玩家的头像
delete_player_picture(IdListStr)->
    IdList = util:string_to_term(IdListStr),
    lib_player:delete_player_picture(IdList).

%%--------------------------------------------------
%% 设置物品有效期
%% @param  RoleIds     玩家ids []表示对所有玩家都执行刷新操作
%% @param  GTypeIds    物品类型id列表
%% @param  ExpiredTime 新的过期时间
%% @return             description
%%--------------------------------------------------
set_goods_expired_time(RoleIdsStr, GTypeIdsStr, ExpiredTime) ->
    RoleIds = util:string_to_term(RoleIdsStr),
    GTypeIds = util:string_to_term(GTypeIdsStr),
    case GTypeIds =/= [] of
        true ->
            lib_goods_api:set_goods_expired_time(RoleIds, GTypeIds, ExpiredTime);
        _ -> skip
    end.

%% Gm修改玩家等级(只能离线)
gm_repair_role_lv(RoleId, Lv, Exp)->
    RolePid = misc:get_player_process(RoleId),
    case is_pid(RolePid) andalso misc:is_process_alive(RolePid) of
        true ->
            %% gen_server:cast(RolePid, {'set_role_lv', Lv, Exp});
            role_online_skip;
        false ->
            %% 经验
            ExpSQL = <<"update `player_high` set exp=~w where id=~w">>,
            %% 等级
            LvSQL = <<"update `player_low` set lv = ~w where id=~w">>,
            if
                Lv =< 370 ->
                    Fun = fun() ->
                                  db:execute(io_lib:format(ExpSQL, [Exp, RoleId])),
                                  db:execute(io_lib:format(LvSQL, [Lv, RoleId]))
                          end,
                    db:transaction(Fun);
                true ->
                    %% 技能点
                    SkSQL = <<"update `player_state` set skill_extra_point = ~w where id=~w">>,
                    %% 天赋技能
                    TSkSQL = <<"delete from talent_skill where role_id = ~w">>,
                    %% 计算技能点
                    SkillPoint = Lv - 370 + 5,
                    Fun = fun() ->
                                  db:execute(io_lib:format(SkSQL,  [SkillPoint, RoleId])),
                                  db:execute(io_lib:format(TSkSQL, [RoleId])),
                                  db:execute(io_lib:format(ExpSQL, [Exp, RoleId])),
                                  db:execute(io_lib:format(LvSQL,  [Lv, RoleId]))
                          end,
                    db:transaction(Fun)
            end
    end.

%% 后台删除玩家任务秘籍
gm_del_task(RoleId, TaskId) ->
    RolePid = misc:get_player_process(RoleId),
    case is_pid(RolePid) andalso misc:is_process_alive(RolePid) of
        true ->
            gen_server:cast(RolePid, {'gm_del_task', RoleId, TaskId});
        false ->
            F = fun() ->
                        %% 删除任务
                        SQL1 = <<"delete from task_bag WHERE role_id=~p and task_id=~p">>,
                        db:execute(io_lib:format(SQL1, [RoleId, TaskId])),
                        %% 删除任务日志
                        SQL2 = <<"delete from task_log WHERE role_id=~p and task_id=~p">>,
                        db:execute(io_lib:format(SQL2, [RoleId, TaskId])),
                        %% 删除和任务日志
                        SQL3 = <<"delete from task_log_clear WHERE role_id=~p and task_id=~p">>,
                        db:execute(io_lib:format(SQL3, [RoleId, TaskId]))
                end,
            db:transaction(F)
    end.

%%清理副本次数
clear_dun_enter_count(PlayerId, DunId) ->
    lib_dungeon:clear_dun_enter_count(PlayerId, DunId).

%% gm重置12点|4点日常次数
gm_reset_daily(Clock)->
    if
        Clock == 12 ->
            timer_midnight:handle();
        Clock == 4 ->
            timer_4_clock:handle();
        true ->
            skip
    end.

%% 刷新gm身份
reload_gm_type(RoleId) ->
    lib_player:reload_gm_type(RoleId).
%%    lib_dress_up:gm_dress_up(RoleId).

%%% ====================
%%% 客户端远程调试指令
%%% ====================
%% @param CtrlId :: integer() 远程指令id
client_remote_debug(RoleId, CtrlId) when is_integer(RoleId), is_integer(CtrlId) ->
    case lib_player:is_online_global(RoleId) of
        true ->
            {ok, Bin} = pt_111:write(11105, [CtrlId]),
            lib_server_send:send_to_uid(RoleId, Bin),
            ok;
        _ ->
            {false, offline}
    end;
client_remote_debug(_RoleId, _CtrlId) ->
    {false, badargs}.

check_multi_team() -> ok.
    % case util:is_cls() of
    %   true ->
    %       Fun = fun(DunType)->
    %         DunIdList = data_dungeon:get_ids_by_type(DunType),
    %         [
    %             begin
    %                 Msg = {check_team, DunId},
    %                 lib_dun_multi_cluster:cast_dun_multi_hall_cluster(DunId, Msg)
    %             end
    %             || DunId <- DunIdList
    %         ]
    %       end,
    %       lists:map(Fun, [5, 13, 22]);
    %   false ->
    %     clusters_node:apply_cast(?MODULE, check_multi_team, [])
    % end.

%% 修复限时目标目标为1任务为4的数据进度
gm_sync_limit_goal_tool() ->
    spawn(fun() -> lib_limit_goal_api:gm_sync_limit_goal() end),
    ok.

%% 修复已达到完成限时目标1任务4进度但没完成的玩家数据
gm_repair_limit_goal_status() ->
    spawn(fun() -> lib_limit_goal_api:gm_repair_limit_goal_status() end),
    ok.

gm_update_guild_lv(RoleId, GuildId, GuildFunds, UpdateList) ->
  mod_guild:cast_to_guild({'gm_update_guild_lv', RoleId, GuildId, GuildFunds, UpdateList}),
  ok.

release_battle_status(Rank) ->
  mod_arena:cast_to_arena(gm_release_battle_status, [Rank]),
  ok.

%% 修复装备榜数据
gm_repair_rank_equip() ->
    mod_common_rank:gm_repair_equip_rank(),
    ok.

php_send_sys_mail_to_all(Title, Content, CmAttachmentStr, Source, MinLv, MinVip, MaxVip, Important, SendLogType) ->
    lib_mail_api:send_sys_mail_to_all(Title, Content, CmAttachmentStr, Source, MinLv, ?DEFAULT_MAX_LV, MinVip, MaxVip, ?DEFAULT_LOGIN_DAY, SendLogType, ?MOD_NONE, ?MOD_NONE, Important).

php_send_sys_mail_to_all(Title, Content, CmAttachmentStr, Source, MinLv, MaxLv, MinVip, MaxVip, Days, Important, SendLogType) ->
    lib_mail_api:send_sys_mail_to_all(Title, Content, CmAttachmentStr, Source, MinLv, MaxLv, MinVip, MaxVip, Days, SendLogType, ?MOD_NONE, ?MOD_NONE, Important).


%% 指定玩家指定物品列表
send_tar_role_mail(RoleListBin, Title, Content) ->
    RoleList = util:string_to_term(RoleListBin),
    InitResult = [],
    send_tar_role_mail_do(RoleList, Title, Content, 0, InitResult).

%% 全部执行成功返回ok
%% 或返回一个玩家列表
send_tar_role_mail_do([], _, _, _, Result) ->
    if Result == [] -> ok;
        true -> Result
    end;
send_tar_role_mail_do([{RoleId, GoodsList}|Rest], Title, Content, Index, Result) ->
    case is_local_serv(RoleId) of
        true ->
            case check_goods_format(GoodsList) of
                true ->
                    case Index rem 5 == 0 of
                        true ->
                            timer:sleep(urand:rand(250, 750)),
                            lib_mail:send_sys_mail([RoleId], ?MOD_NONE, ?MOD_NONE, Title, Content, GoodsList, ?SEND_LOG_TYPE_YES);
                        _ ->
                            lib_mail:send_sys_mail([RoleId], ?MOD_NONE, ?MOD_NONE, Title, Content, GoodsList, ?SEND_LOG_TYPE_YES)
                    end,
                    send_tar_role_mail_do(Rest, Title, Content, Index+1, Result);
                _ ->
                    ?ERR("goods format error ~p ~p", [RoleId, GoodsList]),
                    send_tar_role_mail_do(Rest, Title, Content, Index+1, [RoleId|Result])
            end;
        _ ->
            send_tar_role_mail_do(Rest, Title, Content, Index, Result)
    end.

is_local_serv(RoleId) ->
    ServerId = mod_player_create:get_serid_by_id(RoleId),
    case config:get_merge_server_ids() of
        [] ->
            false;
        MergeSerIds ->
            lists:member(ServerId, MergeSerIds)
    end.

check_goods_format([]) -> true;
check_goods_format([Goods|Rest]) ->
    case Goods of
        {_GoodsType, _GoodsId, _GoodsNum} ->
            check_goods_format(Rest);
        _ ->
            false
    end.

%% 通知前端更新消息
%% Type: 1非强制性更新/2强制性更新
%% Msg : 消息体
notice_msg(Type, OldMsg, MinLevel) ->
    IsMsgString = is_list(OldMsg) orelse is_binary(OldMsg),
    case is_integer(Type) andalso is_integer(MinLevel) andalso IsMsgString of
        true  ->
            Msg = text_enc:fix_enc(unicode:characters_to_list(OldMsg)),
            {ok, BinData} = pt_110:write(11091, [Type, Msg]),
            mod_chat_agent:send_msg([{all_lv, {MinLevel, 999}, BinData}]),
            ok;
        false ->
            error
    end.

%% return: {总在线玩家数量，托管玩家数量}
get_online_num() ->
    TotalOnline = online_monitor:get_node_online_num(),
    HostingNum  = offline_hosting_api:get_hosting_num(),
    {
        TotalOnline - HostingNum,
        HostingNum
    }.
