<?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\SubAccountMoney;
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;

use util\BorrowRedis;

class close extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('check')->setDescription('自动结算配资');
    }

    protected function execute(Input $input, Output $output)
    {
        // 启动协程
    	swoole_timer_tick(5000, function (){
		    //自动审核终止配资
		    $this->checkBorrow();
		    
		});
		\Swoole\Event::wait();
    }
    
    /*自动审核终止操盘*/
    protected function checkBorrow(){
        // 获取数据
        $data_list = Db::name('stock_renewal')->where(['type'=>2,'status'=>0])->order('id desc')->select();
        //$data_list = BorrowRedis::getRenewalLists();//暂未完成测试
        //print_r($data_list);return;
        if(empty($data_list)) return;
        foreach ($data_list as $k => $v){
            $info  = !empty($v['id']) ? Renewal::getStopById($v['id']) : 0;
            $check = BorrowModel::checkApply($info['borrow_id'],$info['uid'],$info['stock_subaccount_id']);
            if(!isset($check['status']) && $check['status'] !== 1){ //检查完毕是否可以清算
                $this->output->writeln($check['msg']);
                break;
            }
            $submoney_info = SubaccountMoney::getMoneyByID($info['stock_subaccount_id']);
            if($submoney_info['freeze_amount'] > 0.1){ //检查该子账户是否还有资金未解冻
                $this->output->writeln("该子账户下还有 " . $submoney_info['freeze_amount'] . " 资金未解冻");
                break;
            }
            $surplus_money = $submoney_info['avail'];//返回的可用余额
            $addmoney      = $submoney_info['stock_addmoney'];//累计追加保证金
            $drawprofit    = $submoney_info['stock_drawprofit'];//累计提取盈利
            $status = 1;//改变配资状态
            $result = Renewal::saveStop($v['id'],$status,$info,$surplus_money,$addmoney,$drawprofit);
            //去结算
            if($result['status'] == 1){
                //申请配资审核通过-短信通知
                $this->output->writeln($result['msg']);
            }
        }
    }
    
}
