<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/4/16
 * Time: 下午6:08
 */

require_once(BASE_ROOT_PATH . '/helper/bonus_helper.php');
require_once(BASE_ROOT_PATH . '/helper/session_helper.php');
require_once(BASE_ROOT_PATH . '/helper/text_filter.php');
require_once(BASE_ROOT_PATH . '/helper/shaker_helper.php');
require_once(BASE_ROOT_PATH . '/helper/ranklist_helper.php');
require_once(BASE_ROOT_PATH . '/helper/special_helper.php');
require_once(BASE_ROOT_PATH . '/helper/util_helper.php');
require_once(BASE_ROOT_PATH . '/helper/search/tcp_client.php');
require_once(BASE_ROOT_PATH . '/helper/search/util.php');
require_once(BASE_ROOT_PATH . '/helper/search_param.php');
require_once(BASE_ROOT_PATH . '/helper/goods_helper.php');
require_once(BASE_ROOT_PATH . '/helper/push_helper.php');
require_once(BASE_ROOT_PATH . '/helper/url_helper.php');
require_once(BASE_ROOT_PATH . '/helper/invite_helper.php');
require_once(BASE_ROOT_PATH . '/helper/activity_helper.php');


class member_bonusControl extends mbMemberControl
{
    const sampler_goods = 30;
    const msg_malice_bonus = '为避免恶意欺诈，只有下单后的用户才能发送红包给好友.';
    private $mPred;

    public function __construct() {
        parent::__construct();
        $this->mPred = new predeposit_helper($_SESSION['member_id']);
    }

    public function predepositexOp()
    {
        $result = [];
        $result['bonus_total']  = $this->mPred->total_bonus();

        $bonus_state = $this->mPred->bonus_state();
        $expiring = $bonus_state['expiring'];
        $warning = "";
        if(!empty($expiring))
        {
            $expiring = intval($expiring * 100 + 0.5);
            if($expiring > 0) {
                $expiring = $expiring / 100;
                $warning = "您有{$expiring}元红包即将过期";
            }
        }

        $result = array_merge($result,$bonus_state);
        $bonus_rate = $this->mPred->bonus_rate();

        if($bonus_rate != null)
        {
            $rates = $bonus_rate->format();
            $rates_money = [];
            foreach ($rates as $rate => $money) {
                $item['rate']  = $rate;
                $item['total'] = $money;
                $rates_money[] = $item;
            }
        } else {
            $rates_money = null;
        }

        if(empty($rates_money)) {
            $result['bonus_rate'] = null;
        } else {
            $result['bonus_rate'] = $rates_money;
        }
        $result['send_bless'] = $this->cur_bless();
        $result['avatar'] = session_helper::avatar();
        $result['sub_titles'] = ['shake' => '','invite' => '赚百分百红包','friends' => '','bonus_detail' => $warning];
        $this->update_available_bonus($result['bonus_total']);

        return self::outsuccess($result);
    }

    private function update_available_bonus($amount)
    {
        if(isset($_SESSION['available_bonus']))
        {
            $old = intval($_SESSION['available_bonus'] * 100 + 0.5);
            $cur_cent = intval($amount * 100 + 0.5);
            if($old == $cur_cent) {
                $fEdit = false;
            } else {
                $fEdit = true;
            }
        } else {
            $fEdit = true;
        }
        if($fEdit)
        {
            $_SESSION['available_bonus'] = $amount;
            $member = Model('member');
            $member->editMember(['member_id' => session_helper::memberid()],['available_bonus' => $amount]);
        }
    }

    private function cur_bless()
    {
        if(isset($_SESSION['cur_share_id']) && $_SESSION['cur_share_id'] > 0) {
            $share = bonus_helper::get_share($_SESSION['cur_share_id']);
        } else {
            $share = bonus_helper::get_share();
            $_SESSION['cur_share_id'] = $share['share_id'];
            return $share['title'];
        }
        return $share['title'];
    }

    private function reset_share()
    {
        $share = bonus_helper::get_share();
        $_SESSION['cur_share_id'] = $share['share_id'];
    }

    public function predepositOp()
    {
        $result = [];
        $result['predeposit_total']  = $this->mPred->total_bonus();
        $result['predeposit_freeze'] = 0;

        $bonus_state = $this->mPred->bonus_state();
        $result = array_merge($result,$bonus_state);
        $bonus_rate = $this->mPred->bonus_rate();

        if($bonus_rate != null)
        {
            $rates = $bonus_rate->format();
            $rates_money = [];
            foreach ($rates as $rate => $money) {
                $item['rate']  = $rate;
                $item['total'] = $money;
                $rates_money[] = $item;
            }
        } else {
            $rates_money = null;
        }

        if(empty($rates_money)) {
            $result['bonus_rate'] = null;
        } else {
            $result['bonus_rate'] = $rates_money;
        }
        $result['avatar'] = session_helper::avatar();
        $result['sub_titles'] = ['shake' => '偷点地主家的余粮','invite' => '赚百分百红包','friends' => ''];
        $result['shake_sub']  = "偷点地主家的余粮";
        $result['invite_sub'] = "赚百分百红包";
        $result['friends_sub'] = "";

        return self::outsuccess($result);
    }

