<?php
namespace app\apicom\model;

use app\apicom\model\Money;
use app\apicom\model\Member as MemberModel;
use app\apicom\model\SubAccount as SubAccountModel;
use app\apicom\model\Record as RecordModel;
use app\apicom\model\RecordAgent as RecordAgentModel;
use app\apicom\model\MemberMessage as MemberMessageModel;
use app\apicom\model\StockSubAccountRisk;
use app\apicom\model\SubAccountMoney;
use app\apicom\model\StockPosition;
use app\apicom\model\Trust;
use app\apicom\model\StockDealStock;
use app\apicom\model\StockDeliveryOrder as Delivery;
use think\facade\Db;
use think\Model;
use think\Exception;

use util\RedisUtil;
/**
 * 配资管理模型
 */
class Borrow extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'stock_borrow';

    static $status_str = ['-1'=>'待审核', '0'=>'未通过', '1'=>'操盘中', '2'=>'已结束','3'=>'已逾期'];

    protected function setAddIpAttr($value)
    {
        return get_client_ip(1);
    }

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //配资类型获取器
    public static function getTypeAttr($value)
    {
        $status = ['1'=>'按天配资', '2'=>'按周配资', '3'=>'按月配资', '4'=>'免费体验', '5'=>'免息配资', '6'=>'模拟操盘'];
        return $status[$value];
    }
    //配资单位获取器
    public static function getTypeUnit($value)
    {
        $status = ['5'=>'天','1'=>'天','2'=>'周','3'=>'月','4'=>'天','6'=>'天'];
        return $status[$value];
    }
    //配资审核状态获取器
    public static function getStatusName($value)
    {
        $status = ['0'=>'待审核','1'=>'已通过','2'=>'未通过'];
        return $status[$value];
    }
    //配资类型设置器
    /**
    public function setTypeAttr()
    {
    return self::getData('type');
    }**/

    //关联子账户资金表定义
    public function member()
    {
        return $this->belongsTo('member');
    }

    /*
     * 获取证券类型列表
     * @param array $map 筛选条件
     * @param array $order 排序
     * @return mixed
     */
    public static function getList($map = [], $order = [],$listRows=20)
    {
        $where=[];
        $where['b.status'] = input('status');//待审核
        $where['b.status'] == '' && $where['b.status'] = -1;
        $data_list = self::view('stock_borrow b', true)
            ->view('member', 'mobile,name', 'member.id=b.member_id', 'left')
            ->view('stock_subaccount s','sub_account','s.id=b.stock_subaccount_id','left')
            ->where($map)
            ->where($where)
            ->order($order)
            ->paginate($listRows, false, ['query' => request()->param()])
            ->each( function($item, $key){
                $item->deposit_money   = money_convert($item->deposit_money);
                $item->init_money      = money_convert($item->init_money);
                $item->borrow_money    = money_convert($item->borrow_money);
                $item->borrow_interest = money_convert($item->borrow_interest);
                $item->stock_money     = money_convert($item->stock_money);
                if($item->getData('type')===3){$unit='个月';}elseif($item->getData('type')===2){$unit='周';}else{$unit='天';}
                $item->borrow_duration .= $unit;
            });
        return $data_list;
    }
    public static function getListAll($map=[], $order=[],$listRows=20)
    {
        //print_r($map);exit;
        $data_list = self::view('stock_borrow b', true)
            ->view('member', 'mobile,name', 'member.id=b.member_id', 'left')
            ->view('stock_subaccount s','sub_account','s.id=b.stock_subaccount_id','left')
            ->view('st_stock_subaccount_money sm','avail,freeze_amount,return_money,stock_addfinancing,stock_addmoney','sm.stock_subaccount_id=b.stock_subaccount_id','left')
            ->where($map)
            ->order($order)
            ->paginate($listRows, false, ['query' => request()->param()])
            ->each( function($item, $key){
                $item->sub_id          = $item->stock_subaccount_id;
                $item->deposit_money   = money_convert($item->deposit_money);
                $item->init_money      = money_convert($item->init_money);
                $item->borrow_money    = money_convert($item->borrow_money);
                $item->borrow_interest = money_convert($item->borrow_interest);
                $item->stock_money     = money_convert($item->stock_money);
                $item->status_n        = self::$status_str[$item->status];
                $item->end_time        = date('Y-m-d H:i:s',$item->end_time);
                
                if($item->getData('type')===3){$unit='个月';}elseif($item->getData('type')===2){$unit='周';}else{$unit='天';}
                $item->borrow_duration .= $unit;
            });
        return $data_list;
    }
    /*
     * 获取到期配资列表
     * @param array $map 筛选条件
     * @param array $order 排序
     * @return mixed
     */
    public static function getEnd($map = [], $order = [])
    {
        $data_list = self::view('stock_borrow b', true)
            ->view("member", 'mobile,name', 'member.id=b.member_id', 'left')
            ->view("stock_subaccount s",'sub_account','s.id=b.stock_subaccount_id','left')
            ->view("stock_subaccount_risk r",'renewal,autoclose','r.id = b.stock_subaccount_id','left')
            ->where($map)
            ->where('b.status','in',[1,3])
            ->where("b.end_time","<=",time()+32400)
            ->order($order)
            ->paginate()
            ->each( function($item, $key){
                $item->deposit_money = money_convert($item->deposit_money);
                $item->init_money = money_convert($item->init_money);
                $item->borrow_money = money_convert($item->borrow_money);
                $item->borrow_interest = money_convert($item->borrow_interest);
                $item->stock_money = money_convert($item->stock_money);
                if($item->getData('type')===3){$unit='个月';}elseif($item->getData('type')===2){$unit='周';}else{$unit='天';}
                $item->borrow_duration .= $unit;
            });
        return $data_list;
    }

    /*
    * 获取即将到期配资列表
    * @param array $map 筛选条件
    * @param array $order 排序
    * @return mixed
    */
    public static function getSoonExpire($map = [], $order = [])
    {
        $tis = 3*86400+time();
        $data_list = self::view('stock_borrow b', true)
            ->view("member", 'mobile,name', 'member.id=b.member_id', 'left')
            ->view("stock_subaccount s",'sub_account','s.id=b.stock_subaccount_id','left')
            ->where($map)
            ->where(['b.status'=>1])
            ->where('b.end_time','<=',$tis)
            ->order('b.id desc')
            ->paginate()
            ->each( function($item, $key){
                $item->deposit_money = money_convert($item->deposit_money);
                $item->init_money = money_convert($item->init_money);
                $item->borrow_money = money_convert($item->borrow_money);
                $item->borrow_interest = money_convert($item->borrow_interest);
                $item->stock_money = money_convert($item->stock_money);
                if($item->getData('type')===3){$unit='个月';}elseif($item->getData('type')===2){$unit='周';}else{$unit='天';}
                $item->borrow_duration .= $unit;
            });


        return $data_list;
    }

    /**
     * 获取待审核的配资记录信息
     * @param array $id 配资ID
     * @return mixed
     */
    public static function getEditBorrow($id=null)
    {
        $where['b.id'] = intval($id);
        $where['b.status'] = -1;//待审核
        $data_list = self::view('stock_borrow b', true)
            ->view("member m", 'mobile,name,pid', 'm.id=b.member_id', 'left')
            //->view("stock_subaccount sub", true, 'sub.id=b.stock_subaccount_id', 'left')
            ->where($where)
            ->find();

        if(!is_null($data_list)){
            if(isset($data_list['pid'])&&$data_list['pid']>1){
                $res=Db::view("admin_user a")
                    ->view('admin_role r','description','r.id=a.role')
                    ->where(["a.id"=>$data_list['pid']])
                    ->find();
                if($res){
                    $data_list['agent']=$res['description']." : ".$res['username'];
                }else{
                    $data_list['agent']="";
                }
            }

            $data_list['deposit_money']   = money_convert($data_list['deposit_money']);
            $data_list['init_money']      = money_convert($data_list['init_money']);
            $data_list['borrow_money']    = money_convert($data_list['borrow_money']);
            $data_list['borrow_interest'] = money_convert($data_list['borrow_interest']);
            $data_list['stock_money']     = money_convert($data_list['stock_money']);
			$data_list['offset_fee']      = money_convert($data_list['offset_fee']);
        }
        return $data_list;
    }

    /**
     * 保存审核的配资记录信息
     * @param array $data 配资信息
     * @return mixed
     */
    public function saveBorrow($data)
    {
        $contents = trim($data['contents']);//审核信息
        //获取会员信息及会员资金信息
        $minfo_m =  Db::name('member')->where(['id'=>$data['member_id']])->where(['status'=>1])->find();
        //当前配资冻结金额
        $sumMoney = ($data['deposit_money'] + $data['borrow_interest']);

        $record = new RecordModel;
        if($data['v_status']==0){//审核未通过
            // 审核不通过，资金解冻、返还利息
            //更新资金表
            Db::startTrans();
            $minfo=Db::name("money")->where(['mid'=>$data['member_id']])->lock(true)->find();
            $mmoney['freeze']  = $minfo['freeze'] > $sumMoney ? $minfo['freeze']  - $sumMoney : 0;//资金解冻，减掉冻结中的资金
            $mmoney['account'] = $minfo['account'] + $sumMoney;//资金解冻，增加会员资金账户余额

			//webtext 退还管理费
			$offset_fee = Db::name('stock_borrow')->where(['id' => $data['id']])->value('offset_fee'); //获取抵扣的管理费
			$mmoney['give_fee'] = $minfo['give_fee'] + $offset_fee;

            $money_res  = Money::where(['mid'=>$data['member_id']])->update($mmoney);
            $record_res = $record->saveData($data['member_id'], $sumMoney, $mmoney['account'], 21, '配资审核未通过，解冻保证金到余额', $offset_fee, $mmoney['give_fee']);
            $res = $this->where(['id'=>$data['id']])->update(['status'=>0]);
            if($res && $money_res && $record_res){
                Db::commit();
                return ['status'=>2, 'msg'=>'审核未通过，处理成功'];
            }else{
                Db::rollback();
                return ['status'=>0, 'msg'=>'未知错误，处理失败'];
            }
        }else{//审核通过
            //根据子账户ID获取子账户信息
            $subInfo = SubAccountModel::where('id',$data['stock_subaccount_id'])->find()->toarray();
            if (empty($subInfo['sub_account']) || empty($subInfo['sub_pwd'])) {
                return ['status'=>0, 'msg'=>'子账户帐号或密码不能为空！'];
            }
            $contents .= "  您的股票交易账号为：".$subInfo['sub_account']." 密码：".$subInfo['sub_pwd'];
            Db::startTrans();
            $minfo=Db::name("money")->where(['mid'=>$data['member_id']])->lock(true)->find();
            //更新资金表
            $mmoney['freeze']          = $minfo['freeze'] > $sumMoney ? $minfo['freeze'] - $sumMoney : 0;//资金解冻，减掉冻结中的资金
            $mmoney['operate_account'] = $minfo['operate_account'] + $data['init_money'];//配资成功，增加该配资的初始操盘资金
            $mmoney['bond_account']    = $minfo['bond_account'] + $data['deposit_money'];
            // 启动事务
            //还息明细表
            $stockDetail = Db::name('stock_detail');
            $insert_res=true;
            if ($data['type'] == "按月配资"&&$data['borrow_duration']>1) {//按月并且大于一个月
                $data['total'] = $data['borrow_duration'];
                //插入还息明细表
                for ($i = 1; $i <= $data['borrow_duration']; $i++) {
                    $detailData['status'] = 1;
                    $detailData['borrow_id'] = $data['id'];
                    $detailData['mid'] = $data['member_id'];
                    $detailData['interest'] = $data['borrow_interest'] / $data['borrow_duration'];
                    $detailData['receive_interest'] = $data['borrow_interest'] / $data['borrow_duration'];
                    $detailData['sort_order'] = $i;
                    $detailData['total'] = $data['borrow_duration'];
                    $detailData['deadline'] = $data['borrow_duration'] == 1 ? time() : strtotime("+{$i} Month");
                    $detailData['repayment_time'] = time();
                    $insert_res=$stockDetail->insert($detailData);
                    if(!$insert_res){
                        break;
                    }
                }
                $stock_res = true;
            }else{
                $stock_res=true;
            }
            $rebate=true;

            //webtext 退还管理费
      		$offset_fee = Db::name('stock_borrow')->where(['id' => $data['id']])->value('offset_fee'); 
            //获取抵扣的管理费
            $subResult = Money::where(['mid'=>$data['member_id']])->update($mmoney);
            // 更新资金日志表信息
            $mmLogRet = $record->saveData($data['member_id'], $sumMoney, $minfo['account'], 22, '配资审核通过，解冻保证金到配资账户',$offset_fee , $minfo['give_fee']);
            //更新配资表信息
            //$borrow = self::where('id',$data['id']);
            $dataInfo['status'] = $data['v_status'];
            $dataInfo['stock_subaccount_id'] = $data['stock_subaccount_id'];
            //print_r($dataInfo);exit;
            switch ($data['type']){
                case "按月配资":
                    $dataInfo['verify_time']=time();
                    $duration=$data['borrow_duration']." month";
                    if(time()<mktime(14,57)){
                        $end_time=date('Y-m-d', strtotime("+{$duration}")-86400);
                    }else{
                        $end_time=date('Y-m-d', strtotime("+{$duration}"));
                    }
                    if(getEndDay2('now', festival())===1&&time()<mktime(14,57)){
                        $dataInfo['verify_time'] = time();
                    }else{
                        $dataInfo['verify_time'] = strtotime(getEndDay('now', 1,festival())." 09:00:00");
                    }
                    break;
                case "按周配资":
                    $dataInfo['verify_time']=time();
                    $duration=$data['borrow_duration']." week";
                    if(time()<mktime(14,57)){
                        $end_time=date('Y-m-d', strtotime("+{$duration}")-86400);
                    }else{
                        $end_time=date('Y-m-d', strtotime("+{$duration}"));
                    }
                    if(getEndDay2('now', festival())===1&&time()<mktime(14,57)){
                        $dataInfo['verify_time'] = time();
                    }else{
                        $dataInfo['verify_time'] = strtotime(getEndDay('now', 1,festival())." 09:00:00");
                    }
                    break;
                case "按天配资":
                    if(getEndDay2('now', festival())===1&&time()<mktime(14,57)){
                        $dataInfo['verify_time'] = time();
                    }else{
                        $dataInfo['verify_time'] = strtotime(getEndDay('now', 1,festival())." 09:00:00");
                    }
                    $start=date('Y-m-d',$dataInfo['verify_time']);
                    $data['borrow_duration']=$data['borrow_duration']-1;
                    $end_time = getEndDay($start, $data['borrow_duration'],festival());
                    break;
                default:
                    if(getEndDay2('now', festival())===1&&time()<mktime(14,57)){
                        $dataInfo['verify_time'] = time();
                    }else{
                        $dataInfo['verify_time'] = strtotime(getEndDay('now', 1,festival())." 09:00:00");
                    }
                    $start=date('Y-m-d',$dataInfo['verify_time']);
                    $data['borrow_duration']=$data['borrow_duration']-1;
                    $end_time=getEndDay($start, $data['borrow_duration'],festival());
                    break;
            }
            $dataInfo['end_time'] = strtotime($end_time." 14:57:00");
            $dataInfo['account_id']  = $subInfo['account_id'] ;
            $dataInfo['sub_account'] = $subInfo['sub_account'];
            //print_r($dataInfo);exit;
            $ret = self::where(['id' =>$data['id'], 'status' => -1])->update($dataInfo);
            //print_r($subInfo);exit;
            if(empty($subInfo['uid']) && $ret){
                $pram['uid']    = $data['member_id'];
                $pram['status'] = 1;
                $mmRet  = SubAccountModel::where(['id' => $subInfo['id']])->update($pram);
            }else{
                $mmRet=false;
            }
            // 子账户风控
            $risk['loss_warn']      = $data['loss_warn'];
            $risk['loss_close']     = $data['loss_close'];
            $risk['position']       = $data['position'];
            $risk['prohibit_open']  = $data['prohibit_open'];
            $risk['prohibit_close'] = $data['prohibit_close'];
            //$risk['prohibit_back'] = $data['prohibit_back'];
            $risk['renewal']        = $data['renewal'];
            $risk['autoclose']      = $data['autoclose'];
            $risk['update_time']    = time();
            $risk_res = Db::name('stock_subaccount_risk')
                ->where(['stock_subaccount_id'=>$data['stock_subaccount_id']])
                ->update($risk);
            $subaccount_money['stock_subaccount_id']= $data['stock_subaccount_id'];
            $subaccount_money['commission_scale']   = $data['commission_scale'];
            $subaccount_money['min_commission']     = $data['min_commission'];
            $subaccount_money['rate_scale']         = $data['rate_scale'];
            $subaccount_money['profit_share_scale'] = $data['profit_share_scale'];
            $subaccount_money['deposit_money']      = $data['deposit_money'];
            $subaccount_money['borrow_money']       = $data['borrow_money'];
            $subaccount_money['avail']              = $data['init_money'];
            $subaccount_money['update_time']        = time();
            $subaccount_money_res = Db::name('stock_subaccount_money')->save($subaccount_money);
			//webtext配资返佣修改
            if ($data['type'] == "按月配资" || $data['type'] == "按天配资" || $data['type'] == "按周配资") {
                //推荐人返利 只有按天、按周配资、按月配资推荐人才会返利
                $investor = $data['member_id'];
                $recommendor = Db::name('member_invitation_relation')->where("invitation_mid = {$investor}")->value('mid');
                if (!is_null($recommendor)) {//如果存在推荐人，则进行推荐人返佣计算
					//$memberInfo = MemberModel::getMemberInfoByID($recommendor);//配资用户信息
					//print_r($memberInfo['name']);exit;
                    $rebate = $this->sendRebate($investor, $minfo_m, $data['id'], $data['borrow_interest']);
                }
                //print_r($rebate);return ['status'=>0, 'msg'=>'未知错误2，处理失败'];
				//$rebate = $this->sendRebate($data['member_id'], $minfo_m, $data['id'], $data['borrow_interest']);
            }
            if($mmRet && $mmLogRet!== false && $ret && $subResult && $risk_res && $subaccount_money_res && $stock_res && $rebate && $insert_res){
                //添加站内信信息
                //$MemberMessageModel = new MemberMessageModel();
                //$MemberMessageModel->addInnerMsg($data['member_id'],'配资审核通知',$contents);//站内信
                Db::commit();
                return ['status'=>1, 'msg'=>'审核通过，处理成功'];
            }else{
                Db::rollback();
                return ['status'=>0, 'msg'=>'未知错误2，处理失败'];
            }
        }
    }
    /*
     * 发送返利给推荐人
     * 返利金额
     * @param $investor 当前用户id
     * @param $investor 配资人信息
     * @param $borrowType 配资ID
     * @param $memberInfo 会员信息及资金信息数据集
     * @return true 无论是否成功，都返回true，不影响后续操作
     */

    public function sendRebate($investor, $memberInfo, $borrowType = '', $money = 0)
    {
		$recommender = Db::name('member_invitation_relation')->where("invitation_mid = {$investor}")->value('mid');
		if (!$recommender) {
			return true;
		}
       	//$borrowInfo = self::get($borrowId);
        $rate = sysConfig('rebate');//获取全局参数推荐人返佣比例
        $amount = $money * $rate / 100;//返佣
        //print_r($money);return;
		$info = "您推荐的用户" . $memberInfo['mobile'] . "(".$memberInfo['name'].")配资成功，配资管理费：" . $money . "元，您获得返利： " . $amount . "元.";
        if ($borrowType == 'expend') { //扩大配资
			$info = "您推荐的用户" . $memberInfo['mobile'] . "(".$memberInfo['name'].")扩大配资成功，配资管理费：" . $money . "元，您获得返利： " . $amount . "元.";
		}
        //将返佣插入推荐人返佣资金记录表
        $dataRecord['mid']         = $recommender;//$investor;
        $dataRecord['money']       = $amount;
        $dataRecord['remark']      = $info;
        $dataRecord['create_time'] = time();
        $record = Db::name('member_invitation_record')->insert($dataRecord);
        $money_info=Money::getMoney($recommender);

        if(isset($money_info['account'])){
            $mmoney['account']=$money_info['account']+$amount;
            $money_res=Money::money_up($recommender,$mmoney);
        }else{
            $mmoney['account']=$money_info['account'];
            $money_res=false;
        }
        //将返佣插入资金记录
        $RecordModel = new RecordModel();
        $moneyRecord = $RecordModel->saveData($recommender,$amount,$mmoney['account'],10,$info);
        $invInfo = Db::name('member')->where("id" , $investor)->find();
        if(empty($invInfo)) return false; 
		//上级代理资金变更记录
		$effectArr = array(
			'mid'           => $recommender,
			'affect_mid'    => $invInfo['id'],
			'affect'        => $amount,
			'info'          =>  "您推荐的用户" . $invInfo['mobile'] . "(".$invInfo['name'].")配资成功，配资管理费：" . $money . "元，您获得返利： " . $amount . "元.",
			'create_time'   => $dataRecord['create_time'],
			'create_ip'     => getClientIp(),
			'affect_mobile' => $invInfo['mobile'],
			'rate'	        => $rate,
			'money_a'       => $money,
 		);
		$agentRecord = DB::name('agents_back_money')->insert($effectArr);
        //print_r($agentRecord);return;
        if($record && $moneyRecord && $agentRecord){
            return true;
        }
    }
    /***代理分配佣金**/
    public function agentToRateMoney($mid,$borrowId,$money,$type_d = 1)
    {
        $memberInfo = MemberModel::getMemberInfoByID($mid);//配资用户信息
        //$arr = self::getFarAgentArr($mid);//上级代理列表 进行查询数据进行分配佣金
        $rate_c = sysConfig('agent_back_rate');
        $rate_u = sysConfig('member_back_rate');
        if($memberInfo['agent_far']){//如果有邀请用户则执行分佣
            $info= MemberModel::getMemberInfoByID($memberInfo['agent_far']);//上级用户
            $rate = $info['agent_rate'];
            $agent_level = $info['agent_id'];
            if($agent_level==1){//上级代理情况分析
                //一级代理分配钱数 to_money_1
                $to_money_1 = round($money * $rate / 100,4);
                self::sendRebate_toAgent($info['id'],$borrowId,$memberInfo,$to_money_1,$rate,$money,$type_d);
            }elseif ($agent_level ==2){
                $info_f = MemberModel::getMemberInfoByID($info['agent_far']);//一级代理信息
                $rate_1 = $info_f['agent_rate'];//一级代理信息
                $to_money_1 = round($money * $rate_1 / 100,4);//一级代理应返金额
                $to_money_2 =  round($money * $rate_1 * $rate / 10000,4);

                $rate_w = $rate_1 * $rate / 100;
                $to_money_1_a =  round(($to_money_1 - $to_money_2),4);
                self::sendRebate_toAgent($info['id'],$borrowId,$memberInfo,$to_money_2,$rate_w,$money,$type_d);//二级代理返佣
                self::sendRebate_toAgent($info_f['id'],$borrowId,$info,$to_money_1_a,$rate_1,$money,$type_d);//一级代理返佣
            }elseif($agent_level==3){
                $info_f = MemberModel::getMemberInfoByID($info['agent_far']);//二级代理信息
                $info_f_1 = MemberModel::getMemberInfoByID($info_f['agent_far']);//一级代理信息
                $rate_2 = $info_f['agent_rate'];//二级返佣比例
                $rate_1 = $info_f_1['agent_rate'];//一级返佣比例

                $to_money_1 = round($money * $rate_1 / 100,4);//一级代理应返金额
                $to_money_2 =  round($money * $rate_2 * $rate_1 / 10000,4);//二级理应返金额
                $to_money_3 =  round($money * $rate_2 * $rate_1 * $rate / 1000000,4);//三级理应返金额

                $rate_w = $rate_1 * $rate_2 / 100;//2
                $rate_w_3 = $rate_1 * $rate_2 * $rate /10000;//2
                $to_money_1_a =  round(($to_money_1 - $to_money_2),4);
                $to_money_2_a =  round(($to_money_2 - $to_money_3),4);

                self::sendRebate_toAgent($info['id'],$borrowId,$memberInfo,$to_money_3,$rate_w_3,$money,$type_d);//三级代理返佣
                self::sendRebate_toAgent($info_f['id'],$borrowId,$info,$to_money_2_a,$rate_w,$money,$type_d);//二级代理返佣
                self::sendRebate_toAgent($info_f_1['id'],$borrowId,$info_f,$to_money_1_a,$rate_1,$money,$type_d);//一级代理返佣

            }else{//上级是普通用户
                $time = time();
                $rate = $rate_u;
                $rate_time = sysConfig('member_back_time') ? sysConfig('member_back_time') : 0;
                $agent_time = $memberInfo['create_time'] + ($rate_time * 86400 * 30);
                if($agent_time > $time){
                    if(!$rate) $rate = $rate ? $rate : $rate_u;//理想状态下 只有一级代理可能不填比例值
                    $to_money_u = round($money * $rate / 100,4);
                    self::sendRebate_toAgent($info['id'],$borrowId,$memberInfo,$to_money_u,$rate,$money,$type_d);
                }
            }
        }
    }
    /*
     * 发送返利给推荐人
     * 返利金额
     * @param $recommender 推荐人id
     * @param $borrowId 配资ID
     * @param $memberInfo 会员信息及资金信息数据集
     * @param $amount 配资金额
     * @return true 无论是否成功，都返回true，不影响后续操作
     */
    public function sendRebate_toAgent($recommender,$borrowId,$memberInfo,$amount,$rate,$money_a,$type_d =1)
    {
        if ($type_d ==2){
            $borrowInfo =  Db::name('stock_addfinancing')->where(['id'=>$borrowId])->find();
            $type_info =  '扩大配资成功，配资管理费';
            $borrowInfo_money = $borrowInfo['borrow_interest'];
            $borrowInfo_member_id =  $borrowInfo['uid'];
            $amount = $amount;
        }elseif ($type_d==3){
            $type_info =  '申请续期成功，配资管理费';
            $borrowInfo =  Db::name('stock_renewal')->where(['id'=>$borrowId])->find();
            $borrowInfo_money = $borrowInfo['borrow_fee'];
            $borrowInfo_member_id = $borrowInfo['uid'];
            $money_a = $money_a;
            $amount = $amount;
        }elseif ($type_d==4){
            $type_info =  '自动续期成功，配资管理费';
            $borrowInfo =  Db::name('stock_borrow')->where(['id'=>$borrowId])->find();

            $borrowInfo_money = $money_a;
            $borrowInfo_member_id = $borrowInfo['member_id'];
            $money_a = $money_a;

            $amount = $amount;
        }else{
            $borrowInfo = Db::name('stock_borrow')->where(['id'=>$borrowId])->find();
            $type_info = '配资成功，配资管理费';
            $borrowInfo_money = $borrowInfo['borrow_interest'];
            $borrowInfo_member_id = $borrowInfo['member_id'];
        }
        //print_r($borrowInfo);return;
        //备注说明信息
        $info = "您推荐的用户" . $memberInfo['mobile'] . "(".$memberInfo['name'].")".$type_info."：" . $borrowInfo_money . "元，您获得返利： " . $amount . "元.";

        // 启动事务
        Db::startTrans();
        try{
            ////将返佣插入推荐人返佣资金记录表
            $dataRecord['mid']         = $recommender;//$investor;
            $dataRecord['money']       = $amount;
            $dataRecord['remark']      = $info;
            $dataRecord['create_time'] = time();
            $record = Db::name('member_invitation_record')->insert($dataRecord);
            
            $money_info=Money::getMoney($recommender);
            if(isset($money_info['account'])){
                $mmoney['account']=$money_info['account'] + $amount;
                $money_res=Money::money_up($recommender,$mmoney);
            }else{
                $mmoney['account']=$money_info['account'];
                $money_res=false;
            }

            //资金记录
            $RecordModel = new RecordModel();
            $moneyRecord = $RecordModel->saveData($recommender,$amount,$mmoney['account'],10,$info);

            //将返佣插入资金记录	($mid,$affect_mid,$affect, $info='')
            $infos = "您推荐的用户" . $memberInfo['mobile'] . "(".$memberInfo['name'].")".$type_info."：" .$borrowInfo_money ."元，您获得返利：" . $amount . "元.";
            $RecordAgentModel = new RecordAgentModel();
            $moneyRecordAgent = $RecordAgentModel->saveData($recommender,$borrowInfo_member_id,$amount,$infos,$memberInfo['mobile'],$rate,$money_a);
            //print_r($moneyRecord);return;
            if($record && $moneyRecord && $money_res && $moneyRecordAgent){
                Db::commit();
            }
        } catch (\Exception $e) {
            Db::rollback();
        }
    }
    /*
     * 查询正在操盘中的实盘配资总金额
     * @param $accountID 证券id
     * @return 返回配资总金额
     */
    public static function getRealBorrowmoney($accountID){
        //$res=Db::name("stock_subaccount")->field("uid")->where(["account_id"=>$accountID])->group("uid")->select();
        $total = self::where(["status" => 1, "account_id" =>$accountID])->sum("init_money");
        return intval($total[0]['borrowMoney']);
    }
    /*
     * 根据ID返回配资记录
     * @id 配资记录ID
     */
    public static function getBorrowById($id,$status=null)
    {
        if($status == null){
            return   $binfo = self::where(["id"=>$id])->find();
        }else{
            return   $binfo = self::where(["id"=>$id,'status'=>$status])->find();
        }
        //print_r($binfo);exit;
    }

    /*
     * 是否已有试用、免费、模拟操盘校验
    */
    public static function trycheck($mid,$type){
        return self::where(['member_id'=>$mid])->where(['type'=>$type])->where('status','<>','0')->find();
    }
    /*
     * 已有申请验证
    */
    public static function onecheck($mid){
        return self::where(['member_id'=>$mid])->where(['status'=>"-1"])->find();
    }
    /*
    * 已有申请验证
    */
    public static function onechecktype($mid){
        $map = "status !=0";
        return self::where(['member_id'=>$mid])->where($map)->find();
    }
    /*
     * 会员发起配资申请存库
     * @return [type] [description]
     */
    public static function createStock($data=[])
    {
        if(empty($data)) return ['status'=>'0', 'msg'=>'缺少参数'];
        $interest  = self::interest($data['type'], $data['rate'], $data['borrow_money'], $data['borrow_duration']);
		//webtext 配资管理费抵扣
		$offsetfee = Money::getOffsetFee($data['member_id'], $interest);
		$interest  = $offsetfee['remain_fee'];
		$data['offset_fee'] = $offsetfee['can_offset'];
        $data['borrow_interest'] = $interest;
        $need_money = bcadd($interest, $data['deposit_money']);
        Db::startTrans();
        $member_money = Money::where(['mid'=>$data['member_id']])->lock(true)->find();
        if($member_money['account'] < $need_money){
            return ['status'=>0, 'msg'=>'资金不足请充值'];
        }
        $account = $member_money['account'] - $need_money;
        $freeze  = $member_money['freeze']  + $need_money;
		//webtext扣除管理费
		$update_give_fee = $member_money['give_fee'] - $offsetfee['can_offset'];
        try{
            $money_res   = Money::where(['mid'=>$data['member_id']])->update(['account'=>$account, 'freeze'=>$freeze, 'give_fee' => $update_give_fee]);
            $record      = new RecordModel;
            $record_res1 = $record->saveData($data['member_id'], -abs($data['deposit_money']), $account, 33, '申请配资:'.$data['order_id'], - $data['offset_fee'], $update_give_fee);
            $record_res2 = $record->saveData($data['member_id'], -abs($interest), $account, 16, '申请配资:'.$data['order_id'], - $data['offset_fee'], $update_give_fee);
            $result      = self::create($data);
            if($money_res !== null && $result && $record_res1 && $record_res2){
                Db::commit();
                return ['status'=>'1', 'msg'=>'提交成功 等待审核'];
            }else{
                Db::rollback();
                return ['status'=>'0', 'msg'=>'系统异常'];
            }
        }catch(\Exception $e){
            Db::rollback();
            return ['status'=>'0', 'msg'=>$e->getMessage()];
        }
    }

    /*
     * 计算利息
     * @param  intval $type         配资类型
     * @param  float $rate          手续费费率
     * @param  intval $borrow_money 配资金额
     * @param  intval $duration     融资期数
     * @return int   利息
     */
    public static function interest($type, $rate, $borrow_money, $duration)
    {
        
        $rate = floatval($rate/100);
        //1: 按天配资 2: 按周配资 3: 按月配资          4:免费体验 5:免息配资 6:模拟操盘
        if (in_array($type, array('1', '2', '3'))){
            $interest = ($borrow_money*1)*($rate*1)*($duration*1);
        }else{
            $interest = 0;
        }
        return floatval($interest);
    }

    public static function getBorrow($mid, $limit='', $map=[], $order='id desc')
    {
        $map['member_id'] = $mid;
        $data_list = self::view('stock_borrow sb', true)
            ->view('stock_subaccount_risk ssr', 'loss_warn, loss_close,renewal', 'sb.stock_subaccount_id=ssr.stock_subaccount_id', 'left')
            ->view('stock_subaccount_money ssm', 'avail,return_money, return_rate', 'sb.stock_subaccount_id=ssm.stock_subaccount_id', 'left')
            ->where($map)
            ->order($order)
            //->limit($limit)
            ->paginate($limit)
            ->each( function($item, $key){
                $item->loss_warn_money  = $item->borrow_money+$item->loss_warn  * $item->deposit_money ;
                $item->loss_close_money = $item->borrow_money+$item->loss_close * $item->deposit_money;
                $item->status_text = self::$status_str[$item->status];

            });
        return $data_list;
    }
    /*
     * 返回带收益的borrow表信息
     */
    public static function getBorrowinfo($mid, $limit='', $map=[], $order='id desc')
    {

        $data_list = self::view('stock_borrow sb', "type as types,*")
            ->view("stock_subaccount subaccount", "sub_account", "sb.stock_subaccount_id=subaccount.id", "left")
            ->view('stock_subaccount_risk ssr', 'loss_warn, loss_close,renewal', 'sb.stock_subaccount_id=ssr.stock_subaccount_id', 'left')
            ->view('stock_subaccount_money ssm', 'avail,return_money, return_rate', 'sb.stock_subaccount_id=ssm.stock_subaccount_id', 'left')
            ->where($map)
            ->where(['member_id'=>$mid])
            ->where("sb.type","<>",6)
            ->order($order)
            ->paginate($limit, false, ['query' => request()->param()])
            ->each( function($item, $key){
                
                $item->loss_warn_money  = $item->borrow_money+$item->loss_warn  * $item->deposit_money;
                $item->loss_close_money = $item->borrow_money+$item->loss_close * $item->deposit_money;
                $item->return_money = $item->return_money;
                if($item->end_time<=time() && $item->status!=2 && $item->end_time > 0){
                    $item->status=3;
                }
                
                if($item->types==3){
                    if(($item->verify_time+2592000)>time()){
                        $item->management ='配资管理费';
                    }else{
                        $item->management ='配资管理费(月)';
                    }
                    $item->imgsType= 'yuepeizi.png';
                }elseif($item->types==5){
                    $item->management ='配资管理费(免)';
                    $item->imgsType= 'mianxipeizi.png';
                }elseif($item->types==1){
                    $item->management ='配资管理费(天)';
                    $item->imgsType= 'tianpeizi.png';
                }elseif($item->types==2){
                    $item->management ='配资管理费(周)';
                    $item->imgsType= 'zhoupeizi.png';
                }elseif($item->types==4){
                    $item->management ='配资管理费(体)';
                    $item->imgsType= 'tiyan.png';
                }
                
                $item->status_text = self::$status_str[$item->status];
                
                $res=Db::name('stock_position')->where(['sub_id'=>$item->stock_subaccount_id,'buying'=>0])->select();
                $sum=0;
                //$item->btn="去交易";
                //下面这段代码会查询实时行情，会导致变慢，所以去掉了。
                if(!empty($res)){//这段代码
                    foreach ($res as $k=>$v){
                        $Qdata = RedisUtil::getQuotationData($v['gupiao_code'],toMarket($v['gupiao_code']),true);
                        if(!isset($Qdata['Price'])){
                            $Qdata['Price']=0;
                        }
                        $sum+=$Qdata['Price']*$v['stock_count'];
                    }
                    //$item->btn="查看实盘交易";
                }
                $item->sum_money=$sum;
            });
        return $data_list;
    }
    /**
     * 根据配资ID获取配资记录详情信息
     * @param array $id 配资ID
     * @author 路人甲乙
     * @return mixed
     */
    public static function getBorrowDetail($id=null)
    {
        $where['b.id'] = intval($id);
        $data_list = self::view('stock_borrow b', true)
            ->view("member m", 'mobile,name', 'm.id=b.member_id', 'left')
            ->view('stock_subaccount_risk ssr', 'loss_warn, loss_close,renewal', 'b.stock_subaccount_id=ssr.stock_subaccount_id', 'left')
            ->view('stock_subaccount_money ssm', 'avail,return_money,available_amount,return_rate', 'b.stock_subaccount_id=ssm.stock_subaccount_id', 'left')
            ->view('stock_subaccount ss', 'sub_account,sub_pwd,agent_id', 'ss.id=b.stock_subaccount_id', 'left')
            ->where($where)
            ->find();
        //print_r($data_list);exit;
        if($data_list['type']=='按周配资'){
            $data_list['type_code'] = 2;
            $data_list['units'] = '周';
        }elseif($data_list['type']=='按天配资'){
            $data_list['type_code'] = 1;
            $data_list['units'] = '天';
        }elseif($data_list['type']=='按月配资'){
            $data_list['type_code'] = 3;
            $data_list['units'] = '月';
        }elseif($data_list['type']=='免费体验'){
            $data_list['type_code'] = 4;
            $data_list['units'] = '体';
        }elseif($data_list['type']=='免息配资'){
            $data_list['type_code'] = 5;
            $data_list['units'] = '免';
        }
        if(!is_null($data_list)){
            if($data_list['loss_warn']===null){
                $list = self::view('stock_borrow b', true)->where($where)->find();
                $data_list['loss_warn']=$list['loss_warn'];
                $data_list['loss_close']=$list['loss_close'];
            }
            $data_list['loss_warn_money']  = $data_list['borrow_money']+$data_list['loss_warn']  * $data_list['deposit_money'];
            $data_list['loss_close_money'] = $data_list['borrow_money']+$data_list['loss_close'] * $data_list['deposit_money'];

            $pos = StockPosition::where(['sub_id'=>$data_list['stock_subaccount_id'], 'buying'=>0])->select()->toArray();
    		$return_money = 0;
    		foreach ($pos as $key => $val ) {
    			$Qdata = RedisUtil::getQuotationData($val['gupiao_code'],toMarket($val['gupiao_code']),true);
    			if($Qdata['Price'] == '') continue;
    			$return_money += ($Qdata['Price'] - $val['buy_average_price']) * $val['stock_count'];
    		}
    		$data_list['return_money']     = round($return_money, 2);
    		
            //$data_list['return_money'] = money_convert($data_list['available_amount']);
            if($data_list['end_time']<=time()&&$data_list['status']==1&&$data_list['end_time'] > 0){
                $data_list['status']=3;
            }
            $data_list['status'] = self::$status_str[$data_list['status']];
        }

        return $data_list;
    }
    
    
    /*
     * 获取 扩大配资*追加保证金*申请延期*申请提盈*终止操盘*的审核记录
     *
     */
    public static function getAuditAll($path,$map=[],$order='',$offset=20)
    {
        switch ($path) {
    		//申请延期历史记录
    		case 'renewal' :
    		    $hList=  Db::view('stock_renewal s',true)
    		    ->view('member m', 'mobile, name', 'm.id=s.uid', 'left')
    		    ->view('stock_borrow b', 'type,sub_account', 'b.id=s.borrow_id', 'left')
    		    ->where(['s.type'=>1])
    		    ->where($map)
    		    ->order($order)
    		    ->paginate($offset, false, ['query' => request()->param()])
                ->each( function($item, $key){
                    $item['type_u']     = isset($item['type']) ? self::getTypeUnit($item['type']) : '';
                    $item['type_n']     = isset($item['type']) ? self::getTypeAttr($item['type']) : '';
                    $item['status_n']   = self::getStatusName($item['status']);
                    $item['borrow_fee'] = money_convert($item['borrow_fee']);
                    $item['add_time']   = date('Y-m-d H:i:s',$item['add_time']);
                    return $item;
                });
    		    break;
    		//追加保证金历史记录
    		case 'addmoney' :
    		    $hList = Db::view('stock_addmoney s',true)
    		    ->view('member m', 'mobile, name', 'm.id=s.uid', 'left')
    		    ->view('stock_borrow b', 'type,sub_account', 'b.id=s.borrow_id', 'left')
    		    ->where($map)
    		    ->order($order)
    		    ->paginate($offset, false, ['query' => request()->param()])
                ->each( function($item, $key){
                    $item['type_u']   = isset($item['type']) ? self::getTypeUnit($item['type']) : '';
                    $item['type_n']   = isset($item['type']) ? self::getTypeAttr($item['type']) : '';
                    $item['status_n'] = self::getStatusName($item['status']);
                    $item['money']    = money_convert($item['money']);
                    $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
                    return $item;
                });
    		    break;
    		//扩大配资历史记录
    		case 'expend' :
    		    $hList = Db::view('stock_addfinancing s',true)
    		    ->view('member m', 'mobile, name', 'm.id=s.uid', 'left')
    		    ->view('stock_borrow b', 'type,sub_account', 'b.id=s.borrow_id', 'left')
    		    ->where($map)
    		    ->order($order)
    		    ->paginate($offset, false, ['query' => request()->param()])
    		    ->each( function($item, $key){
                    $item['type_u']   = isset($item['type']) ? self::getTypeUnit($item['type']) : '';
                    $item['type_n']   = isset($item['type']) ? self::getTypeAttr($item['type']) : '';
                    $item['status_n'] = self::getStatusName($item['status']);
                    $item['money']    = money_convert($item['money']);
                    $item['borrow_interest']  = money_convert($item['borrow_interest']);
                    $item['last_deposit_money']  = money_convert($item['last_deposit_money']);
                    $item['last_borrow_money']  = money_convert($item['last_borrow_money']);
                    $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
                    return $item;
                });
    		    break;
    		//提取盈利历史记录
    		case 'profit' :
    		    $hList = Db::view('stock_drawprofit s',true)
    		    ->view('member m', 'mobile, name', 'm.id=s.uid', 'left')
    		    ->view('stock_borrow b', 'type,sub_account', 'b.id=s.borrow_id', 'left')
    		    ->where($map)
    		    ->order($order)
    		    ->paginate($offset, false, ['query' => request()->param()])
    		    ->each( function($item, $key){
                    $item['type_u']   = isset($item['type']) ? self::getTypeUnit($item['type']) : '';
                    $item['type_n']   = isset($item['type']) ? self::getTypeAttr($item['type']) : '';
                    $item['status_n'] = self::getStatusName($item['status']);
                    $item['money']    = money_convert($item['money']);
                    $item['borrow_money']  = money_convert($item['borrow_money']);
                    $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
                    return $item;
                });
    		    break;
    		//终止操盘历史记录
    		case 'stop' :
    		    $hList = Db::view('stock_renewal s',true)
    		    ->view('member m', 'mobile, name', 'm.id=s.uid', 'left')
    		    ->view('stock_borrow b', 'type,sub_account,multiple,init_money,borrow_money,deposit_money,borrow_duration', 'b.id=s.borrow_id', 'left')
    		    ->where(['s.type'=>2])
    		    ->where($map)
    		    ->order($order)
    		    ->paginate($offset, false, ['query' => request()->param()])
    		    ->each( function($item, $key){
                    $item['init_money']   = money_convert($item['init_money']);
                    $item['borrow_money'] = money_convert($item['borrow_money']);
                    $item['borrow_fee']   = money_convert($item['borrow_fee']);
                    $item['type_u']       = isset($item['type']) ? self::getTypeUnit($item['type']) : '';
                    $item['type_n']       = isset($item['type']) ? self::getTypeAttr($item['type']) : '';
                    $item['status_n']     = self::getStatusName($item['status']);
                    $item['borrow_fee']   = money_convert($item['borrow_fee']);
                    $item['add_time']     = $item['add_time'] ? date('Y-m-d H:i:s',$item['add_time']) : "--";
                    $item['verify_time']  = $item['verify_time'] ? date('Y-m-d H:i:s',$item['verify_time']) : "--";
                    return $item;
                });
    		    break;
    		default :
    		    $hList =  [];
    		    break;
        }
        return $hList;
    }
    /*
     * 卖出
     * $id 子账户id
     * $code 股票代码
     * $count 卖出数量
     * $sys 是否系统卖出标志 0、非系统卖出 1、系统卖出
     */
    public static function saveSell($data,$sys=0,$price=null){
        if(sysConfig('site_trade_sell') == 0) {
            return ['status' => 0, 'message' => '系统设置不允许卖出股票'];
        }
		//检测股票持仓数量
		$poscount = StockPosition::getCanbuyCount($data['subid'],$data['code']);
		if ($poscount < $data['count']) {
			return ['status'=>0, 'message'=>'可卖股票不足'];
		}
		//获取最新行情
		$Qdata = RedisUtil::getQuotationData($data['code'],toMarket($data['code']));
		if(intval($Qdata["Bp1"]) <= 0)  return ['status' => 0, 'message' => '当前买盘不足，无法即时成交！'];
		
        //检查子账户余额
		$moneyinfo   = SubAccountMoney::getAccountMoney($data['subid']);
		$trade_money = 0;
        if($price > 0){
            $trade_money = intval($data['count']) * intval($price);
        }else{
            $price = $Qdata['Bp1'];//定义委托价格
            $trade_money = intval($data['count']) * intval($price);
        }
        //计算佣金
		$commission  = commission($trade_money,$moneyinfo['commission_scale'],$moneyinfo['min_commission']);
        //印花税
        $stamps      = stamps($trade_money);
		//计算过户费
		$transfer    = transfer($trade_money);
        
        $effectMoney = $trade_money - $transfer - $stamps - $commission;
        
        //写入子账户资金变化表
		Db::startTrans();
		try {
		    $ret = SubAccountMoney::upMoneyLog($data['subid'], $effectMoney, 4);
            if(!$ret){
                Db::rollback();
                return ['status'=>0, 'message'=>"交易失败"];
            }
            $Trust_no  = mt_rand(101010, 999999).substr(strval(time()),1);
            //添加到委托表
            $Trust_res = Trust::sell_m_trust($data, $price, $Trust_no, $sys = 1);
            if(!$Trust_res){
                Db::rollback();
                return ['status'=>0, 'message'=>"交易失败"];
            }
            //持仓数量查询
    		$position = Db::name('stock_position')->where(['sub_id' => $data['subid'],'gupiao_code' => $data['code'],'buying' => 0])->find();
    		$amount   = $position['canbuy_count'] - $data['count'];
    		//持仓减少
    		$pos_res  = Db::name('stock_position')->where(['sub_id' => $data['subid'],'gupiao_code' => $data['code'],'buying' => 0])->dec('canbuy_count',intval($data['count']))->update();
    
            $avail    = $moneyinfo["avail"] + $effectMoney;
            $del_res  = Delivery::sell_m_delivery_order($data['code'], $data['count'], $price, $data['subid'], $commission, $transfer, $Trust_no, $stamps, $avail, $amount, $data['model']);
            //print_r($del_res);exit;
            if(!$del_res || !$pos_res){
    			Db::rollback();
    			return ['status'=>0, 'message'=>"交易失败"];
    		}
		} catch (Exception $e ) {
		    Db::rollback();
			return ['status'=>0, 'message'=>"交易失败"];
		}
		Db::commit();
		return ['status'=>200, 'message'=>'卖出交易已成功'];
    }
    /*
     *  处理到期配资
     *
     */
    public static function endBorrow($id, $status = 1)
    {
        $info = !empty($id) ? Renewal::getStopById($id) : 0;
        if($info){
            $submoney_info = SubaccountMoney::getMoneyByID($info['stock_subaccount_id']);
            $surplus_money = round($submoney_info['avail'], 2);//返回的可用余额
            $addmoney      = round($submoney_info['stock_addmoney'], 2);//累计追加保证金
            $drawprofit    = round($submoney_info['stock_drawprofit'], 2);//累计提取盈利
            //$contents      = "配资使用期限结束";
            Db::startTrans();
            $ret = Renewal::settlement($id,$surplus_money,$addmoney,$drawprofit);
            if ($ret) {
                Db::commit();
                /*发送短信给会员
                $u_info = MemberModel::getMemberInfoByID($info['member_id']);
                if ($u_info['mobile']) {
                    $var = $u_info['mobile'];;
                    $contentarr  = getconfigSms_status(['name'=>'stock_borrow_endedit']);
                    $content     = str_replace(array("#var#"),array($var), $contentarr['value']);
                    if($contentarr['status']==1){
                        sendsms_mandao('',$content,'');
                    }
                }
                发送短信给会员*/
                return ['status'=>200, 'message'=>'结算成功！'];
            } else {
                Db::rollback();
                return ['status'=>0, 'message'=>"提交失败！"];
            }
        }
        
        
        
    }
    /*
     * 判断用户是否有未处理的申请
     */
    public static function checkApply($borrow_id,$uid,$sub_id)
    {
        $m_res = Db::name("stock_addmoney")->where(["status" => 0 ,"borrow_id" => $borrow_id , "uid" => $uid])->find();
        if (!empty($m_res)) {
            return ['status'=>0,'msg'=>'该用户还有未审核的增加保证金申请,请处理！'];
        }
        $r_res = Db::name("stock_renewal")->where(["type" => 1, "status" => 0, "borrow_id" => $borrow_id, "uid" => $uid])->find();
        if (!empty($r_res)) {
            return ['status'=>0,'msg'=>'该用户有未审核的延期申请，请处理!'];
        }
        $a_res = Db::name("stock_addfinancing")->where(["status" => 0 ,"borrow_id" => $borrow_id , "uid" => $uid])->find();
        if (!empty($a_res)) {
            return  ['status'=>0,'msg'=>'该用户有未审核的扩大配资申请，请处理!'];
        }
        $d_res = Db::name("stock_drawprofit")->where(["status" => 0 ,"borrow_id" => $borrow_id , "uid" => $uid])->find();
        if (!empty($d_res)) {
            return  ['status'=>0,'msg'=>'该用户有未审核的提取盈利申请，请处理'];
        }
        $p_res = Db::name("stock_position")->where(["sub_id"=>$sub_id])->where('stock_count','>',0)->find();
        if (!empty($p_res)) {
            return  ['status'=>0,'msg'=>'该用户持有未平仓的股票，请处理'];
        }
        return ['status'=>1,'msg'=>'检查完毕可以清算'];
    }
    /*
     * 停止操盘账户
     */
    public static function stopBorr($borrow_id)
    {
        $stop_res = self::where("id",$borrow_id)->update(['status' => '2']);
        if($stop_res){
            return ['status' => 1,'msg' => '停止操盘账户成功'];
        }else{
            return ['status' => 0,'msg' => '停止操盘账户失败'];
        }
    }
}
