<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/6/27
 * Time: 下午2:46
 */

require_once(BASE_ROOT_PATH . '/helper/bonus_helper.php');
require_once(BASE_ROOT_PATH . '/helper/model_helper.php');
require_once(BASE_ROOT_PATH . '/helper/push_helper.php');
require_once(BASE_ROOT_PATH . '/helper/sms_helper.php');
require_once(BASE_ROOT_PATH . '/helper/bonus/parameters.php');
require_once(BASE_ROOT_PATH . '/helper/user_session/favorite.php');
require_once(BASE_ROOT_PATH . '/helper/user_session/anotice.php');
require_once(BASE_ROOT_PATH . '/helper/fcode/mfcode.php');
require_once(BASE_ROOT_PATH . '/helper/fcode/operator.php');
require_once(BASE_ROOT_PATH . '/helper/user_session/fcode.php');
require_once(BASE_ROOT_PATH . '/helper/search/tcp_client.php');
require_once(BASE_ROOT_PATH . '/helper/message/publisher.php');

require_once(BASE_ROOT_PATH . '/helper/async/IAsync.php');
require_once(BASE_ROOT_PATH . '/helper/async/status.php');
require_once(BASE_ROOT_PATH . '/helper/async/register.php');
require_once(BASE_ROOT_PATH . '/helper/async/order.php');
require_once(BASE_ROOT_PATH . '/helper/async/qugc.php');
require_once(BASE_ROOT_PATH . '/helper/async/broadcast_order.php');
require_once(BASE_ROOT_PATH . '/helper/async/broadcast.php');
require_once(BASE_ROOT_PATH . '/helper/async/broadcast/filter.php');
require_once(BASE_ROOT_PATH . '/helper/async/broadcast/operator.php');
require_once(BASE_ROOT_PATH . '/helper/async/broadcast/sender.php');
require_once(BASE_ROOT_PATH . '/helper/async/broadcast/params_table.php');

require_once(BASE_ROOT_PATH . '/helper/order_helper.php');
require_once(BASE_ROOT_PATH . '/helper/fcode/present_manager.php');
require_once(BASE_ROOT_PATH . '/helper/schema_helper.php');
require_once(BASE_ROOT_PATH . '/helper/url_helper.php');

class account_helper
{
    static private $stSysBonus = null;

    public static function invite_bonus($relay_id)
    {
        $last_type = bonus_helper::last_invite_type($relay_id);
        if(is_null($last_type) == false)
        {
            $type = bonus_helper::create_by_paramer($last_type);
            if($type->binded_over() == false && $type->isEnd() == false) {
                return $type->getType_sn();
            }
        }

        $param = bonus\parameters::invite($relay_id);
        $ret = bonus_helper::make_bonus($param,$param['rate_money']);
        if($ret != false) {
            $type_sn = $ret['type_sn'];
            return $type_sn;
        } else {
            return false;
        }
    }

    public static function gain_system($to_id, $amount)
    {
        if(self::$stSysBonus == null) {
            self::$stSysBonus = new bonus\sys_bonus();
        }

        if(self::$stSysBonus->bind_over())
        {
            $param = self::$stSysBonus->gen_param($rates);
            $ret = bonus_helper::make_bonus($param,$rates);
            if($ret != false) {
                $type_sn = $ret['type_sn'];
                self::$stSysBonus->reset($type_sn);
            } else {
                return false;
            }
        }

        $bonus = bonus_helper::send(self::$stSysBonus->type_sn(),[$to_id]);
        return $bonus;
    }

    public static function gain_bonus($from_id,$to_id,$amount)
    {
        $pred_from = new predeposit_helper($from_id);
        $bonus_rate = $pred_from->find_bonus($amount);
        if($bonus_rate == false) {
            return false;
        }

        $minfo = new member_info($from_id);
        $param = \bonus\parameters::shake_gain($minfo->member_id(),$minfo->mobile(),$minfo->nickname(),$bonus_rate['rate'],$bonus_rate['amount']);

        $ret = bonus_helper::make_bonus($param,$param['rate_money']);
        if($ret != false)
        {
            $to_minfo = new member_info($to_id);
            $thief = $to_minfo->nickname();
            bonus_helper::withold_money($from_id,$bonus_rate['rate'],$amount,bonus_helper::send_bonus_withold);
            $pred_from->handout_bonus($amount,$ret['type_sn'],$thief,"{$thief}摇走了您{$amount}元的红包.",\bonus\type::MakeShakeGainType);
            $bonusex = bonus_helper::send($ret['type_sn'],[$to_id]);
            push_helper::stolen_bonus($minfo,$to_minfo,$amount);
            return $bonusex;
        } else {
            return false;
        }
    }