    private function fill_param($input,$bonus_rate)
    {
        $param = $input;
        $param['sender_id'] = $_SESSION['member_id'];
        $param['sender_mobile'] = $_SESSION['member_mobile'];
        $param['sender_name'] = session_helper::nickname();
        if($bonus_rate > 0) {
            $param['bonus_rate'] = $bonus_rate;
        }
        $param['share_id'] = $_SESSION['cur_share_id'];

        return $param;
    }

    public function makeOp()
    {
        if(session_helper::can_send() == false) {
            return self::outerr(errcode::ErrBonus,self::msg_malice_bonus);
        }

        if (intval($_GET['bonus_rate']) > 0) {
            $bonus_rate = intval($_GET['bonus_rate']);
        } else {
            return self::outerr(errcode::ErrParamter,'红包折扣率错误，客户端需要升级新版本.');
        }

        $param = $this->fill_param($_GET,$bonus_rate);
        $type = bonus_helper::create_type_input($param);

        if(!$this->mPred->person_enough($type->getTotal_amount(),$bonus_rate)) {
            return self::outerr(errcode::ErrBonusNotEnough,'余额不够发送红包');
        }

        $rate_moneys = [];
        if($type->isFixedAmount()) {
            $item['amount'] = $type->fixed_money();
        } else {
            $item['amount'] = $type->getTotal_amount();
        }
        $item['hold_amount'] = $type->getTotal_amount();
        $item['num'] = $type->getTotal_num();
        $item['rate'] = $bonus_rate;
        $rate_moneys[] = $item;

        $ret = $this->mPred->make_bonus($type->get_param(),$rate_moneys);
        if($ret === false) {
            return self::outerr(errcode::ErrBonus,"生成红包失败.");
        }
        else
        {
            $type_sn = $ret['type_sn'];
            $url = url_helper::bonus_open_url($type_sn);
            $this->share_info($type,$title,$sub_title,$img_url);
            $this->reset_share();

            $strids = $_GET['toids'];
            if(!empty($strids))
            {
                $mids = explode(',',$strids);
                $bonusex = bonus_helper::send($type_sn,$mids);
                if($bonusex != false) {
                    push_helper::send_bonus(session_helper::memberid(),$mids);
                }
            }

            return self::outsuccess(array('type_sn' => $ret,
                'url' => "{$url}",
                'title' => $title,
                'sub_title' => $sub_title,
                'img_url' => $img_url));
        }
    }

    private function share_info(bonus\type $type,&$title,&$sub_title,&$img_url)
    {
        $share = bonus_helper::get_share($type->share_id());
        $title = $type->bless();

        if(empty($title) || $title == '特权红包，内购正品行货美妆') {
            $title = $share['title'];
        }

        $sub_title = $share['sub_title'] . "\n\n点击领取";
        $img_url = $share['img_url'];
    }

    private function random_cids()
    {
        $type_sn = "member_bonus";
        $time = 0;
        $cids = [];
        if(array_key_exists('goods_sampler',$_SESSION) && array_key_exists($type_sn,$_SESSION['goods_sampler']))
        {
            $cids = $_SESSION['goods_sampler'][$type_sn]['cids'];
            $time = $_SESSION['goods_sampler'][$type_sn]['time'];
        }

        if($time < time() - 86400 || empty($cids))
        {
            if(session_helper::is_man()) {
                $cids = activity\goods_sampler::instance()->fetch_male(self::sampler_goods);
            } else {
                $cids = activity\goods_sampler::instance()->fetch_female(self::sampler_goods);
            }

            if(!empty($cids)) {
                $_SESSION['goods_sampler'][$type_sn]['cids'] = $cids;
                $_SESSION['goods_sampler'][$type_sn]['time'] = time();
            }
        }

        return $cids;
    }

    public function match_goodsexOp()
    {
        $cids = $this->random_cids();
        if(empty($cids))
        {
            return self::outsuccess(['special_list' => null,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'mobile_page' => mobile_page(0)]);
        }

        $model_goods = Model('goods');
        $items = $model_goods->getGoodsListByColorDistinct(['goods_commonid' => ['in',$cids]],goods_helper::fieldstr,'','');

        if(empty($items))
        {
            return self::outsuccess(['special_list' => null,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'mobile_page' => mobile_page(1)]);
        }
        else
        {
            $tmp =[];
            foreach ($items as $item) {
                $commonid = intval($item['goods_commonid']);
                $tmp[$commonid] = $item;
            }

            $goods_list = [];
            foreach ($cids as $cid)
            {
                if(array_key_exists($cid,$tmp)) {
                    $goods_list[] = $tmp[$cid];
                }
            }

            foreach ($goods_list as $goods) {
                $goods_id = intval($goods['goods_id']);
                $goods_ids[] = $goods_id;
            }

            $helper = new goods_helper();
            $ret = $helper->summary($goods_list,$related_goods);
            $block = special_formater::format_goods($goods_ids,"",$ret['sort_summary']);

            $blocks = [];
            if($this->page_no() == 1 && !empty($block)) {
                $divider = special_formater::def_divider();
                $blocks[] = $divider;
            }
            $blocks[] = $block;

            return self::outsuccess(['special_list' => $blocks,
                'summary'  => $ret['summary'],
                'groupbuy' => $ret['groupbuy'],
                'limitime' => $ret['limitime'],
                'bundling' => $ret['bundling'],
                'mobile_page' => mobile_page(1)]);
        }
    }

