<?php
declare (strict_types = 1);

namespace app\apicom\controller;
use app\apicom\model\Borrow as BorrowModel;
use app\apicom\model\Member as MemberModel;
use app\apicom\model\Record as RecordModel;
use app\apicom\model\Money as MoneyModel;
use app\apicom\model\Addfinancing as AddfinancingModel;
use app\apicom\model\Addmoney as AddmoneyModel;
use app\apicom\model\Renewal as RenewalModel;
use app\apicom\model\StockSubAccountRisk;
use app\apicom\model\StockPosition;
use util\RedisUtil;
use util\BorrowRedis;

use think\facade\Db;
/**
 * 我的配资控制器
 * @package app\member\home
 */
class Financing extends BaseController
{
    /**
     * 我的配资页
     * @return [type] [description]
     */
    public function index()
    {
        $offset  = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $data_list = BorrowModel::getBorrowinfo($this->userId, $offset);
        $data_list->each(function($item, $key){
            $item->create_time      = format_date($item->create_time);
            $item->end_time         = $item->status > 0 ? format_date($item->end_time)    : '--';
            $item->verify_time      = $item->status > 0 ? format_date($item->verify_time) : '--';
            $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->deposit_money    = money_convert($item->deposit_money);
            $item->loss_warn_money  = money_convert($item->loss_warn_money);
            $item->loss_close_money = money_convert($item->loss_close_money);
            $item->avail            = money_convert($item->avail);
        });
        return ajaxmsg('我的配资列表',1,$data_list);
    }
    
    //自动续期状态切换。
    public function autorenewal()
    {
        $id    = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $binfo = BorrowModel::getBorrowById($id);
        if(empty($binfo)||$binfo['member_id']!=$this->userId){
            return ajaxmsg('参数错误',0);
        }
        if(in_array($binfo['type'],[4,5,6])){
            return ajaxmsg('此配资类型不允许自动续期',0);
        }
        if($binfo['status']===1){
            $data  = [];
            $subid = $binfo['stock_subaccount_id'];
            if($subid===0){
                return ajaxmsg('系统错误',0);
            }
            $subres = StockSubAccountRisk::getRisk($subid);
            if(empty($subres)){
                return ajaxmsg('系统错误',0);
            }
            if($subres&&$subres['renewal']===1){
                $data['renewal']=0;
            }
            if($subres&&$subres['renewal']===0){
                $data['renewal']=1;
            }
            $res=Db::name('stock_subaccount_risk')->where(['stock_subaccount_id'=>$subid])->update($data);
            if($res){
                $subres['renewal']=$data['renewal'];
                return ajaxmsg('切换成功',1,$subres['renewal']);
            }else{
                return ajaxmsg('切换失败',0,$subres['renewal']);
            }
        }else{
            return ajaxmsg('配资不在操盘中，不能续期！',0);
        }
    }
    //扩大配资手续费计算
    public function getRateMoney()
    {
        $multiple      = input('multiple' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);//倍率
        $rate          = input('rate' , '');//费率
        $type          = input('type' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);//1、按天 2、按周 3、按月 4、免费体验 5、免费
        $deposit_money = input('deposit_money' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);//保证金
        $endTime       = input('endTime' , '');//到期时间 时间戳
        if(!empty($endTime) && $endTime < time()) return ajaxmsg('当前配资账户已到期',0);
        if($type==1&&time()>mktime(14,45)){
            $endTime=$endTime-86400;
			if($endTime<0)return ajaxmsg('该操盘账户已到期',0);
        }
        $fee = calculate_rate($multiple,$rate,$type,$deposit_money,$endTime);
        if(!$fee)return ajaxmsg('操作失败',0);
        return ajaxmsg('扩大配资手续费计算',1,$fee);
    }
	