    public static function lost_bonus($from_id,$to_id,$amount)
    {
        $pred_from = new predeposit_helper($from_id);
        $bonus_rate = $pred_from->find_bonus($amount);
        if($bonus_rate == false) {
            return false;
        }
        $rate = $bonus_rate['rate'];
        $amount = $bonus_rate['amount'];

        $minfo = new member_info($from_id);
        $param = \bonus\parameters::shake_lost($minfo->member_id(),$minfo->mobile(),$minfo->nickname(),$bonus_rate['rate'],$bonus_rate['amount']);
        $ret = bonus_helper::make_bonus($param,$param['rate_money']);
        if($ret != false)
        {
            $to_info = new member_info($to_id);
            $pred_from->handout_bonus($amount,$ret['type_sn'],$to_info->nickname(),"您摇丢了{$amount}的红包.",\bonus\type::MakeShakeLostType);
            bonus_helper::withold_money($from_id,$rate,$amount,bonus_helper::send_bonus_withold);
            $bonusex = bonus_helper::send($ret['type_sn'],[$to_id]);
            push_helper::fly_bonus($minfo,$to_info,$amount);
            return $bonusex;
        } else {
            return false;
        }
    }

    private static function pay_refund($member_id,$amount,$bonus_name)
    {
//        $param = self::base_param($amount,1);
//        self::admin_param($param);
//        $param['make_type'] = \bonus\type::MakePayRefundType;
//        $param['type_name'] = $bonus_name;
//
//        $ret = bonus_helper::make_bonus($param);
//        if($ret != false)
//        {
//            bonus_helper::send($ret['type_sn'],array($member_id));
//            push_helper::order_refund_bonus($member_id,$amount);
//        } else {
//            Log::record("给用户 {$member_id} 退款{$amount}失败.");
//        }
    }

    private static function use_bonus($order_sn, $member_id)
    {
        $mod_order = Model('order');
        $order = $mod_order->getOrderInfo(['order_sn' => $order_sn]);

        $pd_amount = $order['pd_amount'];
        $bonus_rate = $order['bonus_rate'];
        if(empty($bonus_rate)) {
            $bonus_rate = [30 => $pd_amount];
        } else {
            $bonus_rate = unserialize($bonus_rate);
        }

        $pred = new predeposit_helper($member_id);
        $pred->pay_bonus($bonus_rate);
    }

    public static function bonus_refund($type_sn,$member_id)
    {
        $type = bonus\type::create_by_sn($type_sn);
        $amount = $type->remain_amount();
        $rate = $type->bonus_rate();
        if(empty($rate)) $rate = 30;

        $param = \bonus\parameters::bonus_refund($rate,$amount);
        $ret = bonus_helper::make_bonus($param,$param['rate_money']);
        if($ret != false)
        {
            $bonus = bonus_helper::send($ret['type_sn'],[$member_id]);
            if($bonus != false) {
                push_helper::bonus_refund($member_id,$amount);
            }
        }
        else {
            Log::record("给用户 {$member_id} 红包退款{$amount}失败.");
        }
    }

