<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/5/25
 * Time: 上午9:24
 */

namespace statistics;

use Log;
class stbonus extends stat_base
{
    public function __construct($stime)
    {
        parent::__construct($stime);
    }

    public function add_paied($rate,$amount)
    {
        $result = $this->mModel->get_one($this->mDateId, 'bonus_pay_amount,person_send_amount',true);
        $fEdit = empty($result) ? false : true;

        if (empty($result) || empty($result['bonus_pay_amount'])) {
            $pay_amount = [];
            $pay_amount[$rate] = $amount;
        } else {
            $pay_amount = unserialize($result['bonus_pay_amount']);
            if (array_key_exists($rate, $pay_amount)) {
                $pay_amount[$rate] += $amount;
            } else {
                $pay_amount[$rate] = $amount;
            }
        }

        $datas['bonus_pay_amount'] = serialize($pay_amount);
        return $this->save($fEdit, $datas);
    }

    public function add_send($rate,$amount)
    {
        $result = $this->mModel->get_one($this->mDateId,'bonus_pay_amount,person_send_amount',true);
        $fEdit = empty($result) ? false : true;

        if(empty($result) || empty($result['person_send_amount']))
        {
            $send_amount = [];
            $send_amount[$rate] = $amount;
        }
        else
        {
            $send_amount = unserialize($result['person_send_amount']);
            if(array_key_exists($rate,$send_amount)) {
                $send_amount[$rate] += $amount;
            } else {
                $send_amount[$rate] = $amount;
            }
        }

        $datas['person_send_amount'] = serialize($send_amount);
        return $this->save($fEdit,$datas);
    }

    public function daily()
    {
        $mtype = Model('bonus_type');
        $muser_bonus = Model('user_bonus');

        $ret_aval = $this->available_bonus($muser_bonus);
        if($ret_aval == false) {
            Log::record(__METHOD__ . " available_bonus",Log::ERR);
        }

        $ret_all = $this->all_send_bonus($mtype);
        if($ret_all == false) {
            Log::record(__METHOD__ . " all_send_bonus",Log::ERR);
        }

        $ret_admin = $this->admin_send_bonus($mtype);
        if($ret_admin == false) {
            Log::record(__METHOD__ . " admin_send_bonus",Log::ERR);
        }

    }

    /*
	all_total_amount varchar(1024) default '' null comment '今日发送的所有红包金额',
	all_remain_amount varchar(1024) default '' null comment '当日剩余红包总额',
	all_type_count int default '0' null comment 'type表中，红包条数',
  	all_bonus_count int default '0' null,
	all_grab_count int default '0' null,
	all_bind_count int default '0' null,
    */
    private function all_send_bonus($mbonus_type)
    {
        $this->calc_time(self::cur_date_type);

        $cond['send_start_date'] = ['between',"{$this->mStartm},{$this->mEndtm}"];
        $field = 'bonus_rate,
        sum(total_amount) as all_total_amount,
        sum(remain_amount) as all_remain_amount,
        sum(total_num) as all_bonus_count,
        sum(grabed_num) as all_grab_count,
        sum(binded_num) as all_bind_count,
        count(*) as all_type_count';

        $items = $mbonus_type->field($field)->where($cond)->group('bonus_rate')->select();
        if (empty($items)) {
            return false;
        }
        else
        {
            $total_amounts = [];
            $remain_amounts = [];

            $type_conut = 0;
            $bonus_conut = 0;
            $grab_conut = 0;
            $bind_conut = 0;

            foreach ($items as $item)
            {
                $total_amount = [];
                $remain_amount = [];

                $rate = $item['bonus_rate'];
                $total_amount[$rate]  = $item['all_total_amount'];
                $remain_amount[$rate] = $item['all_remain_amount'];
                $total_amounts[] = $total_amount;
                $remain_amounts[] = $remain_amount;

                $type_conut += $item['all_type_count'];
                $bonus_conut += $item['all_bonus_count'];
                $grab_conut += $item['all_grab_count'];
                $bind_conut += $item['all_bind_count'];
            }

            $result = $this->mModel->get_one($this->mDateId,'bonus_pay_amount,person_send_amount',true);
            $fEdit = empty($result) ? false : true;

            $datas['all_total_amount']  = serialize($total_amounts);
            $datas['all_remain_amount'] = serialize($remain_amounts);

            $datas['all_type_count']  = $type_conut;
            $datas['all_bonus_count'] = $bonus_conut;
            $datas['all_grab_count']  = $grab_conut;
            $datas['all_bind_count']  = $bind_conut;

            return $this->save($fEdit,$datas);
        }
    }