    public function match_goodsOp()
    {
        $bonus_rate = $this->mPred->bonus_rate();
        $rate_moneys = $bonus_rate->format();
        $price = bonus_helper::match_price($rate_moneys);

        if($price == false)
        {
            return self::outsuccess(array('special_list' => null,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'mobile_page' => mobile_page(0)));
        }
        else
        {
            $params = ['price' => $price,'page_no' => $this->page_no(),'page_size' => $this->page_size()];
            $result = search\search_client::instance()->match_price($params);
            if($result == false)
            {
                return self::outsuccess(array('special_list' => null,
                    'summary'  => null,
                    'groupbuy' => null,
                    'limitime' => null,
                    'bundling' => null,
                    'mobile_page' => mobile_page(0)));
            }

            $cids = $result['cids'];
            $model_goods = Model('goods');
            $items = $model_goods->getGoodsListByColorDistinct(array('goods_commonid' => array('in',$cids)),goods_helper::fieldstr,'','');
            $page_count = intval($result['page_count']);

            if(empty($items))
            {
                return self::outsuccess(array('special_list' => null,
                    'summary'  => null,
                    'groupbuy' => null,
                    'limitime' => null,
                    'bundling' => null,
                    'mobile_page' => mobile_page($page_count)));
            }
            else
            {
                $tmp =[];
                foreach ($items as $item) {
                    $commonid = intval($item['goods_commonid']);
                    $tmp[$commonid] = $item;
                }

                $goods_list = [];
                foreach ($cids as $cid)
                {
                    if(array_key_exists($cid,$tmp)) {
                        $goods_list[] = $tmp[$cid];
                    }
                }

                foreach ($goods_list as $goods) {
                    $goods_id = intval($goods['goods_id']);
                    $goods_ids[] = $goods_id;
                }

                $helper = new goods_helper();
                $ret = $helper->summary($goods_list,$related_goods);

                $blocks = [];
                $block = special_formater::format_goods($goods_ids,"",$ret['sort_summary']);
                if($this->page_no() == 1 && !empty($block))
                {
                    global $config;
                    $spid = $config['goods_sampler']['mbonus_spid'];

                    $banners   = special_manager::instance()->special($spid,$unused_gids);
                    foreach ($banners as $tmp) {
                        $blocks[] = $tmp;
                    }
                }
                $blocks[] = $block;

                return self::outsuccess(array('special_list' => $blocks,
                    'summary'  => $ret['summary'],
                    'groupbuy' => $ret['groupbuy'],
                    'limitime' => $ret['limitime'],
                    'bundling' => $ret['bundling'],
                    'mobile_page' => mobile_page($page_count)));
            }
        }
    }

    public function makeby_bonusOp()
    {
        if(session_helper::can_send() == false) {
            return self::outerr(errcode::ErrBonus,self::msg_malice_bonus);
        }

        if(!isset($_GET['bonus_sn']) || empty($_GET['bonus_sn'])) {
            return self::outerr(errcode::ErrParamter,"需要红包序列号.");
        }

        $bonus  = bonus\user_bonus::create_by_sn($_GET['bonus_sn']);
        if($bonus->expired()) {
            return self::outerr(errcode::ErrBonus,"该红包已经过期，不能再发送.");
        }

        $param = $this->fill_param($_GET,$bonus->bonus_rate());
        $type = bonus_helper::create_type_input($param);

        $type_amount  = intval($type->getTotal_amount() * 100 + 0.5);
        $bonus_amount = intval($bonus->remain_amount()  * 100 + 0.5);
        if($type_amount > $bonus_amount) {
            return self::outerr(errcode::ErrBonusNotEnough,'该红包余额不足发送红包');
        }

        $rate_moneys = [];
        if($type->isFixedAmount()) {
            $item['amount'] = $type->fixed_money();
        } else {
            $item['amount'] = $type->getTotal_amount();
        }
        $item['hold_amount'] = $type->getTotal_amount();
        $item['num'] = $type->getTotal_num();
        $item['rate'] = $bonus->bonus_rate();
        $rate_moneys[] = $item;

        $ret = $this->mPred->makeby_bonus($type->get_param(),$rate_moneys,$bonus->bonus_sn());
        if($ret === false) {
            return self::outerr(errcode::ErrBonus,"生成红包失败.");
        }
        else
        {
            $type_sn = $ret['type_sn'];
            $url = url_helper::bonus_open_url($type_sn);
            $this->share_info($type,$title,$sub_title,$img_url);
            $this->reset_share();

            return self::outsuccess(array('type_sn' => $ret,
                'url' => "{$url}",
                'title' => $title,
                'sub_title' => $sub_title,
                'img_url' => $img_url));
        }
    }

