<?php
/**
 *------Create thems Model------
 *------SCWPHP  Version 1.0.0------
 *------Dev Model Jions------
 *------Create Time 2017-06-12 05:08:18------
 */
namespace App\Api\Model;
use App\Api\Controller\Nologin;
use \System\Model;

class UserGrade extends Model {

    protected $table = 'dc_user_grade';

    //晋级等级
    function upgrade($todata, $totol_Money=0){

    	if (empty($todata)) {
            return '-50003';
        }
    	$result['data'] = $todata;
    	if ($result['data']['grade'] == 0 || $result['data']['grade'] == -1) {
            return '-50019';
        }
    	//查询等级规则
        $gradelist = lm ('UserGrade', 'Api')->select ('name', 'rule','grade', 'rule_details')->orderBy ('grade', 'asc')->get ();

        if (!count($gradelist)) {
            return '-5002';
        }
        $nextgradeinfo  =   $gradelist[0];

        $gradelist = $gradelist->toArray ();
        $nextgradeinfo = $nextgradeinfo->toArray ();
        $nextgradeinfo['rule_details'] = explode (',', $nextgradeinfo['rule_details']);
        $rule_details = $nextgradeinfo['rule_details'];
        //查询统计数据
        $params['account_identity'] = $result['data']['account_identity'];
        $total  =   0;
        $save = lm ('MoneyRecharge', 'Api')->getPromotionAmount($params);
        if(!$totol_Money){

            $sixbet = lm ('SixmoneyBuy', 'Api')->getsixstreamAmount($params);
            $bet = lm ('MoneyBuy', 'Api')->getstreamAmount($params);
            $zheren =   (new Nologin())->totalUserStatistics($params['account_identity'],'2018-01-01 00:00:00');
            $total = $bet + $sixbet+$zheren;
        }else{
                $total= $totol_Money  ;
        }

        $newgrade = 0;
        $gradename = array();
        foreach ($gradelist as $key => $value) {
            $rule_details = explode (',', $value['rule_details']);

            if ($save >= $rule_details[1] && $total >= $rule_details[2]) {
                $newgrade = $value['grade'];


            }
            $gradename[$value['grade']] = $value['name'];
        }

        if ($newgrade > 0 && $newgrade > $result['data']['grade']) {

            $res = lm ('AccountDetail', 'Api')->where ('account_identity', $result['data']['account_identity'])->update (['grade' => $newgrade]);

            if ($res) {
                $remark['original_grade'] = $gradename[$result['data']['grade']];
                $remark['present_grade'] = $gradename[$newgrade];
                $remark['newgrade'] = $newgrade;
                $remark['oldgrade'] = $result['data']['grade'];
                $remark['type'] = $nextgradeinfo['rule_details'][0];
                $remark['save'] = $save;
                $remark['bet'] = $bet + $sixbet;
                $data['account_identity'] = $result['data']['account_identity'];
                $data['remark'] = json_encode ($remark);
                $data['account_name'] = $result['data']['account'];
                $data['type'] = 'promotion';
                $data['create_time'] = date ('Y-m-d H:i:s');
                lm ('User_log_record', 'Api')->insert ($data);
                $Promotiong = lm ('lottery_money', 'Api')->where ('type','upgrade')->first ();
                if(!empty($Promotiong)){
                    $Promotiong = $Promotiong->toArray();
                    $conent = json_decode ($Promotiong['conent']);
                    if ($conent->setup == 2) {
                        $this->gold ($todata,$Promotiong['id']);
                    }
                }
                return 1;
            } else {
                return '-5007';
            }
        } else {
            return '-5003';
        }
    }

