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

defined('InShopNC') or exit('Access Invalid!');

class user_bonusModel extends Model
{
    const send_bonus = 1;
    const grab_bonus = 2;
    const TopupState = 3;


    public function __construct()
    {
        parent::__construct('user_bonus');
    }

    public function get_by_sql($sql) {
        return $this->query($sql);
    }

    public function get($condition,$fields='*',$lock=false)
    {
        return $this->field($fields)->where($condition)->limit(false)->lock($lock)->select();
    }

    public function getBonusCount($condition = array()) {
        return $this->table('user_bonus')->where($condition)->count();
    }

    public function getBonusList($condition,$field='*', $order = '',$page = 0,$count = 0, $limit = 0, $group = '', $lock = false)
    {
        return $this->table('user_bonus')->field($field)->where($condition)->group($group)->order($order)->limit($limit)->page($page, $count)->lock($lock)->select();
    }

    public function getUsableBonus($member_id)
    {
        $cond = array('user_id' => $member_id,'bonus_status' => 3,'usable_time' => array('gt',time()),'remain_amount' => array('gt','0.00'));
        return $this->getBonusList($cond,'*','usable_time asc');
    }

    public function getUsableSum($member_id)
    {
        $cond = array('user_id' => $member_id,'bonus_status' => 3,'usable_time' => array('gt',time()),'expired' => 0);
        return $this->table('user_bonus')->where($cond)->sum('remain_amount');
    }

    public function getBindSum($member_id)
    {
        return $this->table('user_bonus')->where(['user_id' => $member_id,'bonus_status' => 2])->sum('remain_amount');
    }

    public function getSum($cond,$field = 'remain_amount')
    {
        return $this->table('user_bonus')->where($cond)->sum($field);
    }

    public function lasted_binded_time($condition) {
        $items = $this->where($condition)->field('get_time')->order('get_time desc')->limit(1)->select();
        if(count($items) == 1) {
            return $items[0]['get_time'];
        } else {
            return false;
        }
    }

    public function lasted_grabed_time($condition) {
        $items = $this->where($condition)->field('grab_time')->order('grab_time desc')->limit(1)->select();
        if(count($items) == 1) {
            return $items[0]['grab_time'];
        } else {
            return false;
        }
    }

    public function add($datas) {
        return $this->insert($datas);
    }

    public function getTypeBinded($condition,$fields = '*')
    {
        $condition['bonus_status'] = array('in',array(2,3));
        return $this->where($condition)->field($fields)->order('get_time DESC')->limit(false)->select(array('master' => true));
    }

    public function getBinded($mobile,$fields = '*') {
        return  $this->where(array('user_mobile' => $mobile, 'bonus_status' => 2))->field($fields)->order('type_id')->select();
    }

    public function getStatus($bonus_sn) {
        $ret = $this->where(array('bonus_sn' => $bonus_sn))->field('bonus_status')->find();
        if(empty($ret)) {
            return 0;
        } else {
            return intval($ret['bonus_status']);
        }
    }

    private function getOwned($mobile,$type_id,$fields = '*') {
        return  $this->where(array('user_mobile' => $mobile, 'type_id' => $type_id,'bonus_status' => array('in',array(2,3))))->field($fields)->find();
    }

    public function edit($condition,$datas)
    {
        return $this->where($condition)->update($datas);
    }

    public function comment($bonus_id,$comment) {
        return $this->where(array('bonus_id' => $bonus_id))->update(array('user_comment' => $comment));
    }

    //返回单个红包
    public function grab($type_id,$time_out,$mobile,$sess_id,&$is_new_grab,&$is_new_bind)
    {
        $is_new_grab = false;
        $is_new_bind = false;

        $fields = '*';
        //如果已经绑定手机
        if(!empty($mobile))
        {
            $mine = $this->getOwned($mobile,$type_id,$fields);
            if(!empty($mine)) {
                return $mine;
            }
        }

        $items = $this->where(array('type_id' => $type_id,'session_id' => $sess_id))->field($fields)->order('bonus_status,bonus_id')->limit(1)->select(array('master' => true));
        if(empty($items))
        {
            while(true)
            {
                $is_new_grab = false;
                $is_new_bind = false;

                $cond = array( 'type_id' => $type_id,
                    'bonus_status' => array('in', array(0,1)),
                    'grab_time' => array('lt',time() - $time_out));
                $bonuses = $this->where($cond)->field($fields)->order('bonus_status asc,bonus_id asc')->limit(1)->select(array('master' => true));
                if(empty($bonuses) || empty($bonuses[0])) return false;

                $bonus = $this->try_grab($bonuses[0],$type_id,$is_new_grab,$sess_id,$is_new_bind);
                if($bonus != false) {
                    return $bonus;
                }
            }
        }
        else {
            $mine = $items[0];
            return $mine;
        }
    }