    public function inviteOp()
    {
        $info = invite_helper::share_info(session_helper::share_id());
        return self::outsuccess(['type_sn' => "",
                                 'url' => url_helper::inviter_url(),
                                 'title' => $info['title'],
                                 'sub_title' => $info['sub_title'],
                                 'img_url' => $info['img']]);
    }

    public function invite_pageOp()
    {
        return self::outsuccess(['direct_uri' => url_helper::inviter_url()],"redirect");
    }

    public function shareOp()
    {
        if(!isset($_GET['type_sn']) || empty($_GET['type_sn'])) {
            return self::outerr(errcode::ErrParamter,"需要红包序列号.");
        }
        $type_sn = $_GET['type_sn'];
        $type = bonus\type::create_by_sn($type_sn);
        $this->share_info($type,$title,$sub_title,$img_url);
        $url = url_helper::bonus_open_url($type_sn);
        return self::outsuccess(array('type_sn' => $type_sn, 'url' => "{$url}",
            'title' => $title,
            'sub_title' => $sub_title,
            'img_url' => $img_url));
    }

    public function send_listexOp()
    {
        $type_infos = $this->send_listex($pages);
        if($this->page_no() == 1) {
            $tip_blocks = $this->tip_block('send',count($type_infos));
        } else {
            $tip_blocks = false;
        }

        if($type_infos == null)
        {
            if($tip_blocks == false) $tip_blocks = null;
            return self::outsuccess(array('special_list' => $tip_blocks,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'typeinfos'  => $type_infos,
                'mobile_page' => mobile_page($pages)));
        }
        else
        {
            $blocks = [];
            if($tip_blocks != false)
            {
                foreach ($tip_blocks as $block) {
                    $blocks[] = $block;
                }
            }

            $block = special_formater::format_type($type_infos);
            $blocks[] = $block;

            return self::outsuccess(array('special_list' => $blocks,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'typeinfos'   => $type_infos,
                'mobile_page' => mobile_page($pages)));
        }
    }

    private function send_listex(&$pages)
    {
        $mod_type = Model('bonus_type');
        $cond['sender_id|relayer_id'] = array('_multi'=>true,$_SESSION['member_id'],$_SESSION['member_id']);
        $cond['make_type'] = array('in',array(bonus\type::MakeSendType,bonus\type::MakeInviteType));
        $count = $mod_type->getTypeCount($cond);
        if($count == 0) {
            $pages = 0;
            return null;
        }

        $items = $mod_type->getTypeList($cond,$this->page_size(),'*','type_id desc');
        $type_infos = [];
        foreach($items as $val)
        {
            $type = bonus\type::create_by_paramer($val);

            $item["type_sn"] = $type->getType_sn();
            $item["type_bless"] = $type->bless();
            $item["send_type"] = $type->send_type();

            if($type->make_type() == bonus\type::MakeInviteType) {
                $item["sender_name"] = "邀请好友红包";
            }
            else
            {
                if($type->isFixedAmount()) {
                    $item["sender_name"] = "普通红包";
                } else {
                    $item["sender_name"] = "拼手气红包";
                }
            }
            //$item["sender_name"] = $type->sender_name();
            $item["total_amount"] = $type->getTotal_amount();
            $item["total_num"] = $type->getTotal_num();
            $item["remain_amount"] = $type->remain_amount();
            $item["bonus_rate"]  =  $type->bonus_rate();
            $item["binded_num"] = $type->binded_num();
            $item["send_start_date"] = $type->get_start_time();
            $item["send_end_date"] = $type->get_end_time();
            $item["make_type"] = $type->make_type();
            $item["is_end"] = $type->isEnd();
            $item["binded_over"] = $type->getTotal_num() == $type->binded_num();

            $type_sn = $type->getType_sn();
            $open_url   = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=open&client_type=wap&type_sn={$type_sn}";
            $detail_url = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=detail&client_type=wap&type_sn={$type_sn}";

            $item["open_url"] = $open_url;
            $item["detail_url"] = $detail_url;
            $type_infos[] = $item;
        }

        $pages = $this->pages($count);
        return $type_infos;
    }