    private static function send_bonus($param,$rates,array $member_ids)
    {
        $ret = bonus_helper::make_bonus($param,$rates);
        if($ret != false)
        {
            $type_sn = $ret['type_sn'];
            $items = bonus_helper::send($type_sn,$member_ids);
            if($items != false)
            {
                $result = [];
                foreach ($items as $bonus_param) {
                    $bonus = bonus\user_bonus::create_by_param($bonus_param);
                    $user_id = $bonus->user_id();
                    $result[$user_id] = $bonus;
                }
                return $result;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    }

    public static function add_bonus($rate,$amount,$member_ids,$type_name)
    {
        $param = \bonus\parameters::admin_fixed(intval($rate),doubleval($amount),count($member_ids),$type_name);
        $fix_bonus = self::send_bonus($param,$param['rate_money'],$member_ids);
        if($fix_bonus != false) {
            return true;
        } else {
            return false;
        }
    }

    public static function appreciate($sender_id,$rate,$amount,$toid,$bless)
    {
        $param = bonus\parameters::appreciate($sender_id,intval($rate),$amount,$bless);
        $pred = new predeposit_helper($sender_id);

        $rate_moneys[] = ['rate' => $rate,'num' => 1,'amount' => $amount,'hold_amount' => $amount];
        $ret = $pred->make_bonus($param,$rate_moneys);
        if($ret == false) return false;
        $pred->inc_rate_version();
        $type_sn = $ret['type_sn'];
        $ret = bonus_helper::send($type_sn,[$toid]);
        return ($ret != false);
    }

    public static function withhold_bonus($rate,$amount,$member_id)
    {
        $rates = [intval($rate) => doubleval($amount)];
        $ret = bonus_helper::withold($member_id,$rates,bonus_helper::send_bonus_withold);
        if($ret) {
            $pred = new predeposit_helper($member_id);
            $pred->reduce_pred($amount);
        } else {
            Log::record('扣除预存款失败',Log::ERR);
        }
        return $ret;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static function onPredRefund($change_type,$member_id,$sn,$refund_id)
    {
//        $order_sn = $sn;
//        $order = order::create_by_sn($order_sn);
//        if($order == false) {
//            self::pay_refund($member_id,$pd_amount,"退款红包");
//        } else {
//            self::pay_refund($member_id,$order->pd_amount(),"退款红包");
//        }
    }

    public static function onPredeposit($change_type,$member_id,$sn)
    {
        if($change_type == 'order_pay' || $change_type == 'order_freeze')
        {
            self::use_bonus($sn,$member_id);
        }
        elseif($change_type == 'order_cancel')
        {
            //发送给该用户一个同等额度的红包
            $mod_order = Model('order');
            $order = $mod_order->getOrderInfo(['order_sn' => $sn,'buyer_id' => $member_id]);
            if(!empty($order)) {
                $pay_sn = $order['pay_sn'];
                QueueClient::push('onAsyncOrderCancel',['pay_sn' => $pay_sn]);
            }
        }
        elseif($change_type == 'refund') { //发送给该用户一个同等额度的红包

        }
        elseif($change_type == 'bonus_refund') { // 发送给该用户一个同等额度的红包
            self::bonus_refund($sn,$member_id);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static function onLogin($member_id)
    {
        if(session_helper::isapp()) {
            $updata['client_type'] = session_helper::client_type();
            $updata['client_version'] = session_helper::version_code();
            Model('member')->editMember(['member_id' => $member_id], $updata);
        }

        relation_helper::onLogin($member_id);

        $anotice  = new user_session\anotice();
        $anotice->onStatus();

        $favorate = new user_session\favorite();
        $favorate->onLogin();

        $fcode = new user_session\fcode();
        $fcode->onStatus();

        QueueClient::push('onAsyncStatus',['member_id' => $member_id]);

        $member_info = Model('member')->getMemberInfoByID($member_id);
        $rewared_inviter = intval($member_info['rewared_inviter']);
        $inviter_id = intval($member_info['inviter_id']);

        if(session_helper::isapp() && session_helper::logined() && $rewared_inviter == 0) {
            QueueClient::push('onAsyncRegister',['user' => $member_id,'inviter' => $inviter_id]);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static function onStatus($member_id)
    {
        relation_helper::onLogin($member_id);

        $member_info = Model('member')->getMemberInfoByID($member_id);
        $updata['member_login_num']  = $member_info['member_login_num'] + 1;
        $updata['member_login_time'] = time();
        $updata['member_old_login_time'] = $member_info['member_login_time'];
        $updata['member_login_ip'] = getIp();
        $updata['member_old_login_ip'] = $member_info['member_login_ip'];
        if(session_helper::isapp()) {
            $updata['client_type'] = session_helper::client_type();
            $updata['client_version'] = session_helper::version_code();
        }
        Model('member')->editMember(['member_id' => $member_id], $updata);

        $anotice  = new user_session\anotice();
        $anotice->onStatus();

        $favorate = new user_session\favorite();
        $favorate->onLogin();

        $fcode = new user_session\fcode();
        $fcode->onStatus();

        $rewared_inviter = intval($member_info['rewared_inviter']);
        $inviter_id = intval($member_info['inviter_id']);

        if(session_helper::isapp() && session_helper::logined() && $rewared_inviter == 0) {
            QueueClient::async_push('onAsyncRegister',['user' => $member_id,'inviter' => $inviter_id],2);
        }
        QueueClient::async_push('onAsyncStatus',['member_id' => $member_id],1);
    }

    public static function onAsyncStatus($member_id)
    {
        try
        {
            $iPusher = new async\status($member_id);
            $iPusher->run();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    public static function onAsyncTopup($member_id)
    {
        try
        {
            $iPusher = new async\status($member_id);
            $iPusher->topup();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static function onRegister($member_id,$relay_id)
    {
        if(session_helper::isapp()) {
            $updata['client_type'] = session_helper::client_type();
            $updata['client_version'] = session_helper::version_code();
            Model('member')->editMember(['member_id' => $member_id], $updata);
        }

        if($relay_id > 0) {
            relation_helper::onSubscribe($member_id,$relay_id);
            relation_helper::onInvite($relay_id,$member_id);
        }
        relation_helper::onRegister($member_id);
        $publisher = new message\publisher();
        if($relay_id > 0) {
            $publisher->add_follow($relay_id,[$member_id]);
        }

        $publisher->add_inviter($member_id,$relay_id);
        if(session_helper::logined() && session_helper::isapp()) {
            QueueClient::async_push('onAsyncRegister',['user' => $member_id,'inviter' => $relay_id],2);
        }
    }

    public static function onAsyncRegister($user,$inviter)
    {
        try
        {
            $iPusher = new async\register($user,$inviter);
            $iPusher->run();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static function onAsyncOrderPaied($pay_sn)
    {
        try
        {
            $iPusher = new async\order($pay_sn);
            $iPusher->onPaied();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    public static function onAsyncOrderSended($pay_sn,$logistics_no,$logistics_company)
    {
        try
        {
            $iPusher = new async\order($pay_sn);
            $iPusher->onSended($logistics_no,$logistics_company);
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    public static function onAsyncOrderComplete($pay_sn)
    {
        try
        {
            $iPusher = new async\order($pay_sn);
            $iPusher->onComplete();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }

    public static function onAsyncBroadcastOrder($pay_sn,$amount,$days)
    {
        try
        {
            $iPusher = new async\broadcast_order($pay_sn);
            $iPusher->order_bonus($amount,$days);
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    public static function onAsyncBroadcastNormal($filters,$oper_param,$send_params)
    {
        try
        {
            $sms_type = $send_params['type'];

            $memf_params = $filters['member_filters'];
            $mem_filters = async\filter::create($memf_params);
            $oper = async\operator::create($oper_param);

            $smsf_params = $filters['sms_filters'];
            $sms_filters = async\filter::create($smsf_params);

            $sender = async\sender::create($sms_filters,$send_params);
            $broad = new async\broadcast($mem_filters,$oper,$sender,$sms_type);
            $broad->run();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }

    public static function onAsyncOrderCancel($pay_sn)
    {
        try
        {
            $iPusher = new async\order($pay_sn);
            $iPusher->onCancel();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }

    public static function onAsyncOrderEvaluate($pay_sn)
    {
        try
        {
            $iPusher = new async\order($pay_sn);
            $iPusher->onEvaluate();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static function onAsyncUgcPublish($spid)
    {
        try
        {
            $iPusher = new async\qugc($spid);
            $iPusher->onPublish();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    public static function onAsyncUgcDel($spid)
    {
        try
        {
            $iPusher = new async\qugc($spid);
            $iPusher->onDel();
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    public static function onAsyncUgcSubmit($spid,$user)
    {
        try
        {
            $iPusher = new async\qugc($spid);
            $iPusher->onSubmit($user);
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    public static function onAsyncUgcSupport($spid,$comment_id,$user)
    {
        try
        {
            $iPusher = new async\qugc($spid);
            $iPusher->onSupport($comment_id,$user);
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    public static function onAsyncUgcComment($spid,$commentid,$userid)
    {
        try
        {
            $iPusher = new async\qugc($spid);
            $iPusher->onComment($commentid,$userid);
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }
    public static function onAsyncUgcAppreciate($spid,$user,$rate,$amount)
    {
        try
        {
            $iPusher = new async\qugc($spid);
            $iPusher->onAppreciate($user,$rate,$amount);
        } catch (Exception $ex) {
            Log::record($ex->getMessage(),Log::ERR);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static function onAsyncFollow($user,$follow)
    {

    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static function onAsyncGoodsDiscount($gid)
    {

    }
}