%% ---------------------------------------------------------------------------
%% @doc lib_guild_order_mod.erl
%% @author  zmh
%% @since  2019-12-23
%% @deprecated 社团派单
%% 备注 20201104 此版本之后无须做任务内容 拼单人数凑满即可完成任务
%% ---------------------------------------------------------------------------
-module(lib_guild_order_mod).
-export([
    load_guild_orders/1,
    change_order_state/3,
    trigger_order/3
]).
-compile(export_all).

-include("guild.hrl").
-include("sql_guild.hrl").
-include("errcode.hrl").
-include("common.hrl").
-include("figure.hrl").
-include("def_fun.hrl").
-include("def_module.hrl").
-include("def_event.hrl").
-include("rec_event.hrl").
-include("server.hrl").
-include("goods.hrl").
-include("predefine.hrl").
-include("battle.hrl").
-include("scene.hrl").
-include("guild_labor.hrl").
-include("def_id_create.hrl").
-include("role.hrl").

%%任务加载
load_guild_orders(RoleId)->
    Sql = io_lib:format(?sql_guild_order_select_all, [RoleId]),
    List = db:get_all(Sql),
    Orders = to_trans_order(List,[]),
    Orders.

to_trans_order([],Orders)->
    Orders;
to_trans_order([[OrderID,Cfg,Status,Content0,Teams0,FTime]|T],Orders)->
    Content = util:bitstring_to_term(Content0),
    Teams   = util:bitstring_to_term(Teams0),
    Order = #guild_order{
        id = OrderID,
        cfgid = Cfg,
        status = Status,
        content = Content,
        teams = Teams,
        finish_time = FTime
    },
    to_trans_order(T,[Order|Orders]).