    //续期手续费计算
    public function calculate_rate_renewal(){
        $res=request();
        $multiple = intval($res->param('multiple'));//倍率
        $rate = $res->param('rate');//费率
        $type = intval($res->param('type'));//1、按天 2、按周 3、按月 4、免费体验 5、免费
        $deposit_money = intval($res->param('deposit_money'));//保证金
        $cyctime = $res->param('cyctime');//期数
        switch ($type){
            case 1:
                $start=date('Y-m-d',mktime(0,0));
                $endTime=getEndDay($start, $cyctime, festival());
                $endTime=strtotime($endTime);
                if(date('N', mktime(0,0))>5){
                    $endTime=$endTime+86400;
                }
                break;
            case 2:
                $endTime=mktime(0,0)+$cyctime*3600*24*7;
                break;
            case 3:
                $endTime=mktime(0,0)+$cyctime*3600*24*30;
                break;
            default:
                jaxmsg('请求参数错误',0);
        }
        $fee = calculate_rate($multiple,$rate,$type,$deposit_money,$endTime);
        return ajaxmsg('续期手续费计算',1,$fee);
    }

    /**
     * 配资详情页
     * @return [type] [description]
     */
    public function details()
    {
        $borrow_id = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $result    = BorrowModel::getBorrowDetail($borrow_id);
        if($result['member_id'] != $this->userId)  return ajaxmsg('非法请求',0);
        if(empty($result)){ return ajaxmsg('配资未找到',0);}
        $result['mobile']           = substr_replace(strval($result['mobile']),'****',3,4);
        $result['end_time_st']      = $result['end_time'];
        $result['end_time']         = format_date($result['end_time']);
        $result['verify_time']      = format_date($result['verify_time']);
        $result['init_money']       = money_convert($result['init_money']);
        $result['borrow_money']     = money_convert($result['borrow_money']);
        $result['borrow_interest']  = money_convert($result['borrow_interest']);
        $result['loss_warn_money']  = money_convert($result['loss_warn_money']);
        $result['loss_close_money'] = money_convert($result['loss_close_money']);
        $result['deposit_money']    = money_convert($result['deposit_money']);
        $result['avail']            = money_convert($result['avail']);
        
        return ajaxmsg('操作成功',1,$result);
    }
    /*
     * 获取配资申请历史
     */
    public function detailHistory()
    {
        $model = input('model' , '');
        $borid = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $map["uid"]       = $this->userId;
        $map["borrow_id"] = $borid;
        switch ($model) {
    		//申请延期历史记录
    		case 'renewal' :
    		    $hList=  Db::name('stock_renewal')->where($map)->order("id desc")->select()->toArray();
    		    break;
    		//追加保证金历史记录
    		case 'addmoney' :
    		    $hList = Db::name('stock_addmoney')->where($map)->order("id desc")->select()->toArray();
    		    break;
    		//扩大配资历史记录
    		case 'expend' ://'addfinancing' :
    		    $hList = Db::name('stock_addfinancing')->where($map)->order("id desc")->select()->toArray();
    		    break;
    		//提取盈利历史记录
    		case 'drawprofit' :
    		    $hList = Db::name('stock_drawprofit')->where($map)->order("id desc")->select()->toArray();
    		    break;
    		default :
    		    $hList =  [];
    		    break;
        }
        foreach ($hList as $k=>$v){
            $hList[$k]['create_date'] = getTimeFormt($v['add_time'],5) ?? '';
            $hList[$k]['create_time'] = getTimeFormt($v['add_time'],6) ?? '';
        }
        return ajaxmsg('操作成功', 1, $hList);
    }
    public function statusToArr($value)
    {
        $name = [0=>'', 1=>'成功', 2=>''];
    }
    /**
     * 扩大配资页面
     * @id 配资id
     * @deposit_money 扩大配资金额
     */
    public function expend()
    {
        $borrow_id     = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $deposit_money = input('deposit_money' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if(!$borrow_id) return ajaxmsg('参数错误',0);
        if($borrow_id < 1 || $deposit_money < 1){
            return ajaxmsg('传送数据非法，请重新申请',0);
        }
        $minfo  = MemberModel::getMemberInfoByID($this->userId);
        $amoney = $minfo['account'];
        $borrow_res = BorrowModel::getBorrowById($borrow_id,1);//返回正在使用的配资详情
        //防止超过最大最小配资额
        $gs  = explode('|', sysConfig('money_range'));
        $now = time();
        $closeTime = mktime(14,45);
        if($now >  $closeTime){
            //return ajaxmsg('为了避免计息，14:45以后，不能申请，请明天再来',0);
        }
        if($borrow_res['end_time']<time()){
            return ajaxmsg('该配资已过期不能扩大配资',0);
        }
        if($deposit_money < $gs['0']){
            $msg = '最少配资金额'.$gs['0'].'元起';
            return ajaxmsg($msg,0);
        }
        if($deposit_money % $gs['2'] != 0 ) {
            $msg = '配资金额必须是'.$gs['2'].'的整数倍';
            return ajaxmsg($msg,0);
        }
        $financing = Db::name("stock_addfinancing")->where(["borrow_id"=>$borrow_id,"uid"=>$this->userId,"status"=>0])->count();
        if($financing > 0){
            return ajaxmsg('您当前已有追加配资申请，不能再次申请',0);
        }
        $financing = Db::name("stock_addfinancing")->where(["borrow_id"=>$borrow_id,"uid"=>$this->userId,"status"=>0])->count();
        if($financing > 0){
            return ajaxmsg('您当前已有追加配资申请，不能再次申请',0);
        }
        //对应的配资是否正常
        $bsum=Db::name("stock_borrow")->where(["status"=>1,'member_id'=>$this->userId])->sum('init_money');
        if($deposit_money+$bsum > (int)$gs['1']){
            return ajaxmsg('最大配资金额不能超过'.$gs['1'].'元',0);
        }
        $binfo = BorrowModel::getBorrowById($borrow_id);
        if(!$binfo){
            return ajaxmsg('您当前申请的配资不存在，不能追加配资',0);
        }
        if($binfo['type'] == 5){
            return ajaxmsg('免息配资不能追加配资',0);
        }
        if($binfo['type'] == 4){
            return ajaxmsg('免费体验不能追加配资',0);
        }
        if($binfo['status']<>1){
            return ajaxmsg('您当前申请的配资不在操盘中，不能扩大配资',0);
        }
        //扩大配资收取的利息需要一次性付清
        // 按月配资，每月按照30天计算
        $borrow_interest = calculate_rate($binfo['multiple'],$binfo['rate'],$binfo['type'],$deposit_money,$binfo['end_time']);//利息
        $sumFee = round($deposit_money+$borrow_interest,2);//总费用
        if($sumFee > $amoney){
            return ajaxmsg("帐户金额不足，您申请追加配资所需费用为{$sumFee}元",1);
        }
        // 启动事务
        Db::startTrans();
        //冻结金额
        $money     = Db::name("money")->lock(true)->where(['mid'=>$this->userId])->find();
        $info      = '扩大配资申请，冻结金额';
        $freeze    = $money['freeze'] + $sumFee;//冻结总费用
        $account   = $money['account'] - $sumFee;
        $money_ret = MoneyModel::money_freeze($this->userId,$freeze,$account);
        // 更新资金日志表信息
        $record = new RecordModel;
        $record_ret = $record->saveData($this->userId, -abs($sumFee), $account, 33, $info);
        $data['uid'] = $this->userId;
        $data['borrow_id'] = $borrow_id;
        $data['money'] = $deposit_money;//转成单位为分
        $data['borrow_interest'] = $borrow_interest;//转成单位为分
        $data['rate'] = $binfo['rate'];
        $data['last_deposit_money'] = $binfo['deposit_money'];
        $data['last_borrow_money']  = $binfo['borrow_money'];
        $data['status'] = 0;
        $data['add_time'] = time();
        $ret = Db::name("stock_addfinancing")->insert($data);
        if($money_ret&&$record_ret&&$ret){
            Db::commit();
            return ajaxmsg("申请成功,一分钟后查看",1);
        }else{
            Db::rollback();
            return ajaxmsg("申请失败，请联系客服",0);
        }
        return ajaxmsg("申请失败，请联系客服",0);
    }

    /**
     * 增加保证金页面
     * @id 配资id
     * @$money 追加保证金金额 单位元
     */
    public function addmoney()
    {
        $id    = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $money = input('money' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if(empty($id)) return ajaxmsg('参数错误',0);
        if($id < 1 || $money < 1){
            return ajaxmsg('传送数据非法，请联系客服',0);
        }
        //标目前状态
        $binfo = BorrowModel::getBorrowById($id,1);
        if(empty($binfo)){
            return ajaxmsg('配资不在操盘中，不能申请追加保证金',0);
        }
        $detailinfo = BorrowModel::getBorrowDetail($id);
        $p_res = Db::name('stock_position')->where(['sub_id'=>$detailinfo->stock_subaccount_id,'buying'=>0])->select()->toArray();
        $sum   = 0;
        if(!empty($p_res)){
            foreach ($p_res as $k=>$v){
                $lis  = RedisUtil::getQuotationData($v['gupiao_code'],$v['market']);
                $sum += $lis['Price']*$v['stock_count'];
            }
        }
        if($detailinfo->avail+$sum>$detailinfo->loss_warn_money){
            return ajaxmsg('此配资目前不需要追加保证金',0);
        }
        
        //当前是否正在申请
        $addMoneySql   = Db::name("stock_addmoney");
        $addMoneyState = $addMoneySql->where(["borrow_id"=>$id, "uid"=>$this->userId, "status"=>0])->count();
        if($addMoneyState){
            return ajaxmsg('您已申请追加保证金申请，正在审核中，不能重复申请。',0);
        }
        $minfo = MemberModel::getMemberInfoByID($this->userId);
        //余额
        $amoney = $minfo['account'];
        if($amoney < $money){
            return ajaxmsg("余额不足，需付{$money}元",0);
        }
        //冻结金额，后台审核
        //$info = '追加保证金申请，冻结金额';
        Db::startTrans();
        $minfo_a   = Db::name("money")->lock(true)->where(['mid'=>$this->userId])->find();
        $freeze    = $minfo_a['freeze'] + $money;//冻结总费用
        $account   = $minfo_a['account'] - $money;
        $money_ret = MoneyModel::money_freeze($this->userId,$freeze,$account);
        // 更新资金日志表信息
        $record_ret = RecordModel::saveData($this->userId, -abs($money), $account, 33, $info);//7:追加保证金
        $user_name  = $minfo['name'];
        $moneyAdd['borrow_id']   = $id;
        $moneyAdd['uid']         = $this->userId;
        $moneyAdd['money']       = $money;
        $moneyAdd['status']      = 0;
        $moneyAdd['add_time']    = time();
        $moneyAdd['verify_time'] = 0;
        $retAddMoney = $addMoneySql->insert($moneyAdd);
        if($money_ret && $record_ret && $retAddMoney){
            Db::commit();
            return ajaxmsg('申请成功,一分钟后查看',1);
        }else{
            Db::rollback();
            return ajaxmsg('申请失败，请联系客服',0);
        }
        
        return ajaxmsg('申请失败，请联系客服',0);
    }

    /**
     * 提取盈利页面
     * @id 配资id
     * @$money 提取金额 单位元
     */
    public function profit()
    {
        $borrow_id = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $money     = input('money' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        //if(checkTradeTime()) return ajaxmsg('请在休市期间申请提盈！',0);
        $stockInfo = BorrowModel::getBorrowById($borrow_id);
        $sub_money = Db::name('stock_subaccount_money')->where(['stock_subaccount_id'=> $stockInfo["stock_subaccount_id"]])->find();
        dump($sub_money);exit;
        if($sub_money==null){
            return ajaxmsg('系统错误，请联系管理员',0);
        }
        if($stockInfo['status']<>1){
            return ajaxmsg('不在操盘中，不能申请提取盈利',0);
        }
        if($stockInfo['end_time']<time()){
            return ajaxmsg('配资已到期不能提取盈利',0);
        }
        //免费体验没有提取盈利
        if($stockInfo['type']==4){
            return ajaxmsg('免费体验不能提取盈利',0);
        }
        $sub_money['available_amount'] < 0 ? 0 : $sub_money['available_amount'];
        $result = BorrowModel::getBorrowDetail($borrow_id);
        if($result['available_amount']<0){
            return ajaxmsg('收益额小于零不能提取',0);
        }
        if($money < 100){
            return ajaxmsg('提取金额不能小于100',0);
        }
        if($money>$result['return_money']){
            return ajaxmsg('提取金额不能大于收益额',0);
        }
        $drawprofitInfo =  Db::name("stock_drawprofit")->field(true)->where(["borrow_id"=>$borrow_id, "uid"=>$this->userId, "status"=>0])->find();
        if(isset($drawprofitInfo['status'])&&$drawprofitInfo['status'] == 0){
            return ajaxmsg('您当前已申请过提取盈利，正在审核中，不能再次申请',0);
        }
        //客户需求一天只能提取3次盈利
        $today      = arrangeTime('day');
        $start_time = $today[0];//当天0点
        $end_time   = $today[1];//当天23：59：59
        $where      = [];
        $where[]    = ['add_time','between',[$start_time,$end_time] ];
        $where[]    = ['borrow_id','=',$borrow_id];
        $where[]    = ['uid','=',$this->userId];
        $where[]    = ['status','in',[0,1]];
        $profitCount= Db::name("stock_drawprofit")->where($where)->count();
        
        if($profitCount >= 3){
            return ajaxmsg('每天最多只能提取3次盈利',0);
        }
        if(!isset($sub_money["available_amount"])){
            return ajaxmsg('无可提现金额',0);
        }
        if($sub_money["available_amount"]<$money){
            return ajaxmsg('可提现金额不足',0);
        }
        //添加申请
        $data['borrow_id']    = $borrow_id;
        $data['uid']          = $this->userId;
        $data['borrow_money'] = $stockInfo['init_money'];
        $data['money']        = $money;
        $data['status']       = 0;
        $data['add_time']     = time();
        
        $ret = Db::name("stock_drawprofit")->insert($data);
        if($ret){
            return ajaxmsg('申请成功，请等待审核',1);
        }else{
            return ajaxmsg('申请失败',0);
        }
    }

    /**
     * 续期页面
     * @id 配资id
     * @duration 延长时间  根据配资类型分为 天 周 和月
     */
    public function renewal()
    {
        $borrow_id = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $borrow_duration = input('duration' , '');
        if(!$borrow_id) return ajaxmsg('系统错误',0);
        if($borrow_id < 1 || $borrow_duration < 1){
            return ajaxmsg('传送数据非法，请重新申请',0);
        }
        //$borrow_res = BorrowModel::getBorrowById($borrow_id,1);//返回正在使用的配资详情
        $renewal    = Db::name("stock_renewal")->where(["uid"=>$this->userId, "status"=>0,"borrow_id"=>$borrow_id])->count();
        if($renewal > 0){
            return ajaxmsg('您当前已有申请增加续期，不能再次申请',0);
        }
        $financing = Db::name("stock_addfinancing")->where(["uid"=>$this->userId, 'status'=>0, 'borrow_id'=>$borrow_id])->count();
        if($financing > 0){
            return ajaxmsg('您当前有追加配资申请，不能申请续期',0);
        }
        //对应的配资是否正常
        $binfo = BorrowModel::getBorrowById($borrow_id)->toArray();
        if(!$binfo){
            return ajaxmsg('您当前申请的配资不存在，不能增加续期',0);
        }
        //免费配资没有增加续期
        if($binfo['type'] == 4||$binfo['type'] == 5){
            return ajaxmsg('免费配资和免费体验不能增加续期',0);
        }
        if($binfo['status']<>1 && $binfo['status'] !=3){
            return ajaxmsg('你当前的配资不能申请续期',0);
        }
        //收取利息
        $peiziMoney = $binfo['borrow_money'];
        $multiple   = intval($binfo['multiple']);
        
        switch ($binfo['type']){
            case '按天配资':
                $rateSet = arrayEol(sysConfig('day_rate'),1);
                $rate = $rateSet[$multiple]/100;
                break;
            case '按周配资':
                $rateSet = arrayEol(sysConfig('week_rate'),1);
                $rate = $rateSet[$multiple]/100;
                break;
            case '按月配资':
                $rateSet = arrayEol(sysConfig('month_rate'),1);
                $rate = $rateSet[$multiple]/100;
                break;
            default:
                $rate = 0;
                break;
        }
        if(!$rate) return ajaxmsg('利息不能为0',0);
        
        //利息 * 时间 * 配资金额
        // 延期一次性计算利息
        $borrow_fee = $peiziMoney*$rate*$borrow_duration;
        //print_r($borrow_fee);return;
        $minfo      = MemberModel::getMemberInfoByID($this->userId);
        $amoney     = $minfo['account'] + $minfo['give_fee'];
        if($borrow_fee > $amoney){
            return ajaxmsg('您的余额不足，不能增加续期',0);
        }
        $infomoney = $borrow_fee;//转化为元
        $info  = "申请配资续期，冻结续期利息{$infomoney}元";
        Db::startTrans();
        $money = Db::name("money")->lock(true)->where(['mid'=>$this->userId])->find();
        $freeze     = $money['freeze']  + $borrow_fee;//冻结总费用
        $account    = $money['account'] - $borrow_fee;
        
        $money_ret  = MoneyModel::money_freeze($this->userId,$freeze,$account);
        $record_ret = RecordModel::saveData($this->userId, -abs($borrow_fee), $account, 33, $info);//23:申请配资续期

        $data['uid']             = $this->userId;
        $data['borrow_id']       = $borrow_id;
        $data['borrow_fee']      = $borrow_fee;
        $data['borrow_duration'] = $borrow_duration;
        $data['status']          = 0;
        $data['type']            = 1;
        $data['add_time']        = time();
        $data['verify_time']     = 0;
        $ret = Db::name("stock_renewal")->insert($data);
        
        if($money_ret && $record_ret && $ret){
            Db::commit();
            return ajaxmsg('申请成功，请等待审核',1);
        }else{
            Db::rollback();
            return ajaxmsg('申请失败，请联系客服',0);
        }
        return ajaxmsg('申请失败!，请联系客服',0);
    }

    /**
     * 提前终止页面
     */
    public function stop()
    {
        $minfo     = MemberModel::getMemberInfoByID($this->userId);
        $borrow_id = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if($borrow_id < 1){
            return ajaxmsg('传送数据非法，请重新申请',0);
        }
        $stopfinancing = Db::name("stock_renewal")
            ->where(["status"=>0])
            ->where(["uid"=>$this->userId])
            ->where(["borrow_id"=>$borrow_id])
            ->where(["type"=>2])
            ->count();
        if($stopfinancing > 0){
            return ajaxmsg('您已提交过提前终止申请，不能再次申请',0);
        }
        //对应的配资是否正常
        $binfo = BorrowModel::getBorrowById($borrow_id);
        if(!$binfo){
            return ajaxmsg('您当前申请的配资不存在，不能申请提前终止',0);
        }
        if($binfo['status']<>1){
            return ajaxmsg('您当前申请的配资不在操盘中，不能申请提前终止',0);
        }
        if($binfo['end_time']<time()){
            return ajaxmsg('该配资已过期，请先续期！',0);
        }
        $subPosition = BorrowModel::checkApply($borrow_id,$this->userId,$binfo['stock_subaccount_id']);
        //$subPosition = Db::name('stock_position')->where(['sub_id'=>$binfo['stock_subaccount_id']])->whereOr('stock_count','>',0)->whereOr('count','>',0)->count();
        if($subPosition['status'] === 0)  return ajaxmsg($subPosition['msg'],0);
        $interest = Db::name("stock_detail")
            ->where(["status"=>0])
            ->where(["mid"=>$this->userId])
            ->where(["borrow_id"=>$borrow_id])
            ->sum("interest");
        //按月配资提前终止要付剩余利息的百分比
        if($binfo['type']==3){
            $stop_fee=sysConfig('stop_fee');
            $interestMoney = $interest * $stop_fee;
        }else{
            $interestMoney=0;
        }
        $amoney = $minfo['account'];
        if($interestMoney > $amoney){
            $msg = "帐户全额不足，您申请终止配资所需费用为{$interestMoney}元";
            return ajaxmsg($msg,0);
        }
        Db::startTrans();
        //冻结金额
        if($interestMoney){
            $info = '终止配资申请，冻结金额';
            $money=Db::name("money")->lock(true)->where(['mid'=>$this->userId])->find();
            $freeze = $money['freeze'] + $interestMoney;//冻结总费用
            $account = $money['account'] - $interestMoney;
            $money_ret=MoneyModel::money_freeze($this->userId,$freeze,$account);
            $record = new RecordModel;
            $Record_Ret = $record->saveData($this->userId, -abs($interestMoney), $account, 33, $info);//15:终止配资
        }
        $data['uid']         = $this->userId;
        $data['borrow_id']   = $borrow_id;
        $data['borrow_fee']  = $interestMoney;
        $data['status']      = 0;
        $data['type']        = 2;
        $data['add_time']    = time();
        $data['verify_time'] = 0;
        $ret = Db::name("stock_renewal")->insert($data);
        if(isset($money_ret)&&isset($Record_Ret)){
            if($money_ret&&$Record_Ret&&$ret){
                Db::commit();
                BorrowRedis::addRenewalLists($borrow_id);//加入审核列表缓存
                return ajaxmsg('申请成功，请等待审核',1);
            }else{
                Db::rollback();
                return ajaxmsg('申请失败，请联系客服',0);
            }
        }else{
            if($ret){
                Db::commit();
                return ajaxmsg('申请成功，请等待审核',1);
            }else{
                Db::rollback();

            }
        }
        
    }

    /**
     * 渲染合同
     */
    public function contract()
    {
        $id    = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $binfo = BorrowModel::getBorrowById($id);
        $minfo = MemberModel::getMemberInfoByID($this->userId);
        //按天
        $unit="";
        if ($binfo['type']==1){
            $binfo['Interest']=$binfo['borrow_duration']*$binfo['borrow_money']*$binfo['rate']/100;
            $unit="天";
        }
        //按周
        if($binfo['type']==2){
            $binfo['Interest']=$binfo['borrow_duration']*$binfo['borrow_money']*$binfo['rate']/100;
            $unit="周";
        }
        //按月
        if ($binfo['type'] == 3){
            $binfo['Interest'] = $binfo['borrow_duration']*$binfo['borrow_money']*$binfo['rate']/100;
            $unit="月";
        }
        //免费体验和免息配资
        if ($binfo['type']==4||$binfo['type']==5){
            $binfo['Interest']=0;
            $unit="天";
        }
        $info=file_get_contents(config('data_backup_path')."contract.txt");
        //print_r($info);exit;
        $arr=array(
            "name"=>config('set_site_company_name'),//甲方：委托人
            "dizhi"=>config('web_site_address'),//甲方地址
            "borrowMoney"=>$binfo['init_money'],//委托金额
            "borrow_duration"=>$binfo['borrow_duration'],//配资周期
            "type"=>$unit,//配资类型
            "investor"=>$binfo['Interest']/$binfo['borrow_duration'],//总利息
            "user_name"=>isset($minfo['mobile'])?$minfo['mobile']:"138********",//乙方用户名
            "real_name"=>isset($minfo['name'])?$minfo['name']:"***",//
            "idcard"=>isset($minfo['id_card'])?$minfo['id_card']:"******************",//
            "WEB_URL"=>http().$_SERVER["HTTP_HOST"],//
            "web_name"=>config('web_site_title'),//
            "rate"=>$binfo['rate'],//
            "deposit_money"=>$binfo['deposit_money'],//
            "add_time"=>date('Y-m-d',$binfo['verify_time']),//
            "end_time"=>date("Y-m-d",$binfo['end_time']),//
        );
        $arr['user_name']=isset($minfo['mobile'])?$minfo['mobile']:"138********";
        $arr['real_name']=isset($minfo['name'])?$minfo['name']:"***";
        $arr['idcard']=isset($minfo['id_card'])?$minfo['id_card']:"******************";
        foreach ($arr as $k =>$v){
            $info=str_replace("[".$k."]",$v,$info);
        }

        return ajaxmsg('合同',1,$info);
    }
}