<?php
declare (strict_types = 1);

namespace app\apicom\controller;
use app\apicom\model\StockSubAccount;
use app\apicom\model\Renewal;
use app\apicom\model\Borrow as BorrowModel;
use app\apicom\model\Record as RecordModel;
use app\apicom\model\SubAccount as SubAccountModel;
use app\apicom\model\Addfinancing as AddfinancingModel;
use app\apicom\model\Addmoney as AddmoneyModel;
use app\apicom\model\Money;
use app\apicom\model\Member;
use app\apicom\model\Grid;
use app\apicom\model\Position;

use think\facade\Db;
/*
 * 定时任务
 */
class Crond extends BaseController
{
    
    public function autoRenewal()
    {
        $where = ['r.renewal'=> 1];
        $where = ['b.status' => 1];
        $list  = BorrowModel::getEnd($where)->toArray();
        return ajaxmsg('=已到期的配资=',1,$list);
        //判断获取的数组是否有效
        if(!isset($list['data']) || empty($list['data'])) return false;
        //开始分别计算出续期费用
        foreach ($list['data'] as $key => $val){
            $peiziMoney = $val['borrow_money'];
            $multiple   = intval($val['multiple']);
            switch ($val['type']){
                case '按天配资':
                    $type = 1;
                    $rateSet = arrayEol(sysConfig('day_rate'),1);
                    $rate = $rateSet[$multiple]/100;
                    break;
                case '按周配资':
                    $type = 2;
                    $rateSet = arrayEol(sysConfig('week_rate'),1);
                    $rate = $rateSet[$multiple]/100;
                    break;
                case '按月配资':
                    $type = 3;
                    $rateSet = arrayEol(sysConfig('month_rate'),1);
                    $rate = $rateSet[$multiple]/100;
                    break;
                default:
                    $type = 0;
                    $rate = 0;
                    break;
            }
            if($rate > 0){
                // 延期一次性计算利息 计算方式：利息 * 时间 * 配资金额
                $borrow_fee = $peiziMoney*$rate*1;//数字1为续期的周期，天=>1天；周=>1周；月=>1月
                $msg = "配资[".$val['sub_account']."]自动续期，扣除续期利息{$borrow_fee}元";
                $endTime = Renewal::getAddTime($type,$val['end_time'],1);//数字1为续期的周期，天=>1天；周=>1周；月=>1月
                Db::startTrans();
                $minfo = Db::name("money")->lock(true)->where('mid',$val['member_id'])->find();
                if(!$minfo){
                    Db::rollback();
                    break;
                }
                $mmoney['account'] = $minfo['account'] - $borrow_fee;
                //如果余额小于0，说明账户余额不足，就此停止
                if($mmoney['account'] < 0) break;
                $ret_m = Money::money_up($val['member_id'], $mmoney);
                $ret_b = Db::name("stock_borrow")->where("id",$val['id'])->update(['end_time' => $endTime]);
                $ret_r = RecordModel::saveData($val['member_id'], $borrow_fee, $minfo['account'], 80, $msg);
                
                if($ret_m && $ret_b){
                    Db::commit();
                }else{
                    Db::rollback();
                }
            }
            
            print_r($endTime);echo "\n";
        }
        //return ajaxmsg('=已到期的配资=',1,$borrow_fee);
    }
    /*自动审核配资*/
    public function autoborrow($id = null){
        // 获取数据
        $data_list = BorrowModel::getList();
        //print_r($data_list[0]->toArray());exit;
        if(empty($data_list) || !isset($data_list[0])){
            exit('没有新的配资申请！');
        }
        
        foreach ($data_list as $k =>$v){
            $id         = intval($v['id']);
            $info       = BorrowModel::getEditBorrow($id);//获取配资信息
            $agent      = isset($info['agent'])?$info['agent']:"无代理商";
            $init_money = $info['init_money'];
            $sub_arr    = SubAccountModel::getSelaccountList(0, $init_money);
            if(empty($sub_arr)){
                exit('没有空余的子账户，请到管理后台新增子账户！');
            }
            $lack='';
            if($sub_arr['lack']!=''){
                $lack=$sub_arr['lack'];
                unset($sub_arr['lack']);
            }else{
                unset($sub_arr['lack']);
            }
            foreach ($sub_arr as $i =>$s){
                $subid      = $i;
                $subaccount = $sub_arr[$i];
                break;
            }
            //print_r($subaccount);exit;
            /*组合数据*/
            $data['id']                    = $info['id'];
            $data['member_id']             = $info['member_id'];
            $data['borrow_duration']       = $info['borrow_duration'];
            $data['type']                  = $info['type'];
            $data['v_status']              = 1;
            $data['stock_subaccount_id_r'] = $subid;
            $data['contents']              = '';
            $data['init_money']            = $info['init_money'];
            $data['deposit_money']         = $info['deposit_money'];
            $data['borrow_money']          = $info['borrow_money'];
            $data['borrow_interest']       = $info['borrow_interest'];
            $data['offset_fee']            = $info['offset_fee'];
            $data['loss_warn']             = $info['loss_warn'];
            $data['loss_close']            = $info['loss_close'];
            $data['position']              = $info['position'];
            $data['prohibit_open']         = 1;
            $data['prohibit_close']        = 1;
            $data['renewal']               = 1;
            $data['autoclose']             = 1;
            $data['commission_scale']      = 3.00;
            $data['min_commission']        = 5.00;
            $data['rate_scale']            = 0.00;
            $data['profit_share_scale']    = 0.00;
            $data['stock_subaccount_id']   = $subid;
            $data['sub_account']           = $subaccount;
            $data['status']                = 1;
            
            //webtext防止重复操作
			$borrret = Db::name('stock_borrow')->where(['id' => $data['id']])->value('status');
			if ($borrret != -1) exit('配资已经被审核');
			//print_r($data);exit;
            $BorrowModel = new BorrowModel();
            $result      = $BorrowModel->saveBorrow($data);
            //print_r($result);exit;
            if($result['status']==1){
                //根据佣金比例分配佣金 用户id 配资id 配资管理费
                if($data['borrow_interest']){
					//webtext 佣金上面已经分配
                    $res_agent = $BorrowModel->agentToRateMoney($data['member_id'],$data['id'],$data['borrow_interest']/100);
                }
                //申请配资审核通过-短信通知
                $browid = $data['id'];
                $info   = BorrowModel::getEditBorrow($browid);//获取配资信息
                exit($result['msg']);
            }elseif($result['status']==2){
                exit($result['msg']);
            }else{
                exit($result['msg']);
            }
        }
 
    }
    
