<?php
/*
 * 用户等级接口
 * 时间2018-09-07
 * */
namespace App\Api\Controller;

use Biz\Account\AccountManager;

//ini_set('display_errors', 1);
//error_reporting(E_ALL);
class UserGrade extends BaseController {

    //获取用户下一级流水以及
    public function nextVip(){


        $account = new AccountManager();
        $userinfo = $account->getCurrentUser ();
        $userinfo = $userinfo ? $userinfo->toarray () : [];
        if(empty($userinfo))Render("",-5007);
        $userid =   $userinfo["account_identity"];
        if($userinfo["grade"] ==0 || $userinfo["grade"] ==-1){
            $nextgarade = -2;
        }else{
            $nextgarade =   $userinfo["grade"]+1;
        }


        if($nextgarade==-1)$nextgarade=1;
        $gradeinfo = lm ('UserGrade', 'Api')->orderby("grade","asc")->get(["grade","name","rule_details"]);
        $gradeinfo  =   $gradeinfo?$gradeinfo->toarray():[];
        $_flow_next =   0;
        $_recharge_next =   0;
        $newuserinfo["grade_name_next"]    =   "";
        if(count($gradeinfo)<1)Render("",-5007);

        $newuserinfo["name"]    =  $userinfo["account"];
        $newuserinfo["cash"]    =  $userinfo["cash"];
        $newuserinfo["open_invitation"]    =  $userinfo["open_invitation"];
        $newuserinfo["grade"]    =  $userinfo["grade"];

        foreach ($gradeinfo as $v) {
            if ($v["grade"] == $userinfo["grade"])
                $newuserinfo["grade_name"] = $v["name"];
            if ($v["grade"] == $nextgarade) {
                $newuserinfo["grade_name_next"] = $v["name"];
                $_recharge_next = isset($v["rule_details"]) ? explode(",", $v["rule_details"])[1] : 0;
                $_flow_next = isset($v["rule_details"]) ? explode(",", $v["rule_details"])[2] : 0;
            }
        }
        //查询等级规则
        $nextgradeinfo = lm('UserGrade', 'Api')->select('name', 'rule', 'rule_details')->where('grade', '=', 0)->first();

        if (empty($nextgradeinfo)) {
            //Render($nextgradeinfo, "-5002", '条件不满足');
            return '-5002';
        }

        //升级时间
        $update_grade_date  =   self::getUserGradeUpdate($userinfo["account_identity"]);
        //申请通过时间
        $viptime    =   self::getUserComeVipTime($userinfo["account_identity"])['audittime'];


        $save  =   lm("MoneyRecharge","Api")->getPromotionAmount(["account_identity"=>$userid]);
        //查询统计数据 进行数据累加计算
        $flow = lm('MoneyFlowCount', 'Api')->where("account_identity", $userid)->orderBy('id', 'desc')->first();
        $flow = $flow ? $flow->toarray() : [];
        $last_time = $flow ? $flow['updated_at'] : '';
        $endtime    =  date('Y-m-d H:i:s', time()-3*24*3600);
        $startime   =   $last_time? date('Y-m-d H:i:s',strtotime($last_time)-3*24*3600):'2018-01-01 00:00:00';

        //每3天更新一次数据
        if(time()-strtotime($last_time)>=3*24*3600){

            $zheren =   (new Nologin())->totalUserStatistics($userid,$startime,$endtime);
            $zheren_update =   $zheren>0?$this->updateMoneyFlowCount($userid,2,$zheren):0;

            $bet = lm("MoneyBuy","Api")->getstreamAmount(["account_identity"=>$userid],$startime,$endtime);
            $sixbet = lm("SixmoneyBuy","Api")->getsixstreamAmount(["account_identity"=>$userid],$startime,$endtime);
            $total_pc = $bet + $sixbet;
            $total_pc_update =   $total_pc>0?$this->updateMoneyFlowCount($userid,1,$total_pc):0;
        }

        $zheren =   (new Nologin())->totalUserStatistics($userid,$endtime);

        $bet = lm("MoneyBuy","Api")->getstreamAmount(["account_identity"=>$userid],$endtime);
        $sixbet = lm("SixmoneyBuy","Api")->getsixstreamAmount(["account_identity"=>$userid],$endtime);
        $total_pc = $bet + $sixbet +$zheren;


         $total= lm('MoneyFlowCount','Api')->where(['account_identity'=>$userid,'cycle'=>'alldays'])->sum('total')+$total_pc;

        $newuserinfo["flow"]   =  $total;
        $newuserinfo["charge"]   =   $save;

        //距下次升级 还需流水
        $flow_dif    =   $_flow_next-$total;
        $newuserinfo["flow_dif_next"]  =   $total >= $_flow_next&&$_flow_next>0?0:($flow_dif>0?$flow_dif:0);//小于0则等级达到最大值

        //距下一级充值 还需要 充值
        $recharge_dif   =   $_recharge_next-$save;
        $newuserinfo["recharge_dif_next"]   =  $save >= $_recharge_next&&$_recharge_next>0?0:($recharge_dif>0?$recharge_dif:0);//小于0则等级达到最大值


        //最高可得彩金
        $lotter  =   lm ('lottery_money', 'Api')->where ('type', "upgrade")->first ();
        $lotter  =   $lotter?$lotter->toarray():[];
        $lotter_money   =   $lotter?json_decode($lotter["conent"],1):[];
        $max_lotter_money   =   isset($lotter_money["grade"][$nextgarade])?$lotter_money["grade"][$nextgarade]:0;
        $newuserinfo["lotter_money_next"]   =   $max_lotter_money;
        $newuserinfo["lotter_money_id"]   =   isset($lotter["id"])?$lotter["id"]:0;

        //条件
        $date   =   ["all"=>"","year"=>"年","mouth"=>"月","week"=>"周",];
        foreach ($gradeinfo as $v){
            if($v["grade"]<1) continue;
            $row["grade"]    =  $v["name"];
            $row["lotter_money"]    =  isset($lotter_money["grade"][$v["grade"]])?$lotter_money["grade"][$v["grade"]]:0;
            $rule   =   explode(",",$v["rule_details"]);
            $rule[0]    =   isset($date[$rule[0]])?$date[$rule[0]]:"";
            $row["condition"]   =   $rule;

            $newuserinfo["show_list"][]=$row;
        }



        //彩金id
        $newuserinfo["grade_time"]   =   isset($update_grade_date["create_time"])?$update_grade_date["create_time"]:($viptime?$viptime:$userinfo['register_time']);
        $_data  =   ['account_identity'=>$userinfo["account_identity"],'grade'=>$userinfo["grade"],'lottery_money_type'=>'upgrade'];
        $status =  lm("Lottery_money_log","Api")->where($_data)->first();
        $status =   $status?$status->toarray():[];
        $newuserinfo["status"]     = isset($status['status'])?$status['status']:-1;


        //自动升级
        lm ('UserGrade', 'Api')->upgrade ($userinfo,$total);

        return $newuserinfo;
    }