    private function tip_block($state,$count)
    {
        if(is_publish())
        {
            if($state == 'usable') {
                $special_id = $count > 0 ? 151 : 149;
            }
            elseif($state == 'expiring') {
                $special_id = $count > 0 ? 150 : 150;
            }
            elseif($state == 'used') {
                $special_id = 153;
            }
            elseif($state == 'expired') {
                $special_id = 0;
            }
            elseif($state == 'send') {
                $special_id = $count == 0 ? 152 : 0;
            }
            else {
                $special_id = 0;
            }
        }
        else
        {
            if($state == 'usable') {
                $special_id = $count > 0 ? 151 : 149;
            }
            elseif($state == 'expiring') {
                $special_id = $count > 0 ? 150 : 150;
            }
            elseif($state == 'used') {
                $special_id = 153;
            }
            elseif($state == 'expired') {
                $special_id = 0;
            }
            elseif($state == 'send') {
                $special_id = $count == 0 ? 152 : 0;
            }
            else {
                $special_id = 0;
            }
        }
        if($special_id == 0) return false;

        $helper = new special_formater($special_id);
        $blocks = $helper->format($goods_ids);

        return $blocks;
    }

    public function topupOp()
    {
        $items = $this->mPred->topup_bonus($_SESSION['member_mobile']);
        $this->async_topup();
        if($items === false) {
            return self::outsuccess(array("count" => 0,'total_amount' => 0.00));
        }
        else
        {
            $total_amount = 0.00;
            $max_rate = 0;
            $max_share = 0;

            $result = [];
            foreach ($items as $item)
            {
                $bonus = bonus\user_bonus::create_by_param($item);
                $type = bonus\type::create_by_sn($bonus->type_sn());
                $user_id = $type->sender_id();
                $member = new member_info($user_id);
                $avatar = $member->avatar();

                if($type->binded_over() == false && $type->getTotal_num())
                {
                    $share_num = $type->getTotal_num() - $type->binded_num();
                    if($max_share < $share_num) {
                        $result['max_share']['avatar'] = $avatar;
                        $result['max_share']['count']  = $share_num;
                        $result['max_share']['total_amount'] = $item['bonus_value'];//$type->getTotal_amount();
                        $result['max_share']['rate'] = $type->bonus_rate();
                        $result['max_share']['type_sn'] = $type->getType_sn();
                        $max_share = $share_num;
                    }
                }

                $rate = $bonus->bonus_rate();
                if ($max_rate < $rate)
                {
                    $result['max_rate']['avatar'] = $avatar;
                    $result['max_rate']['rate'] = $rate;
                    $result['max_rate']['type_sn'] = $type->getType_sn();
                    $max_rate = $rate;
                }
                $total_amount += doubleval($item['bonus_value']);
            }
            $result['max_rate']['total_amount'] = $total_amount;
            $result['max_rate']['count'] = count($items);

            if(!empty($result['max_share'])) {
                $info = $result['max_share'];
                $count = intval($info['count']);
                $title = "恭喜获得{$count}个可分享红包";
                $sub_title = "分享给小伙伴，大家一起抢。";
                $btn_type  = 'send';
                $btn_title = '发红包';
            }
            else
            {
                $info = $result['max_rate'];
                $count = intval($info['count']);
                $total_amount = $info['total_amount'];
                $title = "您领了{$count}个红包";
                $sub_title = "总共{$total_amount}元，已到账";
                $btn_type  = 'detail';
                $btn_title = '查看红包';
            }

            $detail_url = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=detail&client_type=wap&type_sn={$info['type_sn']}";
            return self::outsuccess(array("count" => $count, 'total_amount' => $info['total_amount'],
                'title' => $title,'sub_title' => $sub_title,
                'avatar' => $info['avatar'],
                'rate' => $info['rate'],
                'type_sn' => $info['type_sn'],
                'btn_type' => $btn_type,
                'btn_title' => $btn_title,
                'detail_url' => $detail_url));
        }
    }

    private function async_topup()
    {
        $last_topup = intval($_SESSION['last_topup_time']);
        if(time() - $last_topup > 7 * 86400) {
            QueueClient::push('onAsyncTopup',['member_id' => session_helper::memberid()]);
            $_SESSION['last_topup_time'] = time();
        }
    }

    public function topupexOp()
    {
        $items = $this->mPred->topup_bonus($_SESSION['member_mobile']);
        $this->async_topup();

        if($items === false) {
            return self::outsuccess(array("count" => 0,'total_amount' => 0.00));
        }
        else
        {
            $total_amount = 0.00;
            $max_rate = 0;
            $avatar = RESOURCE_SITE_URL . '/mobile/defimg/female.png';
            $type_sn = '';
            foreach ($items as $item)
            {
                $bonus = bonus\user_bonus::create_by_param($item);
                $rate = $bonus->bonus_rate();
                if ($max_rate < $rate) {
                    $type = bonus\type::create_by_sn($bonus->type_sn());
                    $user_id = $type->sender_id();
                    $member = new member_info($user_id);
                    $avatar = $member->avatar();
                    $max_rate = $rate;
                    $type_sn = $type->getType_sn();
                }
                $total_amount += doubleval($item['bonus_value']);
            }

            $count = count($items);
            $title = "您新领了{$count}个， 总额价值{$total_amount}元的红包.";
            $detail_url = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=detail&client_type=wap&type_sn={$type_sn}";

            return self::outsuccess(array("count" => $count, 'total_amount' => $total_amount,
                'title' => $title, 'avatar' => $avatar, 'rate' => $max_rate,
                'type_sn' => $type_sn, 'detail_url' => $detail_url));
        }
    }