    /*自动审核扩大配资*/
	public function autoexpend(){
		$data_list= AddfinancingModel::getAddfinancing();
        foreach ($data_list as $k =>$v){
            $id=intval($v['id']);
			if(!empty($id)){$info = AddfinancingModel::getAddfinancingById($id);}
			if(!$info){continue;}
			//print_r($info);exit;
			$Addf_Model=new AddfinancingModel();
            $ret=$Addf_Model->saveAddfinancing($id,1,$info);
            //配资类型  1:按天配资 2:按周配资 3:按月配资 4:试用配资 5:免息配资
			$data=[];
			switch ($info['type']){
				case 1:
					$config  = day_config();
					$data['multiple'] = $info['multiple']; // 倍率
					$data['deposit_money'] = $info['money']+$info['deposit_money'];//扩大配资后的保证金
					$loss_warn =  $config['day_loss'][0]; // 预警线
					$loss_close = $config['day_loss'][1];// 止损线
					$data['borrow_money']=$info['money']*$info['multiple'] + $info['borrow_money'];//扩大后的总配资金额
					$data['loss_warn']  = ($data['deposit_money']+$data['borrow_money'])*($loss_warn/100);//扩大后预警线
					$data['loss_close'] = ($data['deposit_money']+$data['borrow_money'])*($loss_close/100);//扩大后平仓线
					$data['rate']= $config['day_rate'][$data['multiple']]; //系统天利率
					$data['borrow_interest']= BorrowModel::interest($info['type'],$data['rate'],$data['borrow_money'],$info['borrow_duration']); //扩大后的管理费
					break;
				case 2:
					$config  = week_config();
					$data['multiple'] = $info['multiple']; // 倍率
					$data['deposit_money'] = $info['money']+$info['deposit_money'];//扩大配资后的保证金
					$loss_warn  =  $config['week_loss'][0]; // 预警线
					$loss_close  = $config['week_loss'][1];// 止损线
					$data['borrow_money']=$info['money']*$info['multiple'] + $info['borrow_money'];//扩大后的总配资金额
					$data['loss_warn']  = ($data['deposit_money']+$data['borrow_money'])*($loss_warn/100);//扩大后预警线
					$data['loss_close'] = ($data['deposit_money']+$data['borrow_money'])*($loss_close/100);//扩大后平仓线
					$data['rate'] = $config['week_rate'][$data['multiple']];//系统天利率
					$data['borrow_interest']= BorrowModel::interest($info['type'],$data['rate'],$data['borrow_money'],$info['borrow_duration']); //扩大后的管理费
					break;
				case 3:
					$config  = month_config();
					$data['multiple'] = $info['multiple']; // 倍率
					$data['deposit_money'] = $info['money']+$info['deposit_money'];//扩大配资后的保证金
					$loss_warn  =  $config['month_loss'][0]; // 预警线
					$loss_close =  $config['month_loss'][1];// 止损线
					$data['borrow_money']=$info['money']*$info['multiple'] + $info['borrow_money'];//扩大后的总配资金额
					$data['loss_warn']  = ($data['deposit_money']+$data['borrow_money'])*($loss_warn/100);//扩大后预警线
					$data['loss_close'] = ($data['deposit_money']+$data['borrow_money'])*($loss_close/100);//扩大后平仓线
					$data['rate'] = $config['month_rate'][$data['multiple']];//系统天利率
					$data['borrow_interest']= BorrowModel::interest($info['type'],$data['rate'],$data['borrow_money'],$info['borrow_duration']); //扩大后的管理费
					break;
				default:
					//$this->error('类型出错，请重新输入！');
			}

			$result =  Db::name('stock_borrow')->where(['id'=>$info['borrow_id']])->update($data);
			//根据佣金比例分配佣金 用户id 配资id 配资管理费
			if($result){
				if($status){
					$BorrowModel = new BorrowModel();
					if($data['borrow_interest'])  $res_agent = $BorrowModel->agentToRateMoney($info['uid'],$info['id'],$info['borrow_interest']/100,2);
					//$this->success($ret['msg'],url('addf_list'));
				}
			}
        }
	}
	
	/*追加保证金审核*/
    public function autoaddmoney(){
        $data_list= AddmoneyModel::getAddmoney();
        foreach ($data_list as $k =>$v){
			$id=intval($v['id']);
			if(!empty($id)){$info = AddmoneyModel::getAddmoneyById($id);}
			if(!$info) {continue;}
			//print_r($info);exit;
            $Addf_Model=new AddmoneyModel();
            $ret=$Addf_Model->saveAddmoney($id,1,$info);
            if($ret['status']==='1'){
                exit($ret['msg']);
            }elseif($ret['status']==='0'){
                exit($ret['msg']);
            }
		}
    }
}

?>