<?php
declare (strict_types = 1);

namespace app\command;

use app\apicom\model\Money as MoneyModel;
use app\apicom\model\Borrow as BorrowModel;
use app\apicom\model\Addfinancing;
use app\apicom\model\SubAccount;
use app\apicom\model\Addmoney;
use app\apicom\model\Renewal;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class check extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('check')->setDescription('自动审核检查');
    }

    protected function execute(Input $input, Output $output)
    {
        // 启动协程
    	swoole_timer_tick(1000, function (){
		    //自动审核申请配资
		    $this->checkBorrow();
		    //自动审核扩大配资
		    $this->checkExpend();
		    //自动审核追加保证金
		    $this->checkAddmoney();
		    //自动审核延期申请
		    $this->checkRenewal();
		});
		\Swoole\Event::wait();
    }
    
    /*自动审核配资*/
    protected function checkBorrow(){
        // 获取数据
        $BorrowModel = new BorrowModel;
        $data_list   = $BorrowModel->getList();
        if(empty($data_list) || !isset($data_list[0])) return;
        foreach ($data_list as $k => $v){
            $info  = $BorrowModel->getEditBorrow($v['id']);//获取配资信息
            //print_r($info);return;
            //$agent      = isset($info['agent']) ? $info['agent'] : "无代理商";
            $subid = Db::name('stock_subaccount')->where(['uid' => null,'status' => 0])->value('id');
            //print_r($subid);return;
            //if(!$subid) $this->output->writeln('没有空余的子账户，请到管理后台新增子账户！');
            /*组合数据*/
            $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['status']                = 1;
            //webtext防止重复操作
			$borrret = Db::name('stock_borrow')->where(['id' => $data['id']])->value('status');
			if ($borrret != -1) $this->output->writeln('配资已经被审核');
            $result = $BorrowModel->saveBorrow($data);
            $this->output->writeln($result['msg']);
            if($result['status'] == 1){
                // 检测是否满足首次配资赠送管理费活动
                $counts = Db::name('stock_borrow')->where('member_id', $data['member_id'])->count();
                if(sysConfig('give_open') == 1 && $counts == 1) MoneyModel::setGiveFee($data['member_id'], 'give_firstborrow', 0);
                //根据佣金比例分配佣金 用户id 配资id 配资管理费
                if($data['borrow_interest']){
                    $res_agent = $BorrowModel->agentToRateMoney($data['member_id'],$data['id'],$data['borrow_interest']);
                }
                //申请配资审核通过-短信通知
                //$browid = $data['id'];
                //$info   = $BorrowModel->getEditBorrow($browid);//获取配资信息
                //$this->output->writeln($result['msg']);
            }
        }
    }
    /*自动审核扩大配资*/
	protected function checkExpend(){
		$BorrowModel  = new BorrowModel;
		$Addfinancing = new Addfinancing;
		$data_list    = $Addfinancing->getAddfinancing();
        foreach ($data_list as $k =>$v){
            $id   = intval($v['id']);
			$info = !empty($id) ? $Addfinancing->getAddfinancingById($id) : 0;
			if(!$info) continue;
            $ret  = $Addfinancing->saveAddfinancing($id,1,$info);
            if($ret['status'] != 1) return false;
            //配资类型  1:按天配资 2:按周配资 3:按月配资 4:试用配资 5:免息配资
			$data=[];
			switch ($info['type']){
				case 1:
					$config     = day_config();
					$loss_warn  = $config['day_loss'][0]; // 预警线
					$loss_close = $config['day_loss'][1]; // 止损线
					$data['multiple']       = $info['multiple']; // 倍率
					$data['deposit_money']  = $info['money']+$info['deposit_money'];//扩大配资后的保证金
					$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();
					$loss_warn  = $config['week_loss'][0]; // 预警线
					$loss_close = $config['week_loss'][1]; // 止损线
					$data['multiple']       = $info['multiple']; // 倍率
					$data['deposit_money']  = $info['money']+$info['deposit_money'];//扩大配资后的保证金
					$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();
					$loss_warn  = $config['month_loss'][0]; // 预警线
					$loss_close = $config['month_loss'][1]; // 止损线
					$data['multiple']       = $info['multiple'];// 倍率
					$data['deposit_money']  = $info['money']+$info['deposit_money'];//扩大配资后的保证金
					$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:
			}
            
			$result =  Db::name('stock_borrow')->where(['id'=>$info['borrow_id']])->update($data);
			//根据佣金比例分配佣金 用户id 配资id 配资管理费
			if($result){
				if($data['borrow_interest'])  $res_agent = $BorrowModel->agentToRateMoney($info['uid'],$info['id'],$info['borrow_interest'],2);
			}
        }
	}
	/*追加保证金审核*/
    protected function checkAddmoney(){
        $Addmoney = new Addmoney;
        $list     = $Addmoney->getAddmoney();
        foreach ($list as $k =>$v){
			$id=intval($v['id']);
			$info = !empty($id) ? $Addmoney->getAddmoneyById($id) : 0;
			if(!$info) continue;
            $ret = $Addmoney->saveAddmoney($id,1,$info);
            if($ret['status']==='1'){
                //$this->output->writeln($ret['msg']);
            }elseif($ret['status']==='0'){
                //$this->output->writeln($ret['msg']);
            }
		}
    }
    /*操盘延期申请审核*/
    protected function checkRenewal(){
        $Renewal = new Renewal;
        $list    = $Renewal->getRenewal();
        foreach ($list as $k =>$v){
			$id=intval($v['id']);
			$info = !empty($id) ? $Renewal->getRenewalById($id) : 0;
			if(!$info) continue;
			//print_r($info);exit;
            $ret = $Renewal->saveRenewal($id,1,$info);
            if($ret['status']==='1'){
                //$this->output->writeln($ret['msg']);
            }elseif($ret['status']==='0'){
                //$this->output->writeln($ret['msg']);
            }
		}
    }
}