    /*
    available_total_amount varchar(1024) default '' null comment '可用红包金额',
	available_count int default '0' null comment '可用红包个数',
    */
    private function available_bonus($muser_bonus)
    {
        $this->calc_time(self::cur_date_type);
        $field = 'bonus_rate,sum(remain_amount) as total_amount,count(*) as bonus_count';
        $cond = ['bonus_status' => 3, 'usable_time' => ['gt', $this->mStartm]];
        $items = $muser_bonus->field($field)->where($cond)->group('bonus_rate')->select();
        if (empty($items)) {
            return false;
        }
        else
        {
            $result = [];
            $bonus_conut = 0;
            foreach ($items as $item)
            {
                $val = [];
                $rate = $item['bonus_rate'];
                $val[$rate] = $item['total_amount'];
                $bonus_conut += $item['count'];
                $result[] = $val;
            }

            $datas['available_total_amount']  = serialize($result);
            $datas['available_count'] = $bonus_conut;

            $result = $this->mModel->get_one($this->mDateId,'bonus_pay_amount,person_send_amount',true);
            $fEdit = empty($result) ? false : true;

            return $this->save($fEdit,$datas);
        }
    }

    /*
    admin_total_amount varchar(1024) default '' null comment '系统发放金额',
	admin_remain_amount varchar(1024) default '' null comment '余额',
	admin_type_count int null comment '管理员发送的红包个数',
	admin_bonus_count int default '0' null,
	admin_grab_count int default '0' null,
	admin_bind_count int default '0' null,
    */
    private function admin_send_bonus($mbonus_type)
    {
        $this->calc_time(self::cur_date_type);

        $cond['send_start_date'] = ['between',"{$this->mStartm},{$this->mEndtm}"];
        $cond['sender_id'] = self::admin_member_id;
        $field = 'bonus_rate,
        sum(total_amount) as admin_total_amount,
        sum(remain_amount) as admin_remain_amount,
        sum(total_num) as admin_bonus_count,
        sum(grabed_num) as admin_grab_count,
        sum(binded_num) as admin_bind_count,
        count(*) as admin_type_count';

        $items = $mbonus_type->field($field)->where($cond)->group('bonus_rate')->select();
        if (empty($items)) {
            return false;
        }
        else
        {
            $total_amounts = [];
            $remain_amounts = [];

            $type_conut = 0;
            $bonus_conut = 0;
            $grab_conut = 0;
            $bind_conut = 0;

            foreach ($items as $item)
            {
                $total_amount = [];
                $remain_amount = [];

                $rate = $item['bonus_rate'];
                $total_amount[$rate] = $item['admin_total_amount'];
                $remain_amount[$rate] = $item['admin_remain_amount'];
                $total_amounts[] = $total_amount;
                $remain_amounts[] = $remain_amount;

                $type_conut += $item['admin_type_count'];
                $bonus_conut += $item['admin_bonus_count'];
                $grab_conut += $item['admin_grab_count'];
                $bind_conut += $item['admin_bind_count'];
            }

            $result = $this->mModel->get_one($this->mDateId,'bonus_pay_amount,person_send_amount',true);
            $fEdit = empty($result) ? false : true;

            $datas['admin_total_amount']  = serialize($total_amounts);
            $datas['admin_remain_amount'] = serialize($remain_amounts);

            $datas['admin_type_count']  = $type_conut;
            $datas['admin_bonus_count'] = $bonus_conut;
            $datas['admin_grab_count']  = $grab_conut;
            $datas['admin_bind_count']  = $bind_conut;

            return $this->save($fEdit,$datas);
        }
    }