    /**
     * 更新流水统计记录
     * @param $uuid
     * @param $lasttime
     * @param $type
     * @param $flow
     */
    private function updateMoneyFlowCount($uuid,$type,$flow){
        $update_flow    =   lm('MoneyFlowCount','Api');
        $info=   $update_flow->where(["account_identity"=>$uuid,'money_type'=>$type])->first();
        $info =   $info?$info->toarray():[];

        $update_data =   [
                "account_identity"=>$uuid,
                'updated_at'=>date('Y-m-d H:i:s'),
                'created_at'=>isset($info['created_at'])?$info['created_at']:date('Y-m-d H:i:s'),
                'total'=>isset($info['total'])?$flow+$info['total']:$flow,
                'cycle'=>'alldays',
                'money_type'=>$type

            ];

            $ret = $info?$update_flow->where(["account_identity"=>$uuid,'money_type'=>$type,'cycle'=>'alldays'])->update($update_data):$update_flow->insert($update_data);

            return $ret;
    }

    private function getLotteryInfo($typeOrid){
        $info   =   lm("LotterMoney","Api")->where('type',$typeOrid)->whereOr('id',$typeOrid)->first();
        return $info?$info->toarray():[];
    }

    public function upGradeStatus(array $data){
        $actvie =   new Active();
        return $actvie->getStatus($data);
    }

    /**
     * 获取vip申请通过时间
     */
    private function getUserComeVipTime($userid){
        $res    =   lm("user_vip","Api")
            ->where(["account_identity"=>$userid,"status"=>2])
            ->get(['audittime'])
            ->first();
        return $res?$res->toarray():['audittime'=>''];
    }