%%状态变更
change_order_state(OpTy,OrderID,Status)->
    #player_status{
        id=RoleID,
        figure=#figure{name=RName},
        guild=GuildStatus
    }=Status,
    #status_guild{id=GuildId,name=GName,orders=Orders}=GuildStatus,
    HasOrder = lib_daily:get_count(RoleID,?MOD_GUILD,1),
    CheckList = [
        {check_order_times,Status,HasOrder},
        {check_guild_enter,GuildId},
        {check_own_order,OrderID,Orders},
        {check_order_state,OpTy,OrderID,Orders}
    ],
    case util:check_lists(?MODULE,CheckList) of
        true -> %%选定
            NOrders = do_change_orders(RoleID,OpTy,OrderID,Orders),
            NGuildStatus = GuildStatus#status_guild{orders=NOrders},
            NStatus = Status#player_status{guild=NGuildStatus},
            {ok,NStatus};
        {ok,NOrder} -> %%出发 结算
            #guild_order{teams=Teams,cfgid=Cfg, content = Content} = NOrder,
            NOrders = do_change_orders(RoleID,OpTy,OrderID,Orders),
            Len = length(Teams),
            {ok,Bin} = pt_400:write(40040,[OrderID,length(Teams),Cfg]),
            lib_server_send:send_to_uid(RoleID,Bin),
            case custom_unite_buff:check_buff(Status,order_up) of
                {ok,UniteAdd}->
                    skip;
                _->
                    UniteAdd=0
            end,
            case data_guild:get_order_base(Cfg) of
                 #base_guild_order{color=Color,max_num=MNum,awards=Awards, ai_ratio = AiRatio, people_ratio = PeoPleRatio}->
                     %% 宠物技能，增加ai奖励比例
                     AddRatio = lib_pet_api:pet_life_skill_about_guild_order(Status),
                     F = fun(Id, Sum) ->
                         ?IF(Id > 10, Sum + PeoPleRatio, Sum + AiRatio + AddRatio)
                         end,
                     AllRatio = lists:foldl(F, 0, Teams),
                     BaseRatio =
                     case data_guild:get(base_reward) of
                         Ratio when is_integer(Ratio) -> Ratio;
                         _ -> 0
                     end,
                     FinalRatio = BaseRatio + AllRatio +  UniteAdd*Len,
                     FinalAwards = calc_award(Awards, FinalRatio, []),
                     lib_goods_api:send_reward_with_mail(RoleID, #produce{reward=FinalAwards,type=guild_order},?MOD_GUILD);
                _->
                    Color = 0, MNum = 0,Awards=[],
                    skip
            end,
            NGuildStatus = GuildStatus#status_guild{orders=NOrders},
            NStatus = Status#player_status{guild=NGuildStatus},
            %% 发起者获得感谢信
            UniqueId = mod_id_create:get_new_id(?ORDER_ID_CREATE),
            lib_player:apply_cast(RoleID, ?APPLY_CAST_STATUS,
                guild_thank, add_order_thank_packet,
                [GuildId, UniqueId, RoleID, Teams, Cfg, Content]),

            case custom_unite_buff:check_times(NStatus,order_up)>0 of
                true->
                    custom_unite_buff:cost_times(Status,order_up,1,100);
                _->
                    lib_daily:increment(RoleID,?MOD_GUILD,1)
            end,
            %% 嗨点活动
            mod_hi_point:success_end(RoleID, ?MOD_GUILD, 3),
            custom_act_adventure:do_trigger_adventure_task(RoleID, ?MOD_GUILD, 3),
            contract_task_api:place_order_trigger(RoleID, 1),
            lib_guild_labor:task_active(RoleID,?GTASK_TYPE_ORDER),
            brocast_help_tv(GuildId,RName,Cfg,Teams,[]),
            lib_custom_act_slices:task_event(NStatus,?MOD_GUILD,3),
            lib_activitycalen_api:role_success_end_activity(RoleID, ?MOD_GUILD, 3, 1),
            lib_log_api:log_guild_order(GuildId,GName,RoleID,RName,0,OrderID,Color,MNum,Teams,Awards),
            {ok,NStatus};
        {false,ErrCode}->
            {false,ErrCode}
    end.

calc_award([], _, FinalAward) ->
    FinalAward;
calc_award([{Type, GoodsTypeId, Num}|T], Ratio, FinalAward) ->
    RealNum = umath:floor(Num * Ratio / 100),
    calc_award(T, Ratio, [{Type, GoodsTypeId, RealNum} | FinalAward]);
calc_award([_|T], Ratio, FinalAward) ->
    calc_award(T, Ratio, FinalAward).

%%邀请助手
invite_guild_member(OrderID,1,Status)->
    #player_status{id=RoleID,guild=GuildStatus}=Status,
    #status_guild{id=GuildId,orders=Orders}=GuildStatus,
    CheckList = [
        {check_guild_enter,GuildId},
        {check_own_order,OrderID,Orders},
        {check_order_anchor,1,OrderID,Orders}
    ],
    case util:check_lists(?MODULE,CheckList) of
        {ok,{_Cfg,Order}}->
            #guild_order{id=OrderId,teams=Teams}=Order,
            FRid   = length(Teams)+1,
            NOrder = Order#guild_order{teams=[FRid|Teams]},
            NOrders = lists:keystore(OrderId,#guild_order.id,Orders,NOrder),
            NGuildStatus = GuildStatus#status_guild{orders=NOrders},
            NStatus = Status#player_status{guild=NGuildStatus},
            update_notice_order(RoleID,NOrder),
            db_guild_order_insert(RoleID,NOrder),
            {ok,NStatus};
        {false,Res}->
            {false,Res}
    end;
%%剔除助手
invite_guild_member(OrderID,2,Status)->
    #player_status{id=RoleID,guild=GuildStatus}=Status,
    #status_guild{id=GuildId,orders=Orders}=GuildStatus,
    CheckList = [
        {check_guild_enter,GuildId},
        {check_own_order,OrderID,Orders},
        {check_order_anchor,2,OrderID,Orders}
    ],
    case util:check_lists(?MODULE,CheckList) of
        {ok,{_Cfg,Order}}->
            #guild_order{id=OrderId,teams=Teams0}=Order,
            Teams  = [FRid||FRid<-Teams0,FRid>10],
            NOrder = Order#guild_order{teams=Teams},
            NOrders = lists:keystore(OrderId,#guild_order.id,Orders,NOrder),
            NGuildStatus = GuildStatus#status_guild{orders=NOrders},
            NStatus = Status#player_status{guild=NGuildStatus},
            update_notice_order(RoleID,NOrder),
            db_guild_order_insert(RoleID,NOrder),
            {ok,NStatus};
        {false,Res}->
            {false,Res}
    end;
invite_guild_member(OrderID,IRid,Status)->
    #player_status{id=RoleID,figure=#figure{name=Name,lv=Lv,vip=Vip,sup_vip=SVip},guild=GuildStatus}=Status,
    #status_guild{id=GuildId,orders=Orders}=GuildStatus,
    CheckList = [
        {check_guild_enter,GuildId},
        {check_own_order,OrderID,Orders},
        {check_order_anchor,0,OrderID,Orders}
    ],
    case util:check_lists(?MODULE,CheckList) of
        {ok,{Cfg,_Order}}->
            {ok,Bin} = pt_400:write(40038,[RoleID,Lv,Vip,SVip,Name,Cfg,OrderID]),
            lib_server_send:send_to_uid(IRid,Bin),
            {ok,Status};
        {false,Res}->
            {false,Res}
    end.

%%邀请回复
reply_guild_order(Status,FGuildID,FRid,UOrderId)->
    #player_status{id=RoleID,guild=GuildStatus}=Status,
    #status_guild{id=GuildId,orders=Orders}=GuildStatus,
    CheckList = [
        {check_guild_same,GuildId,FGuildID},
        {check_own_order,UOrderId,Orders},
        {check_order_state,UOrderId,Orders},
        {check_order_anchor_reply,FRid,Orders}
    ],
    case util:check_lists(?MODULE,CheckList) of
        {ok,Order}->
            #guild_order{id=OrderId,teams=Teams}=Order,
            NOrder = Order#guild_order{teams=[FRid|Teams]},
            NOrders = lists:keystore(OrderId,#guild_order.id,Orders,NOrder),
            NGuildStatus = GuildStatus#status_guild{orders=NOrders},
            Res = ?SUCCESS,
            NStatus = Status#player_status{guild=NGuildStatus},
            update_notice_order(RoleID,NOrder),
            db_guild_order_insert(RoleID,NOrder);
        {false,Res}->
            NStatus = Status
    end,
    {ok,Bin} = pt_400:write(40039,[Res]),
    lib_server_send:send_to_uid(FRid,Bin),
    {ok,NStatus}.

%%发起感谢
thanks_teams(OrderId,Status)->
    #player_status{id=RoleID,guild=GuildStatus,figure=Figure}=Status,
    #figure{name=RName}=Figure,
    #status_guild{id=GuildId,name=GName,orders=Orders}=GuildStatus,
    case lists:keytake(OrderId,#guild_order.id,Orders) of
        {value,Order,TailOrders}->
            #guild_order{status=CurS,cfgid=Cfg,teams=Teams}=Order,
            case CurS =:= ?OVER_ORDER of
                true->
                    NOrder = Order#guild_order{status=?CLOSE_ORDER},
                    NOrders = [NOrder|TailOrders],
                    NGuildStatus = GuildStatus#status_guild{orders=NOrders},
                    NStatus = Status#player_status{guild=NGuildStatus},
                    % {ok,Bin} = pt_400:write(40042,[Figure,Cfg]),
                    #base_guild_order{
                        color=Color, max_num=MNum,
                        %thank_reward=ThankAwards,
                        order_reward=OrderAwards
                    }=data_guild:get_order_base(Cfg),

                    % ThankProduce = #produce{
                    %    reward=ThankAwards,
                    %    type=guild_order,
                    %    title=utext:get(4000024),
                    %    content=utext:get(4000025,[RName])
                    % },
                    % awards_teams(Teams,ThankProduce,Bin),

                    db_guild_order_insert(RoleID,NOrder),

                    lib_achievement_api:guild_thank_event(Status, 1),

                    % lib_goods_api:send_reward_with_mail(RoleID, #produce{reward=OrderAwards,type=guild_order},?MOD_GUILD),
                    update_notice_order(RoleID,NOrder),
                    lib_log_api:log_guild_order(GuildId,GName,RoleID,RName,1,OrderId,Color,MNum,Teams,OrderAwards),
                    {ok,NStatus};
                _->
                    {false,?ERRCODE(err400_order_need_finish)}
            end;
        _->
            {false,?FAIL}
    end.

awards_teams([],_Produce,_Bin)->
    ok;
awards_teams([H|T],Produce,Bin)->
    case H>10 of
        true->
            lib_goods_api:send_reward_with_mail(H, Produce, ?MOD_GUILD),
            lib_server_send:send_to_uid(H,Bin),
            awards_teams(T,Produce,Bin);
        _->
            awards_teams(T,Produce,Bin)
    end.

%%需要把其他选中的置0清除拼单
do_change_orders(RoleID,OpTy,OrderID,Orders)->
    NOrders = reset_anchored_orders(RoleID,Orders,OrderID,[]),
    case lists:keytake(OrderID,#guild_order.id,NOrders) of
        {value,Order,TailOrders}->
            NOrder = case OpTy of
                0->
                    Order#guild_order{status=?ANCHOR_ORDER,teams=[]};
                _->
                    Order#guild_order{status=?OVER_ORDER}
            end,
            update_notice_order(RoleID,NOrder),
            db_guild_order_insert(RoleID,NOrder),
            [NOrder|TailOrders];
        _->
            NOrders
    end.

reset_anchored_orders(_RoleID,[],_OrderID,NOrders)->
    NOrders;
reset_anchored_orders(RoleID,[H|T],OrderID,Orders)->
    #guild_order{id=Id,status=CurS}=H,
    case CurS =:= ?ANCHOR_ORDER of
        true ->
            case Id =:= OrderID of
                true->
                    NewH = H;
                _->
                    NewH = H#guild_order{status=0,teams=[]},
                    db_guild_order_insert(RoleID,NewH)
            end,
            reset_anchored_orders(RoleID,T,OrderID,[NewH|Orders]);
        _->
            reset_anchored_orders(RoleID,T,OrderID,[H|Orders])
    end.


%%获取面板数据
get_pane_orders(Status)->
    #player_status{id=RoleID,guild=GuildStatus}=Status,
    #status_guild{orders=Orders}=GuildStatus,
    HasOrder = lib_daily:get_count(RoleID,?MOD_GUILD,1),
    HasRefresh = lib_daily:get_count(RoleID,?MOD_GUILD,2),
    NOrders = case length(Orders)=<0 of
        true->
            init_guild_orders(Status);
        _->
            Orders
    end,
    OrderList = pack_order_list(NOrders,[]),
    {ok,Bin} = pt_400:write(40035,[HasOrder,HasRefresh,OrderList]),
    lib_server_send:send_to_uid(RoleID,Bin),
    NGuildStatus = GuildStatus#status_guild{orders=NOrders},
    Status#player_status{guild=NGuildStatus}.

%%任务刷新
refresh_orders(Status)->
    #player_status{id=RoleID,guild=GuildStatus}=Status,
    HasOrder   = lib_daily:get_count(RoleID,?MOD_GUILD,1),
    Max = get_max_accept(Status),
    case HasOrder<Max of
        true->
            HasRefresh = lib_daily:get_count(RoleID,?MOD_GUILD,2),
            FreeMax    = data_guild:get(order_refresh_free),
            Costs      = case HasRefresh<FreeMax of
                true->
                    [];
                _->
                    data_guild:get(order_refresh_cost)
            end,
            Res = case Costs /= [] of
                true->
                    lib_goods_api:cost_object_list_with_check(Status, Costs, guild_order, ["guild order refresh"]);
                _->
                    {true,Status,[]}
            end,
            case Res of
                {true,TmpStatus,_}->
                    NOrders = case HasRefresh rem 3 of
                        0 when HasRefresh>0->
                            init_guild_orders(3,TmpStatus);
                        _->
                            init_guild_orders(TmpStatus)
                    end,
                    NGuildStatus = GuildStatus#status_guild{orders=NOrders},
                    NStatus      = TmpStatus#player_status{guild=NGuildStatus},
                    lib_daily:increment(RoleID,?MOD_GUILD,2),
                    {ok,NStatus};
                {false,Err,_}->
                    {false,Err}
            end;
        _->
            {false,?ERRCODE(err400_guild_order_max)}
    end.


get_max_accept(Status)->
    case custom_unite_buff:check_times(Status,order_up)>0 of
        true->
            data_guild:get(accept_limit)+1;
        _->
            data_guild:get(accept_limit)
    end.

pack_order_list([],Orders)->
    Orders;
pack_order_list([H|T],Orders)->
    #guild_order{
        id = OrderID,
        cfgid = Cfg,
        status = State,
        teams  = Teams,
        content = [{_,_,_,CurV,Max}],
        finish_time = FTime
    }=H,
    TeamHeads = make_join_team(Teams,[]),
    pack_order_list(T,[{OrderID,Cfg,State,CurV,Max,TeamHeads,FTime}|Orders]).

make_join_team([],TeamHeads)->
    TeamHeads;
make_join_team([H|T],TeamHeads)->
    case H>10 of
        true->
            RoleShow = lib_role:get_role_show(H),
            #ets_role_show{figure=Figure}=RoleShow;
        _->
            Figure = #figure{id=H}
    end,

    make_join_team(T,[Figure|TeamHeads]).

%%订单初始化
init_guild_orders(Status)->
    init_guild_orders(0,Status).
init_guild_orders(Color,Status)->
    #player_status{
        id=RoleID,
        figure=Figure
    }=Status,
    #figure{lv=Lv}=Figure,
    CfgOrders0 = data_guild:get_all_orders(),
    CfgOrderWeights  = filter_cfg_order(CfgOrders0,Lv,[]),
    CfgColorWeights  = filter_cfg_color_order(CfgOrderWeights,Color,[]),
    case CfgColorWeights /= [] of
            true->
                MustId = urand:rand_with_weight(CfgColorWeights),
                #base_guild_order{color=InitColor}=data_guild:get_order_base(MustId),
                Num = 5;
            _->
                Num = 6,
                MustId = 0,
                InitColor = 1
    end,
    [Orders0,Max] = rand_enough_orders(CfgOrderWeights,Num,[],InitColor),
    Orders = case MustId>0 of
        true->
            ulists:list_shuffle([MustId|Orders0]);
        _->
            Orders0
    end,
    InitOrders = make_init_orders(RoleID,Orders,1,[],Max,false),
    InitOrders.

rand_enough_orders([],_,Orders,Max)->
    [Orders,Max];
rand_enough_orders(_,0,Orders,Max)->
    [Orders,Max];
rand_enough_orders(CfgOrderWeights,Num,Orders,Max)->
    Order = urand:rand_with_weight(CfgOrderWeights),
    #base_guild_order{color=Color}=data_guild:get_order_base(Order),
    NMax = max(Max,Color),
    rand_enough_orders(CfgOrderWeights,Num-1,[Order|Orders],NMax).

%%拼接初始数据
make_init_orders(_RoleID,[],_,InitOrders,_Max,_IsChoose)->
    InitOrders;
make_init_orders(RoleID,[H|T],Id,InitOrders,Max,IsChoose)->
    #base_guild_order{
        content = Content,
        color = Color
    } = data_guild:get_order_base(H),
    case Color =:= Max of
        true when IsChoose =:= false ->
            Status = ?ANCHOR_ORDER,
            NIsChoose = true;
        _->
            Status = ?INIT_ORDER,
            NIsChoose = IsChoose
    end,
    Order = #guild_order{
        id = Id,
        cfgid = H,
        status = Status,
        content = Content
    },
    db_guild_order_insert(RoleID,Order),
    make_init_orders(RoleID,T,Id+1,[Order|InitOrders],Max,NIsChoose).

%%等级过滤  拼接权重列表
filter_cfg_order([],_Lv,CfgOrderWeights)->
    CfgOrderWeights;
filter_cfg_order([H|T],Lv,CfgOrderWeights)->
    #base_guild_order{
        weight = W,
        min_lv = MinLv,
        max_lv = MaxLv
    } = data_guild:get_order_base(H),
    case MinLv=<Lv andalso Lv=<MaxLv of
        true->
            filter_cfg_order(T,Lv,[{W,H}|CfgOrderWeights]);
        _->
            filter_cfg_order(T,Lv,CfgOrderWeights)
    end.