    public function recv_listexOp()
    {
        $bonus = $this->recv_list($state,$count,$pages);
        if($this->page_no() == 1) {
            $tip_blocks = $this->tip_block($state,$count);
        } else {
            $tip_blocks = false;
        }

        if($bonus == null)
        {
            if($tip_blocks == false) $tip_blocks = null;
            return self::outsuccess(array('special_list' => $tip_blocks,
                'summary'  => null,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'bonuses'  => $bonus,
                'mobile_page' => mobile_page($pages)));
        }
        else
        {
            $blocks = [];
            if($tip_blocks != false)
            {
                foreach ($tip_blocks as $block) {
                    $blocks[] = $block;
                }
            }

            $block = special_formater::format_bonus($bonus);
            $blocks[] = $block;

            return self::outsuccess(array('special_list' => $blocks,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'bonuses'  => $bonus,
                'mobile_page' => mobile_page($pages)));
        }
    }

    //我收到的红包
    public function recv_listOp()
    {
        $bonus = $this->recv_list($state,$count,$pages);
        if($bonus == null) {
            return self::outsuccess(array('bonuses' => array(), 'mobile_page' => mobile_page($pages)));
        }

        return self::outsuccess(array('bonuses' => $bonus,'mobile_page' => mobile_page($pages)));
    }

    private function recv_cond(&$state,&$order_by)
    {
        static $stQuerys = array('usable','expiring','used','expired');
        static $day_secs = 24 * 3600;

        $cond = array('user_id' => $_SESSION['member_id'],'bonus_status' => 3);

        $query_state = $_GET['query_state'];
        if(!empty($query_state) && in_array($query_state,$stQuerys))
        {
            $state = $query_state;
            if($query_state == 'usable') {
                $cond['usable_time'] = ['gt',time()];
                $cond['remain_amount'] = array('gt','0.00');
                $cond['expired'] = 0;
                $order_by = 'grab_time DESC';
            } elseif ($query_state == 'expiring') {
                $cond['usable_time&usable_time'] = ['_multi'=>true,['gt',time()],['elt',time() + 5 * $day_secs]];
                $cond['remain_amount'] = array('gt','0.00');
                $cond['expired'] = 0;
                $order_by = 'grab_time DESC';
            } elseif ($query_state == 'used') {
                $cond['remain_amount'] = '0.00';
                $cond['expired'] = 0;
                $order_by = 'grab_time DESC';
            } elseif ($query_state == 'expired') {
                $cond['expired'] = 1;
                $cond['usable_time'] = ['lt',time()];
                $cond['remain_amount'] = ['gt','0.00'];
                $order_by = 'bonus_rate DESC,bonus_id DESC';
            } else {
                return false;
            }
        }

        return $cond;
    }

    private function recv_list(&$state,&$count,&$pages)
    {
        $mod_bonus = Model('user_bonus');
        $cond = $this->recv_cond($state,$order_by);

        $count = $mod_bonus->getBonusCount($cond);
        if($count == 0) {
            $pages = 0;
            return null;
        }

        $pages = $this->pages($count);
        if($this->page_no() > $pages) {
            return null;
        }

        $items = $mod_bonus->getBonusList($cond,'*',$order_by,$this->page_size(),$count);
        $type_ids = array();
        foreach ($items as $val) {
            array_push($type_ids,intval($val['type_id']));
        }

        $types = array();
        $type_items = Model('bonus_type')->getTypeList(array('type_id' => array('in',$type_ids)));
        foreach ($type_items as $val) {
            $type = bonus\type::create_by_paramer($val);
            $types[$type->getType_id()] = $type;
        }

        $result = [];
        foreach($items as $val)
        {
            $user_bonus = bonus\user_bonus::create_by_param($val);

            $item['bonus_sn'] = $user_bonus->bonus_sn();
            $item['bonus_value'] = $user_bonus->bonus_value();
            $item['remain_amount'] = $user_bonus->remain_amount();
            $item['usable_time'] = $user_bonus->usable_time();
            $item['expired'] = $user_bonus->expired();
            $item['spend_over'] = $user_bonus->spend_over();
            $item['get_time'] = $user_bonus->get_time();
            $bonus_rate = $user_bonus->bonus_rate();
            $item['bonus_rate'] = empty($bonus_rate)  ? 30 : $bonus_rate;

            if(array_key_exists($user_bonus->type_id(),$types) == false) {
                continue;
            }

            $type = $types[$user_bonus->type_id()];
            $item['sender_name'] = $this->show_name($type);//$type->sender_name();
            $item['rand_type']  = $type->isRandomAmount();
            $item['total_num']  = $type->getTotal_num();
            $item['binded_num'] = $type->binded_num();
            $item['share_end'] = $type->isEnd();
            $item['show_type'] = self::show_type($type->make_type());

            $type_sn = $type->getType_sn();
            $item['type_sn'] = $type_sn;

            $item['url']        = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=open&client_type=wap&type_sn={$type_sn}";
            $item['detail_url'] = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=detail&client_type=wap&type_sn={$type_sn}";

            $result[] = $item;
        }

        return $result;
    }