    private function try_grab($bonus, $type_id, &$is_new_grab, $sess_id, &$is_new_bind)
    {
        if($bonus['bonus_status'] == 0) {
            $is_new_grab = true;
        }

        $cond = [];
        $cond['type_id']  = $type_id;
        $cond['bonus_id']  = $bonus['bonus_id'];
        $cond['bonus_status'] = $bonus['bonus_status'];
        $cond['grab_time'] = $bonus['grab_time'];
        $cond['get_time']  = $bonus['get_time'];
        $cond['session_id']  = $bonus['session_id'];

        if(session_helper::isLogin()) { // 如果是登录状态直接绑定
            $datas = array('bonus_status' => 2,
                'grab_time' => time(),
                'get_time'  => time(),
                'session_id' => $sess_id,
                'user_id' => $_SESSION['member_id'],
                'user_mobile' => session_helper::cur_mobile(),
                'user_name' => session_helper::nickname());
            $is_new_bind = true;
        }
        else if(session_helper::isVerfiyMobile()) { //如果该会话手机号码曾经认证过，直接绑定
            $datas = array('bonus_status' => 2,
                'grab_time' => time(),
                'get_time'  => time(),
                'session_id' => $sess_id,
                'user_mobile' => session_helper::cur_mobile());
            $is_new_bind = true;
        }
        else {
            $datas = array('bonus_status' => 1,
                'grab_time' => time(),
                'session_id' => $sess_id);
        }

        $ret = $this->where($cond)->update($datas);
        $affect_rows = $this->affected_rows();

        Log::record("user_bonusModel::grab ret={$ret} affected_rows={$affect_rows}",Log::DEBUG);
        if($ret != false && $affect_rows > 0) {
            $bonus = array_merge($bonus,$datas);
            return $bonus;
        } else {
            return false;
        }
    }

    public function bind($type_id,$bonus_id,$sess_id,$mobile,&$bonus)
    {
        $fields = '*';
        $items = $this->getOwned($mobile, $type_id, $fields);
        if (!empty($items)) {
            $bonus = $items;
            return false;
        }

        $condition = array('type_id' => $type_id, 'bonus_id' => $bonus_id, 'session_id' => $sess_id, 'bonus_status' => 1);
        $datas = array('bonus_status' => 2,
            'user_mobile' => $mobile,
            'get_time' => time());

        if (session_helper::isLogin()) {
            $datas['user_name'] = session_helper::nickname();
            $datas['user_id'] = $_SESSION['member_id'];
        }

        $ret = $this->where($condition)->update($datas);
        $affect_rows = $this->affected_rows();
        return ($ret != false && $affect_rows > 0);
    }

    public function replace($data)
    {
        $this->insert($data,true);
    }

    public function replaceAll($datas)
    {
        $this->insertAll($datas,array(),true);
    }

    public function getNeedWarn($left_days, $interval_days)
    {
        if(!isset($left_days) || !isset($interval_days)) {
            return false;
        }

        $day_secs = 24 * 3600;
        $left_warn_secs = intval($left_days) * $day_secs;
        $period_secs = intval($interval_days) * $day_secs;

        $cur_time = time();

        $cond = array();
        $cond['bonus_status'] = 3;
        $cond['usable_time'] = array(array('gt',$cur_time), array('elt',$cur_time + $left_warn_secs),'and');
        $cond['notify_time'] = array(array('eq',0), array('elt',$cur_time - $period_secs),'or');
        $cond['expired'] = 0;
        $cond['remain_amount'] = array('gt','0.00');
        $ret = $this->getBonusList($cond,'*','usable_time asc',0,0,1000);
        if(empty($ret)) {
            return false;
        } else {
            return $ret;
        }
    }

    public function getExpired($maxtm)
    {
        $cond = array('expired' => 0, 'remain_amount' => array('gt','0.00'),'bonus_status' => 3,'usable_time' => array('elt',$maxtm));
        $ret = $this->getBonusList($cond,'*','usable_time asc',0,0,1000);
        return $ret;
    }
}