filter_cfg_color_order([],_Color,CfgColorWeights)->
    CfgColorWeights;
filter_cfg_color_order(_CfgOrderWeights,0,CfgColorWeights)->
    CfgColorWeights;
filter_cfg_color_order([{W,H}|T],Color,CfgColorWeights)->
    #base_guild_order{
        color = C
    } = data_guild:get_order_base(H),
    case C>=Color of
        true->
            filter_cfg_color_order(T,Color,[{W,H}|CfgColorWeights]);
        _->
            filter_cfg_color_order(T,Color,CfgColorWeights)
    end.


%%主动更新单个任务
update_notice_order(RoleID,Order)->
    #guild_order{
        id = OrderID,
        cfgid = Cfg,
        status = State,
        teams  = Teams,
        content = [{_,_,_,CurV,Max}],
        finish_time = FTime
    }=Order,
    TeamHeads = make_join_team(Teams,[]),
    {ok,Bin} = pt_400:write(40065,[OrderID,Cfg,State,CurV,Max,TeamHeads,FTime]),
    lib_server_send:send_to_uid(RoleID,Bin).



db_guild_order_insert(RoleID,GuildOrder) ->
    #guild_order{
        id = OrderID,
        cfgid = Cfg,
        status = State,
        content = Content0,
        teams = Teams0,
        finish_time = FTime
    }=GuildOrder,
    Content = util:term_to_string(Content0),
    Teams = util:term_to_string(Teams0),
    Sql = io_lib:format(?sql_guild_order_insert, [OrderID,RoleID,Cfg,State,Content,Teams,FTime]),
    db:execute(Sql).