    /**
     * 获取用户最新晋级信息
     * @param $userid 用户唯一id
     */
     private function getUserGradeUpdate($userid){
        $res    =   lm("user_log_record","Api")
                    ->where(["account_identity"=>$userid,"type"=>"promotion"])
                    ->orderby("id","desc")
                    ->first();
        return $res?$res->toarray():[];
     }
    /**
     * 等级升级申请
     * @return [type] [description]
     */
    public function UserUpgrade(){
         $uinfo = $_SESSION['uinfo'];
        if (empty($uinfo)) {
            //Render(null, '-5009','条件不满足');
            Render("", "-5009", '');
        }

        //查询等级规则
        $gradelist = lm ('UserGrade', 'Api')->select ('name', 'rule', 'rule_details')->where ('grade','>',0)->get();
        $nextgradeinfo = lm ('UserGrade', 'Api')->select ('name', 'rule', 'rule_details')->where ('grade','=',0)->first ();
        if (empty($nextgradeinfo)) {
            //Render($nextgradeinfo, "-5002", '条件不满足');
            Render("", "-5002", '');
        }
        if (empty($gradelist)) {
            //Render($nextgradeinfo, "-5002", '条件不满足');
            Render("", "-5002", '');
        }
        $gradelist = $gradelist ->toArray ();
        $nextgradeinfo = $nextgradeinfo->toArray ();

        $nextgradeinfo['rule_details'] = explode (',', $nextgradeinfo['rule_details']);
        //查询统计数据
        $save = lm ('MoneyRecharge', 'Api')->where('account_identity', $uinfo['account_identity'])->where('status',1)->where('recharge_type','汇款')->where('recharge_type','后台充值')->where('recharge_type','在线充值');
        $bet = lm ('MoneyBuy', 'Api')->where('account_identity', $uinfo['account_identity'])->where('status','<', 4);
        $sixbet = lm ('SixmoneyBuy', 'Api')->where ('account_identity', $uinfo['account_identity'])->where('status','<', 4);

        //时间类型条件判断
        if ($nextgradeinfo['rule_details'][0] == 'year') {
            $startime = date ('Y-01-01', time ()) . ' 00:00:00';
            $endtime = date ('Y-12-31', time ()) . ' 23:59:59';
            $save = $save->where ('complete_time', '>=', $startime)->where ('complete_time', '<=', $endtime);
            $bet = $bet->where ('money_time', '>=', $startime)->where ('money_time', '<=', $endtime);
            $sixbet = $sixbet->where ('money_time', '>=', $startime)->where ('money_time', '<=', $endtime);
        } elseif ($nextgradeinfo['rule_details'][0] == 'month') {
            $startime = date ('Y-m-01', strtotime (date ('Y', time ()) . '-' . (date ('m', time ()) - 1) . '-01')) . ' 00:00:00';
            $endtime = date ('Y-m-d', strtotime ("$startime +1 month -1 day")) . ' 23:59:59';
            $save = $save->where ('complete_time', '>=', $startime)->where ('complete_time', '<=', $endtime);
            $bet = $bet->where ('money_time', '>=', $startime)->where ('money_time', '<=', $endtime);
            $sixbet = $sixbet->where ('money_time', '>=', $startime)->where ('money_time', '<=', $endtime);
        } elseif ($nextgradeinfo['rule_details'][0] == 'week') {
            $now_day = date ('w', time ()) - 1;
            $sunday_str = time () - $now_day * 60 * 60 * 24;
            $sunday = date ('Y-m-d 00:00:00', $sunday_str);
            $strday_str = time () + (6 - $now_day) * 60 * 60 * 24;
            $strday = date ('Y-m-d 23:59:59', $strday_str);
            $save = $save->where ('complete_time', '>=', $sunday)->where ('complete_time', '<=', $strday);
            $bet = $bet->where ('money_time', '>=', $sunday)->where ('money_time', '<=', $strday);
            $sixbet = $sixbet->where ('money_time', '>=', $sunday)->where ('money_time', '<=', $strday);
        } elseif ($nextgradeinfo['rule_details'][0] == 'day') {
            $firstday = date ('Y-m-d 00:00:00', strtotime ("-" . $nextgradeinfo['rule_details'][3] . " day"));
            $save = $save->where ('complete_time', '>=', $firstday)->where ('complete_time', '<=', date ('Y-m-d 23:59:59', strtotime ('-1 day')));
            $bet = $bet->where ('money_time', '>=', $firstday)->where ('money_time', '<=', date ('Y-m-d 23:59:59', strtotime ('-1 day')));
            $sixbet = $sixbet->where ('money_time', '>=', $firstday)->where ('money_time', '<=', date ('Y-m-d 23:59:59', strtotime ('-1 day')));
        }elseif($nextgradeinfo['rule_details'][0] == 'ymd'){
            $firstday = $nextgradeinfo['rule_details'][3].' 00:00:00';
            $save = $save->where ('complete_time', '>=', $firstday);
            $bet = $bet->where ('money_time', '>=', $firstday);
            $sixbet = $sixbet->where ('money_time', '>=', $firstday);
        }

        $save = $save->sum ('money');
        $bet = $bet->sum ('money');
        $sixbet = $sixbet->sum ('money');
        $total = $bet+$sixbet;
        $newgrade = 0;
        foreach($gradelist as $key =>$value){
            $rule_details = explode(',',$value['rule_details']);
            if($save >= $rule_details[1] && $total >= $rule_details[2]){
                $newgrade = $key;
            }
        }

        if ($newgrade > 0 && $newgrade > $uinfo['grade']) {
            $res = lm ('AccountDetail', 'Api')->where ('account_identity', $uinfo['account_identity'])->update (['grade' => $newgrade]);
            if ($res) {
                $remark['original_grade'] = $uinfo['grade'];
                $remark['present_grade'] = $newgrade;
                $remark['type'] = $nextgradeinfo['rule_details'][0];
                $remark['save'] = $save;
                $remark['bet'] = $bet + $sixbet;
                $data['account_identity'] = $uinfo['account_identity'];
                $data['remark'] = json_encode ($remark);
                $data['account_name'] = $uinfo['account'];
                $data['type'] = 'promotion';
                $data['create_time'] = date ('Y-m-d H:i:s');
                lm ('User_log_record', 'Api')->insert ($data);
                Render($res, "1", '');
            } else {

                Render($res, "-5007", '');
            }
        } else {
            Render("", "-5003", '');
        }

    }



}