    public function discount_self()
    {
        $this->calc_time(self::cur_date_type);

        $mod_member = Model('member');
        $mod_order = Model('order');
        $orders = $mod_order->table('order')->where(array('order_state' => ['in',[20,30,40]],
            'payment_time' => ['between',"{$this->mStartm},{$this->mEndtm}"]))->field('bonus_rate,buyer_id')->limit(false)->select();

        foreach ($orders as $order)
        {
            $member_id = $order['buyer_id'];
            $discount = 0.00;
            $rates = $order['bonus_rate'];
            if(!empty($rates))
            {
                $rate_amount = unserialize($rates);
                foreach ($rate_amount as $key => $val) {
                    $discount += $val;
                }
            }
            $mod_member->editMember(['member_id' => $member_id],['discount_self_amount' => ['exp', "discount_self_amount + {$discount}"]]);
        }
    }

    public function discount_invitee()
    {
        $this->calc_time(self::cur_date_type);

        $mod_member = Model('member');
        $mod_order = Model('order');
        $orders = $mod_order->table('order')->where(array('order_state' => ['in',[20,30,40]],
            'payment_time' => ['between',"{$this->mStartm},{$this->mEndtm}"]))->field('bonus_rate,buyer_id')->limit(false)->select();

        foreach ($orders as $order)
        {
            $member_id = $order['buyer_id'];
            $inviter_id = $this->inviter($mod_member,$member_id);
            if($inviter_id == false) continue;

            $discount = 0.00;
            $rates = $order['bonus_rate'];
            if(!empty($rates))
            {
                $rate_amount = unserialize($rates);
                foreach ($rate_amount as $key => $val) {
                    $discount += $val;
                }
            }
            $mod_member->editMember(['member_id' => $inviter_id],['discount_invitee_amount' => ['exp', "discount_invitee_amount + {$discount}"]]);
        }
    }

    private function inviter($mod_member,$member_id)
    {
        $members = $mod_member->field('inviter_id')->where(['member_id' => $member_id])->limit(false)->select();
        if(empty($members)) {
            return false;
        }

        return intval($members[0]['member_id']);
    }

    public function init_discount_self()
    {
        $mod_member = Model('member');
        $members = $mod_member->field('*')->limit(false)->select();
        foreach ($members as $member)
        {
            $member_id = intval($member['member_id']);
            $mod_order = Model('order');
            $orders = $mod_order->table('order')->where(['order_state' => ORDER_STATE_SUCCESS,'buyer_id' => $member_id])->field('bonus_rate')->limit(false)->select();

            if(empty($orders)) continue;

            $discount = 0.00;
            foreach ($orders as $order)
            {
                $rates = $order['bonus_rate'];
                if(!empty($rates))
                {
                    $rate_amount = unserialize($rates);
                    foreach ($rate_amount as $key => $val) {
                        $discount += $val;
                    }
                }
            }
            $mod_member->editMember(['member_id' => $member_id],['discount_self_amount' => $discount]);
        }
    }

    private function invitees($mod_member,$member_id)
    {
        $members = $mod_member->field('member_id')->where(['inviter_id' => $member_id])->limit(false)->select();
        if(empty($members)) {
            return false;
        }

        $result = [];
        foreach ($members as $member) {
            $result[] = intval($member['member_id']);
        }

        return $result;
    }

    public function init_discount_invitee()
    {
        $mod_member = Model('member');
        $members = $mod_member->field('*')->limit(false)->select();
        foreach ($members as $member)
        {
            $member_id = intval($member['member_id']);
            $invitees = $this->invitees($mod_member,$member_id);
            if($invitees == false) continue;

            $mod_order = Model('order');
            $orders = $mod_order->table('order')->where(['order_state' => ORDER_STATE_SUCCESS,'buyer_id' => ['in',$invitees]])->field('bonus_rate')->limit(false)->select();

            if(empty($orders)) continue;

            $discount = 0.00;
            foreach ($orders as $order)
            {
                $rates = $order['bonus_rate'];
                if(!empty($rates))
                {
                    $rate_amount = unserialize($rates);
                    foreach ($rate_amount as $key => $val) {
                        $discount += $val;
                    }
                }
            }
            $mod_member->editMember(['member_id' => $member_id],['discount_invitee_amount' => $discount]);
        }
    }
}