% mon_die(Minfo, ?BATTLE_SIGN_PLAYER, AtterId)->
%     case Minfo of
%         #scene_object{mon=#scene_mon{mid=MonID}} ->
%             trigger_order(AtterId,2,MonID);
%         _ ->
%             skip
%     end;
mon_die(_,_,_)->ok.

% %% 通关副本
% handle_event(PS, #event_callback{type_id = ?EVENT_DUNGEON_SUCCESS, data = Data}) when is_record(PS, player_status) ->
%     #callback_dungeon_succ{dun_id = DunID} = Data,
%     {ok, NewPS} = trigger_guild_order(PS, 1, DunID),
%     {ok, NewPS};
handle_event(Status, #event_callback{type_id = ?EVENT_FOUR_CLOCK}) when is_record(Status, player_status) ->
    #player_status{
        guild = StatusGuild
    } = Status,
    NOrders = init_guild_orders(Status),
    NGuildStatus = StatusGuild#status_guild{orders=NOrders},
    NStatus = Status#player_status{guild=NGuildStatus},
    get_pane_orders(NStatus),
    {ok, NStatus};
handle_event(Status, _Event) ->
    {ok, Status}.


trigger_order(RoleID,Type,Value)->
    lib_player:apply_cast(RoleID, ?APPLY_CAST_SAVE, ?MODULE, trigger_guild_order, [Type,Value]).

trigger_guild_order(Status,Type,Value)->
    #player_status{id=RoleID,guild=GuildStatus}=Status,
    #status_guild{id = GuildId,orders=Orders}=GuildStatus,
    case GuildId>0 of
        true->
            NOders = trigger_guild_order(RoleID,Orders,Type,Value,[]),
            NGuildStatus = GuildStatus#status_guild{orders=NOders},
            NStatus=Status#player_status{guild=NGuildStatus},
            {ok,NStatus};

        _->
            {ok,Status}
    end.

trigger_guild_order(_RoleID,[],_Type,_Value,NOders)->
    NOders;
trigger_guild_order(RoleID,[Order|T],Type,Value,NOders)->
    NOrder = do_trigger_guild_order(RoleID,Order,Type,Value),
    trigger_guild_order(RoleID,T,Type,Value,[NOrder|NOders]).

do_trigger_guild_order(RoleID,Order,Type,Value)->
    case Order of
        #guild_order{id=OrderId,status=?ALIVE_ORDER,cfgid=Cfg,content=Content,teams=Teams}->
            {IsOver,IsUpdate,_CurV,NContent} = update_order_process(Content,Type,Value),
            NOrder = case IsOver of
                true->
                    case length(Teams)=<0 of
                        true->
                            Order#guild_order{status=?CLOSE_ORDER,content=NContent,finish_time=utime:unixtime()};
                        _->
                            Order#guild_order{status=?OVER_ORDER,content=NContent,finish_time=utime:unixtime()}
                    end;
                _->
                    Order#guild_order{content=NContent}
            end,
            IsUpdate andalso db_guild_order_update(RoleID,Order),
            IsOver andalso begin
                update_notice_order(RoleID,NOrder),
                {ok,Bin} = pt_400:write(40040,[OrderId,length(Teams),Cfg]),
                lib_server_send:send_to_uid(RoleID,Bin),
                case data_guild:get_order_base(Cfg) of
                     #base_guild_order{awards=Awards}->
                        lib_goods_api:send_reward_with_mail(RoleID, #produce{reward=Awards,type=guild_order},?MOD_GUILD);
                    _->
                        skip
                end
            end,
            NOrder;
        _->
            Order
    end.

update_order_process([],_,_)->
    {false,false,0,[]};
update_order_process([{Type,Aim,Scene,Max,Max}],Type,_V)->
    {true,{Type,Aim,Scene,Max,Max}};
update_order_process([{Type,Aim,Scene,CurV,Max}],Type,Aim)->
    case CurV+1>=Max of
        true->
            {true,true,Max,[{Type,Aim,Scene,Max,Max}]};
        _->
            {false,true,CurV+1,[{Type,Aim,Scene,CurV+1,Max}]}
    end;
update_order_process(Content,_,_)->
    {false,false,0,Content}.

db_guild_order_update(RoleID,Order)->
    #guild_order{id=OrderID,status=State,content=Content0,finish_time=FTime}=Order,
    Content = util:term_to_string(Content0),
    Sql = io_lib:format(?sql_guild_order_update, [State,Content,FTime,OrderID,RoleID]),
    db:execute(Sql).

brocast_help_tv(GuildId,RName,Cfg,[],Names)->
    case length(Names)>0 of
        true->
            TeamNames = util:join_bitstring(Names, <<"、"/utf8>>),
            #base_guild_order{color=Color,name=OName}=data_guild:get_order_base(Cfg),
            Id = case Color of
                1->
                    16;
                2->
                    17;
                _->
                    18
            end,
            Msg = [TeamNames,RName,OName],
            lib_chat:send_TV({guild, GuildId}, ?MOD_GUILD, Id, Msg);
        _->
            skip
    end;
brocast_help_tv(GuildId,RName,Cfg,[H|T],Names)->
    case H>10 of
        true->
            RoleShow = lib_role:get_role_show(H),
            #ets_role_show{figure=#figure{name=HName}}=RoleShow;
        _->
            HName = data_role_name:get_guild_helper_name()
    end,
    brocast_help_tv(GuildId,RName,Cfg,T,[HName|Names]).


check({check_order_times,Status,HasOrder})->
    Max = get_max_accept(Status),
    case HasOrder<Max of
        true->
            true;
        _->
            {false,?ERRCODE(err400_guild_order_max)}
    end;

check({check_guild_same,GuildA,GuildB})->
    case GuildA == GuildB andalso GuildA>0 of
        true->
            true;
        _->
            {false,?ERRCODE(err400_need_same_guild)}
    end;
check({check_order_anchor_reply,FRid,Orders})->
    Anchors = [O||O<-Orders,O#guild_order.status =:= ?ANCHOR_ORDER],
    case Anchors of
        [H|_]->
            #guild_order{cfgid=Cfg,teams=Teams}=H,
            %% 队伍中没有发起者的id
            L = length(Teams) + 1,
            case data_guild:get_order_base(Cfg) of
                #base_guild_order{max_num=Max} ->
                    ignore;
                _ -> Max = 0
            end,
            case lists:member(FRid,Teams) of
                true->
                    {false,?ERRCODE(err400_no_need_join_again)};
                _->
                    case L>=Max of
                        true->
                            {false,?ERRCODE(err400_no_need_more_team)};
                        _ when Max =< 0 ->
                            {false,?ERRCODE(missing_config)};
                        _->
                            {ok,H}
                    end
            end;
        _->
            {false,?ERRCODE(err400_guild_order_miss)}
    end;
check({check_order_anchor,OpTy,OrderID,Orders})->
    case lists:keyfind(OrderID,#guild_order.id,Orders) of
        #guild_order{cfgid=Cfg,status=?ANCHOR_ORDER,teams=Teams}=Order->
            case OpTy of
                1->
                    TeamsLen = length(Teams) + 1,
                    HelperLen = length([A||A<-Teams,A<10]),
                    case data_guild:get_order_base(Cfg) of
                        #base_guild_order{max_num=Max} ->
                            ignore;
                        _ -> Max = 0
                    end,
                    if
                        Max =< 0 ->
                            {false,?ERRCODE(missing_config)};
                        HelperLen > 0 ->
                            {false,?ERRCODE(err400_need_no_more_fake_helper)};
                        TeamsLen >= Max ->
                            {false,?ERRCODE(err400_no_need_more_team)};
                        true ->
                            {ok,{Cfg,Order}}
                    end;
                2->
                    case length([A||A<-Teams,A<10])=<0 of
                        true->
                            {false,?ERRCODE(err400_has_no_fake_helper)};
                        _->
                             {ok,{Cfg,Order}}
                    end;
                _->
                    TeamsLen = length(Teams) + 1,
                    case data_guild:get_order_base(Cfg) of
                        #base_guild_order{max_num=Max} ->
                            ignore;
                        _ -> Max = 0
                    end,
                    if
                        Max =< 0 ->
                            {false,?ERRCODE(missing_config)};
                        TeamsLen >= Max ->
                            {false,?ERRCODE(err400_order_max_people_num)};
                        true ->
                            {ok,{Cfg,Order}}
                    end
            end;
        _->
            {false,?ERRCODE(err400_need_anchor_order)}
    end;

check({check_order_state,OrderID,Orders})->
    case lists:keyfind(OrderID,#guild_order.id,Orders) of
        #guild_order{status=?ANCHOR_ORDER}->
            true;
        _->
            {false,?ERRCODE(err400_this_order_over)}
    end;

check({check_order_state,0,OrderID,Orders})->
    case lists:keyfind(OrderID,#guild_order.id,Orders) of
        #guild_order{status=?ANCHOR_ORDER}->
            {false,?ERRCODE(err400_order_repeate_anchor)};
        #guild_order{status=?ALIVE_ORDER}->
            {false,?ERRCODE(err400_order_already_alive)};
        #guild_order{status=?OVER_ORDER}->
            {false,?ERRCODE(err400_order_already_over)};
        #guild_order{status=?CLOSE_ORDER}->
            {false,?ERRCODE(err400_order_already_over)};
        _->
            true
    end;
check({check_order_state,_,OrderID,Orders})->
    Anchors = [O||O<-Orders,O#guild_order.status =:= ?ANCHOR_ORDER],
    case lists:keyfind(OrderID,#guild_order.id,Anchors) of
        #guild_order{cfgid=Cfg,teams=Teams}=Order->
            CurNum = length(Teams)+1,
            case data_guild:get_order_base(Cfg) of
                #base_guild_order{max_num=_MaxNum} when CurNum>=2 ->
                    {ok,Order#guild_order{status=?OVER_ORDER}};
                _->
                    {false,?ERRCODE(err400_order_need_more_helper)}
            end;
        _->
            {false,?ERRCODE(err400_order_need_anchor)}
    end;
check({check_own_order,OrderID,Orders})->
    case lists:keymember(OrderID,#guild_order.id,Orders) of
        true->
            true;
        _->
            {false,?FAIL}
    end;

check({check_guild_enter,GuildId})->
    case GuildId>0 of
        true->
            true;
        _->
            {false,?ERRCODE(err400_not_in_guild)}
    end.