    //晋级彩金
    function gold($todata,$id){

    	if (empty($todata)) {
            return '-50003';
        }
    	$result['data'] = $todata;
    	if ($result['data']['grade'] == 0 || $result['data']['grade'] == -1) {
            return '-50019';
        }

    	$userinfo = $todata;
        $wherel['type'] = 'upgrade';
        $wherel['id'] = $id;
        $Promotiong = lm ('lottery_money', 'Api')->where ($wherel)->first ();
        if (empty($Promotiong)) {
            return -50010;
        }
        $Promotiong = $Promotiong->toArray ();
        $conent = json_decode ($Promotiong['conent']);
        $gradeinfo = lm ('UserGrade', 'Api')->select ('name', 'rule', 'rule_details')->where ('grade', $userinfo['grade'])->first ();
        if (empty($gradeinfo)) {
            return -50013;
        }
        $gradelist = lm ('UserGrade', 'Api')->select ('name','grade')->orderBy ('grade', 'asc')->get ();
        if (!count($gradelist)) {
            return '-5002';
        }
        $gradelist = $gradelist->toArray ();
        $gradename = array();
        foreach ($gradelist as $key => $value) {
            $gradename[$value['grade']] = $value['name'];
        }
        $gradeinfo = $gradeinfo->toArray ();
        $gradeinfo['rule_details'] = explode (',', $gradeinfo['rule_details']);
        $amount = 0;
        $grade = $conent->grade;

        if (empty($grade)) {
            return -50014;
        }

        foreach ($grade as $key => $value) {
            $gra[$key] = $value;
        }
        if ($conent->give_type == 'pre') {
            $amount = $gradeinfo['rule_details'][2] * $gra[$userinfo['grade']];
        } else {
            if (!isset($gra[$userinfo['grade']])) Render ('', "-50014");
            $amount = $gra[$userinfo['grade']];
        }

        $where['type'] = 'promotion';
        $where['account_identity'] = $result['data']['account_identity'];
        $tograde = lm ('User_log_record', 'Api')->where ($where)->get ();
        $status = 0;
        if (!count($tograde)) {
            return -50013;
        }

        $tograde = $tograde->toArray ();

        $newremark = array();
        foreach ($tograde as $key => $value) {
            $remark = json_decode ($value['remark'], true);
            if ($remark['newgrade'] == $userinfo['grade']) {
                $status = 1;
                if (!empty($remark['oldgrade'])) {
                    $original_grade = $remark['oldgrade'];
                } else {
                    $original_grade = 0;
                }

                if ($conent->setup == 2) {
                    $remark['operator'] = 'system';
                    $remark['update_time'] = date ('Y-m-d H:i:s');
                }

                $newremark = $remark;

            }else{
                $original_grade = 0;
            }
        }
        $originalgradeinfo = lm ('UserGrade', 'Api')->select ('name')->where ('grade', $original_grade)->first ();
        if(!empty($originalgradeinfo)){
            $originalgradeinfo = $originalgradeinfo->toArray();
        }else{
            $originalgradeinfo['name'] = $original_grade;
        }

        if ($status == 1) {
            $wheretwo['account_identity'] = $result['data']['account_identity'];
            $wheretwo['grade'] = $userinfo['grade'];
            $wheretwo['lottery_money_type'] = $Promotiong['type'];
            $num = lm ('lottery_money_log', 'Api')->where ($wheretwo)->count ();
            if ($num == 0) {
                if ($amount > 0) {
                    $data['account_identity'] = $result['data']['account_identity'];
                    $data['grade'] = $userinfo['grade'];
                    $data['lottery_money_type'] = $Promotiong['type'];
                    $data['lottery_money_id'] = $Promotiong['id'];
                    $data['lottery_money_name'] = $Promotiong['name'];
                    $data['money'] = $amount;
                    $data['create_time'] = date ('Y-m-d H:i:s');
                    if ($conent->setup == 2) {
                        $data['status'] = 1;
                        $data['operator'] = 'system';
                        //$setupname = '自动计算';
                    } else {
                        $data['status'] = 0;
                        //$setupname = '手动计算';
                    }
                    $data['account_name'] = $result['data']['account'];

                    $data['operator_id'] = 0;
                    $data['detail'] = sprintf (lang('Userup', 'Api')->get ('promotion'), $result['data']['account'], $gradename[$original_grade], $gradename[$userinfo['grade']], $amount);
                    $data['flow_record'] = json_encode ($newremark);
                    if ($conent->setup == 2) {
                        $recharge['info_identity'] = UUID ();
                        $recharge['order_id'] = OrderID ();
                        $recharge['apply_time'] = date ('Y-m-d H:i:s');
                        $recharge['complete_time'] = date ('Y-m-d H:i:s');
                        $recharge['money'] = $amount;
                        $recharge['account_identity'] = $result['data']['account_identity'];
                        $recharge['account_name'] = $result['data']['account'];
                        $recharge['status'] = 1;
                        $recharge['recharge_type'] = '活动充值';
                        $recharge['sysetem_user'] = 'system';
                        $recharge['reason'] = '用于活动';
                        $recharge['money_cash'] = $amount + $result['data']['cash'];
                        $recharge['remark'] = sprintf (lang('Userup', 'Api')->get ('promotion'), $result['data']['account'], $gradename[$original_grade], $gradename[$userinfo['grade']], $amount);

                        $rechargeremark['order_id'] = $recharge['order_id'];
                        $rechargeremark['name'] = $result['data']['account'];
                        $rechargeremark['recharge_time'] = date ('Y-m-d H:i:s');
                        $rechargeremark['money'] = $recharge['money'];
                        $rechargeremark['remark'] = sprintf (lang('Userup', 'Api')->get ('promotion'), $result['data']['account'], $gradename[$original_grade], $gradename[$userinfo['grade']], $amount);

                        $details['info_identity'] = UUID ();
                        $details['trade_id'] = OrderID ();
                        $details['account_name'] = $result['data']['account'];
                        $details['account_identity'] = $result['data']['account_identity'];
                        $details['money'] = $amount;
                        $details['money_time'] = date ('Y-m-d H:i:s');
                        $details['money_type'] = 1;
                        $details['money_cash'] = $amount + $result['data']['cash'];
                        $details['trade_type'] = 12;
                        $details['trade_desc'] = sprintf (lang('Userup', 'Api')->get ('promotion'), $result['data']['account'], $gradename[$original_grade], $gradename[$userinfo['grade']], $amount);
                        $details['sysetem_user'] = '系统';
                        $details['status'] = 1;
                        $mess['title'] = '申领彩金提醒';
                        $mess['content'] = '恭喜'.$result['data']['account'].'您从'.$originalgradeinfo['name'].'升级到'.$gradeinfo['name'].'，通过VIP晋级彩金活动申请的彩金'.$amount.'已到账，请查收！';
                        $mess['type'] = '1';
                        $mess['formname'] = '系统通知';
                        $mess['toname'] = $result['data']['account'];
                        $mess['add_time'] = date('Y-m-d H:i:s');
                        $mess['add_status'] = '2';
                        $MoneyQuery = new \Biz\Money\MoneyQuery;
                        $MoneyHandle = new \Biz\Money\MoneyHandle;
                        $MoneyQuery->recordWithdraw (1, $result['data']['account_identity'], 0, $amount, $conent->multiple);
                        lm ('MoneyRecharge', 'Api')->insert ($recharge);
                        lm ('MoneyDetails', 'Api')->insert ($details);
                        lm ('MoneyRechargeRemark', 'Api')->insert ($rechargeremark);
                        lm("message",'commons')->insert($mess);
                        try {
                            $re = $MoneyHandle->updateAccountMoney ($result['data']['account_identity'], $amount, 1);
                            if ($re < 0) {
                                _rollBack ();
                            }
                        } catch (PDOException $e) {
                            _rollBack ();
                        }
                    }
                    $res = lm ('lottery_money_log', 'Api')->insert ($data);
                    if ($res) {
                        return 1;
                    } else {
                        return -50016;
                    }
                } else {
                    return -50017;
                }

            } else {
                return -50018;
            }

        } else {
            return -50019;
        }
    }

}
