%% ---------------------------------------------------------------------------
%% @doc 礼品卡
%% @author hhl
%% @since  2016-11-14
%% @deprecated
%% ---------------------------------------------------------------------------
-module(lib_gift_card).
-include("server.hrl").
-include("common.hrl").
-include("predefine.hrl").
-include("figure.hrl").
-include("errcode.hrl").
-include("goods.hrl").
-include("def_module.hrl").
-include("def_goods.hrl").
-export([
         trigger_card/3,
         web_page_trigger_card/4,
         do_web_page_trigger_card/4,
         extract_mochijson2/2,
         send_reward/8
        ]).

%% 卡号的长度限制
-define(CARD_MIN_LEN, 5).
-define(CARD_MAX_LEN, 30).
-define(CardOpenLv,   30).
-define(VERSION,    "cn").
-define(GAME,     "mrzj").

-define(GIFT_CARD_TYPE_VIP, 5). %% vip礼包卡类型

trigger_card(Ps, CardNo, GoodsId) ->
    #player_status{id = RoleId, source = Source, figure = Figure} = Ps,
    #figure{name = Name, lv = Lv, vip = Vip} = Figure,
    GoodsStatus = lib_goods_do:get_goods_status(),
    GoodsInfo = lib_goods_util:get_goods(GoodsId, GoodsStatus#goods_status.dict),
    case Lv >= ?CardOpenLv of
        false ->
            {false, ?LEVEL_LIMIT};
        true ->
            case util:check_length(CardNo, ?CARD_MIN_LEN, ?CARD_MAX_LEN) of
                false ->
                    {false, ?ERRCODE(err150_gift_card_err_len)};
                true ->
                    case {GoodsId, GoodsInfo} of
                        {0, _} -> %% 物品id为0直接过
                            do_trigger_card(Lv, CardNo, Source, Vip, RoleId, Name, GoodsId);
                        {_, #goods{type = ?GOODS_TYPE_VIP_GIFT_CARD}} ->
                            do_trigger_card(Lv, CardNo, Source, Vip, RoleId, Name, GoodsId);
                        _ ->
                            {false, ?ERRCODE(err150_type_err)}
                    end
            end
    end.

do_trigger_card(Lv, CardNo, Source, Vip, RoleId, Name, GoodsId) ->
    Charge = lib_recharge_data:get_total_rmb(RoleId),
    [GUrl, Appkey] = get_url_appkey(),
    [Game, Version] = [?GAME, ?VERSION],
    NowTime = utime:unixtime(),
    AuthStr = util:md5(lists:concat([Appkey, NowTime, "gift_card"])),
    Url = lists:concat([GUrl, "time=", NowTime, "&method=gift_card&sign=", AuthStr]),
    PostData = [
        {<<"card_no">>, CardNo},
        {<<"source">>, Source},
        {<<"vip_type">>, Vip},
        {<<"unique_id">>, RoleId},
        {<<"role_name">>, Name},
        {<<"game">>, Game},
        {<<"version">>, Version},
        {<<"recharge">>, Charge},
        {<<"role_lv">>, Lv}
    ],
    Body = iolist_to_binary(mochiweb_util:urlencode(PostData)),
    mod_gift_card:send_to_card_server(Url, Body, RoleId, CardNo, gift_card, null, GoodsId),
    ok.

%% ---------------------------------------------------------------------------
%% @doc 在网页推广兑换礼包(php调用)
%% web_page_trigger_card(PlayerId, CardNo, Title, Content) -> reture
%% {ok, 1}|{false, ErrorCode}
%% ErrorCode: 0失败  1成功 2操作过快 3卡号过长 4卡号已经被领取 5玩家不在线
%% lib_gift_card:web_page_trigger_card(4294967297, "SGVlBtPG4zrmZS", <<"V+测试礼包">>, <<"V+测试测试内容">>).
web_page_trigger_card(PlayerId, CardNo, Title, Content) ->
    Key = {web_page_trigger_card, PlayerId},
    NowTime = utime:unixtime(),
    CdRes = case get(Key) of
                undefined -> put(Key, NowTime), true;
                LastTime ->
                    case NowTime - LastTime > 3 of
                        true -> put(Key, NowTime), true;
                        false -> false
                    end
            end,
    %% 是否操作过快
    case CdRes of
        false -> {false, 2}; %% 操作过快
        true ->
            RolePid = misc:get_player_process(PlayerId),
            case lib_player:apply_cast(RolePid, ?APPLY_CALL_STATUS, lib_gift_card, do_web_page_trigger_card, [CardNo, Title, Content]) of
                skip ->
                    {false, 5};
                _ ->
                    {ok, ?SUCCESS}
            end
    end.

%% 请求奖励发送邮件
do_web_page_trigger_card(Ps, CardNo, Title, Content) ->
    #player_status{id = RoleId, source = Source, figure = Figure} = Ps,
    #figure{name = Name, vip = Vip} = Figure,
    case util:check_length(CardNo, ?CARD_MIN_LEN, ?CARD_MAX_LEN) of
        false -> 3; %% 卡号过长
        true ->
            [GUrl, Appkey] = get_url_appkey(),
            [Game, Version] = [?GAME, ?VERSION],
            NowTime = utime:unixtime(),
            AuthStr = util:md5(lists:concat([Appkey, NowTime, "gift_card"])),
            Url = lists:concat([GUrl, "time=", NowTime, "&method=gift_card&sign=", AuthStr]),
            Recharge = lib_recharge_data:get_total_rmb(RoleId),
            PostData = [{card_no, CardNo}, {source, Source}, {vip_type, Vip}, {unique_id, RoleId},
                        {role_name, Name}, {game, Game}, {version, Version}, {recharge, round(Recharge)}],
            StrBody = mochiweb_util:urlencode(PostData),
            mod_gift_card:send_to_card_server(Url, StrBody, RoleId, CardNo, Title, null, Content),
            ok
    end.

extract_mochijson2([], Rest) -> [Rest];
extract_mochijson2([ElmKey | TElmKey],{struct, RestJSON} = A) when is_tuple(A)->
    [ Value || {Key, Rest} <- RestJSON, Key =:= ElmKey, Value <- extract_mochijson2(TElmKey, Rest)];
extract_mochijson2(List, A) ->
    [ Value || B <- A, Value <- extract_mochijson2(List, B)].

%% 发送奖励
send_reward(PS, CardNo, GiftType, CardType, GiftList, GoodsId, T, C) ->
    #player_status{id = RoleId, sid = Sid, figure = #figure{lv = _Lv}} = PS,
    %% 邮件内容
    if
        CardType =:= ?GIFT_CARD_TYPE_VIP andalso GoodsId =/= 0 -> %% vip认证礼包需要删除道具
            GoodsStatus = lib_goods_do:get_goods_status(),
            GoodsInfo = lib_goods_util:get_goods(GoodsId, GoodsStatus#goods_status.dict),
            case lib_goods_api:delete_one_by_id(PS, GoodsId, GoodsInfo#goods.goods_id, 1, vip_gift_card) of
                1 -> %% 删除成功
                    do_send_reward(RoleId, GiftList, T, C),
                    IsSuccess = 1,
                    CostGoods = [{GoodsInfo#goods.goods_id, GoodsId}],
                    ErrorCode = ?ERRCODE(err150_card_ok_send);
                _ ->
                    ErrorCode = ?ERRCODE(err150_type_err),
                    IsSuccess = 0,
                    CostGoods = [],
                    skip
            end;
        CardType =/= ?GIFT_CARD_TYPE_VIP -> %% 不是认证礼包直接发奖励
            do_send_reward(RoleId, GiftList, T, C),
            CostGoods = [],
            IsSuccess = 1,
            ErrorCode = ?ERRCODE(err150_card_ok_send);
        true ->
            CostGoods = [],
            IsSuccess = 0,
            ErrorCode = ?ERRCODE(err150_type_err)
    end,
    lib_log_api:log_gift_card_list(RoleId, CardNo, CardType, GiftType, GiftList, CostGoods, IsSuccess),
    ta_agent_fire:gift_card(PS, [CardNo, CardType, GiftType, true, 1]),
    {ok, BinData} = pt_160:write(16009, [ErrorCode]),
    lib_server_send:send_to_sid(Sid, BinData),
    PS.

do_send_reward(RoleId, GiftList, T, C) ->
    {Title, Content} = if
       T == gift_card -> {utext:get(1600001), utext:get(1600002)};
       true -> {T, C}
    end,
    lib_mail_api:send_sys_mail([RoleId], ?MOD_WELFARE, Title, Content, GiftList).

get_url_appkey() ->
    {Url, AppKey} = data_vsn:get_imgreg_url_and_key(),
    [Url, AppKey].