    private function show_type($make_type)
    {
        switch ($make_type)
        {
            case bonus\type::MakeSendType: //抢
            case bonus\type::MakeInviteType:
            case bonus\type::MakeVoteType:
                return 1;
            case bonus\type::MakeBonusRefundType: //退
            case bonus\type::MakePayRefundType:
            case bonus\type::MakeOrderCancelType:
                return 2;
            case bonus\type::MakeShakeGainType: //摇
            case bonus\type::MakeShakeLostType:
                return 3;
            case bonus\type::MakePayType:         //赠
            case bonus\type::MakeRegisterType:
            case bonus\type::MakeEvaluateType:
            case bonus\type::MakeInviteRewardType:
            case bonus\type::MakePayRewardInviterType:
            case bonus\type::MakePayRewardInviteeType:
            case bonus\type::MakeAllowanceType:
                return 4;
            default:
                return 0;   //什么都不显示
        }
    }

    private function show_name(bonus\type $type)
    {
        $make_type = $type->make_type();
        switch ($make_type) {
            case bonus\type::MakeSendType: //抢
            case bonus\type::MakeShakeGainType: //摇
                return $type->sender_name();
            case bonus\type::MakeVoteType:
                return "投票或答题红包";
            case bonus\type::MakeEvaluateType:
            case bonus\type::MakeInviteType:
            case bonus\type::MakeBonusRefundType: //退
            case bonus\type::MakePayRefundType:
            case bonus\type::MakeOrderCancelType:
            case bonus\type::MakeShakeLostType:

            case bonus\type::MakePayType:   //赠
            case bonus\type::MakeRegisterType:
            case bonus\type::MakeInviteRewardType:
            case bonus\type::MakePayRewardInviterType:
            case bonus\type::MakePayRewardInviteeType:
            case bonus\type::MakeAllowanceType:
                return $type->name();
            default:
                return "熊猫美妆";   //什么都不显示
        }
    }

    //预存款收支记录
    public function pdlogOp()
    {
        $mod_pd = Model('predeposit');
        $count = $mod_pd->getPdLogCount(array('lg_member_id' => $_SESSION['member_id']));
        $items = $mod_pd->getPdLogList(array('lg_member_id' => $_SESSION['member_id']),$this->page_size(),'*','lg_id desc');
        if(empty($items)) {
            return self::outsuccess(array('pd_logs' => array(),'mobile_page' => mobile_page(0)));
        }
        $pd_logs = $this->mPred->filter_pd_log($items);

        $pages = $this->pages($count);

        return self::outsuccess(array('pd_logs' => $pd_logs,'mobile_page' => mobile_page($pages)));
    }

    public function shakeOp()
    {
        if(!isset($_POST['strength']) || empty($_POST['strength'])) {
            $strength = intval($_POST['strength']);
        } else {
            $strength = 3;
        }

        $shaker = new shaker_helper();
        $items = $shaker->shake($strength,$err);
        if($items == false) {
            return self::outsuccess(array("bonuses" => [],"info" => array('count' => 0, 'money' => 0.0)));
        }
        else
        {
            $total_amount = 0;
            $bonuses = array();
            foreach ($items as $bonus)
            {
                $user_bonus = bonus\user_bonus::create_by_param($bonus);
                $type_info = bonus_helper::get_typeinfo($user_bonus->type_sn());
                $type_info = $type_info['type_info'];
                $type = bonus\type::create_by_paramer($type_info);

                $item = array();
                if($_SESSION['member_id'] == $user_bonus->user_id()) {
                    $item['direction'] = 'gain';
                    $item['name'] = $type->sender_name();
                    $item['bonus_value'] = $user_bonus->bonus_value();
                    $item['url'] = $this->bonus_detailurl($user_bonus->type_sn());
                    $total_amount += $user_bonus->bonus_value();
                    $minfo = new member_info($type->sender_id());
                } else {
                    $item['direction'] = 'lost';
                    $item['name'] = $user_bonus->user_name();
                    $item['bonus_value'] = $user_bonus->bonus_value();
                    $item['url'] = $this->bonus_detailurl($user_bonus->type_sn());

                    $total_amount -= $user_bonus->bonus_value();
                    $minfo = new member_info($user_bonus->user_id());
                }

                $item['is_man'] = $minfo->is_man();
                $item['avatar'] = $minfo->avatar();

                array_push($bonuses,$item);
            }

            $count = count($bonuses);
            return self::outsuccess(array("bonuses" => $bonuses,"info" => array('count' => $count, 'money' => $total_amount)));
        }
    }

    public function thiefOp()
    {
        $user_id = $_GET['enmember_id'];
        if(empty($user_id)) {
            return self::outerr(errcode::ErrParamter,"被偷的用户不存在");
        }
        $user_id = util::decrypt_data(urldecode($user_id));
        if($user_id <= 0) {
            return self::outerr(errcode::ErrParamter,"被偷的用户不存在");
        }
        else
        {
            $amount = session_helper::thief($user_id,$err);
            if($amount == false)
            {
                return self::outerr($err['code'],$err['msg']);
            }
            else
            {
                $bonuses = account_helper::gain_bonus($user_id, $_SESSION['member_id'], $amount);
                if($bonuses == false || empty($bonuses)) {
                    return self::outerr(errcode::ErrBonus,"这次没偷着");
                } else {
                    $bonus = $bonuses[0];
                    $tips = "您成功偷到{$bonus['bonus_value']}元";
                    return self::outsuccess(array("bonuses" => $bonuses,
                        "info" => ['count' => 1, 'money' => $bonus['bonus_value'],'tips' => $tips]));
                }
            }
        }
    }

    private function bonus_detailurl($type_sn)
    {
        $url = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=detail&type_sn={$type_sn}&client_type=wap";
        return $url;
    }

    public function daily_rankOp()
    {
        $count = ranklist_helper::list_count($_SESSION['member_id']);
        if($count == false) {
            return self::outerr(errcode::ErrBonusDailyRank,"您还没有抢红包记录，明天才能看到榜单～");
        }
        $start_index = ($this->page_no() - 1) * $this->page_size();
        $end = $start_index + $this->page_size();
        $end = $end > $count ? $count : $end;

        $times = array();
        $start_tm = time();
        for ($index = $start_index; $index < $end; ++$index) {
            $date_time = date_helper::sub_days($start_tm,$index + 1);
            array_push($times,$date_time);
        }

        $mids = array();
        array_push($mids,intval($_SESSION['member_id']));

        $top_infos = array();
        $tops = ranklist_helper::ranklists($_SESSION['member_id'],$times);
        foreach ($tops as $key => $top) {
            $item = array();
            $item['list_sn'] = $top->list_sn();
            $item['list_rank']  = $top->get_rank() + 1;
            $item['list_value'] = $top->money();
            $item['list_date']  = $top->list_date();
            $item['top_id'] = $top->top_id();
            $item['top_money'] = $top->top_money();
            if(in_array($top->top_id(),$mids) == false) {
                array_push($mids,$top->top_id());
            }
            array_push($top_infos,$item);
        }

        $mem_desc = array();
        $members = Model('member')->getMemberList(array('member_id' => array('in',$mids)));
        foreach ($members as $val) {
            $info = new member_info($val);
            array_push($mem_desc,$info->filter());
        }
        $pages = intval($count / $this->page_size()) + ( ($count % $this->page_size()) == 0 ? 0 : 1);
        return self::outsuccess(array('top_list' => $top_infos,'mem_desc' => $mem_desc,'mobile_page' => mobile_page($pages)));
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public function share_oneOp()
    {
        if(!isset($_GET['bonus_sn']) || empty($_GET['bonus_sn'])) {
            return self::outerr(errcode::ErrParamter,"需要红包序列号.");
        }
        $bonus_sn = $_GET['bonus_sn'];
        $ret = $this->mPred->share_bonus($bonus_sn,$msg);
        if($ret === false) {
            return self::outerr(errcode::ErrBonus,empty($msg) ? "生成红包失败." : $msg);
        } else {
            $type_sn = $ret['type_sn'];
            $url = url_helper::bonus_open_url($type_sn);
            return self::outsuccess(array('type_sn' => $ret,'url' => "{$url}"));
        }
    }

    public function send_listOp()
    {
        $type_infos = $this->send_list($pages);
        return self::outsuccess(array('type_infos' => $type_infos, 'mobile_page' => mobile_page($pages)));
    }

    private function send_list(&$pages)
    {
        $mod_type = Model('bonus_type');
        $cond['sender_id|relayer_id'] = array('_multi'=>true,$_SESSION['member_id'],$_SESSION['member_id']);
        $cond['make_type'] = array('in',array(bonus\type::MakeSendType,bonus\type::MakeInviteType));

        $count = $mod_type->getTypeCount($cond);
        if($count == 0) {
            $pages = 0;
            return null;
        }

        $items = $mod_type->getTypeList($cond,$this->page_size(),'*','type_id desc');
        $type_infos = [];
        foreach($items as $val) {
            $type_info = bonus_helper::filter_type($val);
            $type_infos[] = $type_info;
        }

        $pages = $this->pages($count);
        return $type_infos;
    }
}