<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\apicom\model\StockAccount;
use app\apicom\model\Stock as StockModel;
use app\apicom\model\Borrow as BorrowModel;
use app\apicom\model\SubAccount;
use app\apicom\model\SubAccountMoney;
use app\apicom\model\Renewal;

use app\admin\model\StockList;


use think\facade\Db;
use util\RedisUtil;
class Risk extends AdminBase
{
    public function index()
    {
        return '您好！这是一个[Risk]示例应用';
    }
    /******************************************************************************************************************************/
    /* 
     * 获取证券公司列表
     */
    public function getCompanys()
    {
        $lid    = input('lid', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $name   = input('name','');
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = 'create_time desc';
        $where  = [];
        if(!empty($name))   $where[] = ['name' ,'=', $name];
        if(!empty($mobile)) $where[] = ['mobile' ,'=', $mobile];
        // 数据列表
        $data_list = StockAccount::where($where)
            ->order($order)
            ->paginate($offset, false, ['query' => request()->param()])
            ->each( function($item, $key){});
        if(isset($data_list)){
            return ajaxmsg('操作成功',200,$data_list);
        }
        return ajaxmsg('操作失败',0);
    }
    /* 
     * 新增/修改证券公司信息
     */
    public function editCompany()
    {
        $data = input();
        if(!isset($data['id'])){
            $data['create_time'] = date('Y-m-d H:i:s',time());
        }
        $data['update_time'] = date('Y-m-d H:i:s',time());
        // 验证数据
		$result = $this->validate($data, 'Risk.create');
		if ($result !== true) return ajaxmsg($result,0);
        if(Db::name('stock_account')->strict(false)->save($data)){
            return ajaxmsg('操作成功',200);
        }
        return ajaxmsg('操作失败',0);
    }
    /******************************************************************************************************************************/
    /*
     * 初始化股票列表
     */
    public function intStockList()
    {
        $data = Eastmoney_HSJ_List();
        if(empty($data)) $data = apiStockList();
        if(empty($data)) return ajaxmsg('无法获取到数据',0);
        $res = StockList::intStockList($data['items']);
        if(!$res) return ajaxmsg('初始化失败',0);
        return ajaxmsg('操作成功',200);
    }
    /*
     * 获取股票列表
     */
    public function getStockList()
    {
        $name   = input('name','');
        $code   = input('code','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = 'id asc';
        $where = [];
        if(!empty($name)) $where[] = ['title','like', "%{$name}%"];
        if(!empty($code)) $where[] = ['code' ,'like', "%{$code}%"];
    	$data_list = StockModel::getAll($where,$order,$offset);
    	if(!$data_list) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$data_list);
    }
    /*
     * 删除指定股票
     */
    public function delStock()
    {
        $id = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if(empty($id)) return ajaxmsg('缺少ID参数',0);
    	$res = Db::name('stock_list')->delete($id);
    	if(!$res) return ajaxmsg('操作失败',0);
        return ajaxmsg('操作成功',200);
    }
    /*
     * 禁用指定股票
     */
    public function doDisable()
    {
        $id     = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $status = input('status','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if(empty($id)) return ajaxmsg('缺少ID参数',0);
    	$res = Db::name('stock_list')->where('id',$id)->update(['status'=>$status]);
    	if(!$res) return ajaxmsg('操作失败',0);
        return ajaxmsg('操作成功',200);
    }
    /*
     * 新增/修改股票
     */
    public function editStock()
    {
        $data = input();
        $data['market'] = isset($data['market']) ? strtoupper($data['market']) : '';
        $data['pinyin'] = isset($data['pinyin']) ? strtoupper($data['pinyin']) : '';
        // 验证数据
		$result = $this->validate($data, 'Stock.saveStock');
        if ($result !== true) return ajaxmsg($result,0);
        if(empty($data['id'])) {
            $data['add_time']  = time();
        }else{
            $data['edit_time'] = time(); 
        }
    	$res = Db::name('stock_list')->save($data);
    	if(!$res) return ajaxmsg('操作失败',0);
        return ajaxmsg('操作成功',200);
    }
    /******************************************************************************************************************************/
    /*
     * 获取配资列表
     */
    public function getBorrowList()
    {
        $name    = input('name', '');
        $mobile  = input('mobile','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $orderid = input('orderid','',['trim', FILTER_SANITIZE_NUMBER_INT]);
        $status  = input('status','');
        $offset  = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $where   = [];
        $order   = 'b.create_time desc';
        $stat_n  = ['全部'=>'','待审核'=>-1,'未通过'=>0,'使用中'=>1,'已结束'=>2,'已逾期'=>3];
        if($status && isset($stat_n[$status]) && $stat_n[$status]!=='') $where[] = ['b.status','=',$stat_n[$status]];
        if(!empty($name))   $where[] = ['member.name'  ,'=', $name];
        if(!empty($mobile)) $where[] = ['member.mobile','=', $mobile];
    	if(!empty($orderid))$where[] = ['b.order_id','=', $orderid];
    	$data_list = BorrowModel::getListAll($where,$order,$offset);
    	if(!$data_list) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$data_list);
    }
    /*
     * 获取子账户列表
     */
    public function getSubList()
    {
        $subcode = input('subcode','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $status  = input('status' ,'');
        $offset  = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order   = 'id asc';
        $where   = [];
        if(!empty($subcode)) $where[] = ['sub_account','=', $subcode];
        $data_list = SubAccount::getAllList($where,$order,$offset);
        if(!$data_list) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$data_list);
    }
    /*
     * 修改子账户列表
     */
    public function editSubList()
    {
        $data  = input();
        $count = $data['nums'] > 100 ? 100 : $data['nums'];
        $subAccount = Db::name('stock_subaccount')->order('id desc')->value('sub_account') ?? 60753103;
        for ($i = 0 ; $i < $count; $i ++) {
            $datas[] = [
                'uid'         => null,
                'sub_account' => $subAccount+$i+1,
                'sub_pwd'     => '123456',
                'agent_id'    => 1,
                'account_id'  => $data['account_id'][0], 
                'create_time' => time(),
            ];
        }
        //print_r($datas);exit;
        Db::startTrans();
    	$sub = Db::name('stock_subaccount')->insertAll($datas);
    	if($sub){
    	    Db::commit();
		    return ajaxmsg('操作成功',200);
		}
		Db::rollback();
		return ajaxmsg('操作失败',0);
    }
    /* 
     * 通过账户号码获取子账户完整数据
     */
    public function getSubInfo()
    {
        $sub = input('sub','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if(empty($sub)) return ajaxmsg('缺少SUBID参数',0);
        $where = ['s.sub_account' => $sub];
        $data  = SubAccount::getSubInfo($where);
        if(!$data) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$data);
    }
    /* 
     * 修改子账号数据 并一起修改配资列表的对应设置
     */
    public function editSubInfo()
    {
        $data = input();
        if(empty($data['id'])) return ajaxmsg('缺少ID参数',0);
        $risk = [
            'loss_warn'      => $data['loss_warn']  ?? '50.00',
            'loss_close'     => $data['loss_close'] ?? '20.00',
            'position'       => $data['position']   ?? 100, 
            'prohibit_open'  => $data['prohibit_open'],
            'prohibit_close' => $data['prohibit_close'],
            'prohibit_back'  => $data['prohibit_back'],
            'renewal'        => $data['renewal'],
            'autoclose'      => $data['autoclose'],
            'update_time'    => time(),
        ];
        $borrow = [
            'loss_warn'  => $data['loss_warn']  ?? '50.00',
            'loss_close' => $data['loss_close'] ?? '20.00',
            'position'   => $data['position']   ?? 100, 
        ];
        Db::startTrans();
    	$res = Db::name('stock_subaccount_risk')->where(['stock_subaccount_id' => $data['id']])->update($risk);
    	$bor = Db::name('stock_borrow')->where(['stock_subaccount_id' => $data['id']])->update($borrow);
    	if($res && $bor){
    	    Db::commit();
		    return ajaxmsg('操作成功',200);
		}
		Db::rollback();
		return ajaxmsg('操作失败',0);
    }
    /*
     * 删除子账户
     */
    public function delSubac()
    {
        $id  = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $sub = SubAccount::where('id', $id)->find();
        if(empty($sub)) return ajaxmsg('查询失败',0);
		$bor = Db::name('stock_borrow')->where(['stock_subaccount_id' => $sub['id']])->where('status','in',[1,3])->find();
		if ($bor) {
			return ajaxmsg('操作失败,该子账户下有配资未清空',0);
		}
		$result = SubAccount::where('id', $id)->delete();
        if ($result) {
            return ajaxmsg('操作成功',200);
        } else {
            return ajaxmsg('操作失败',0);
        }
    }
    /******************************************************************************************************************************/
    /*
     * 获取配资审核列表
     */
    public function getAuditList()
    {
        $path   = input('path','');
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = 'id desc';
        $where  = [];
        if(!$path) return ajaxmsg('缺少参数',0);
        $data_list = BorrowModel::getAuditAll($path,$where,$order,$offset);
        if(!$data_list) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$data_list);
    }
    /*
     * 人工审核提前终止操盘
     */
    public function editStopBorr()
    {
        $id     = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $status = input('status','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if(!$id || $status == '') return ajaxmsg('缺少参数',0);
        $info = !empty($id) ? Renewal::getStopById($id) : 0;
        if(!$info) return ajaxmsg('没有申请记录',0);
        //*******************下面操作终止操盘审核*******************//
        if($status == 1){
            //检测配资申请和持仓情况
            $check_res = BorrowModel::checkApply($info['borrow_id'],$info['uid'],$info['stock_subaccount_id']);
            if($check_res['status'] === 0) return ajaxmsg($check_res['msg'],0);
            //检测子账户资金情况
            $submoney_info = SubaccountMoney::getMoneyByID($info['stock_subaccount_id']);
            if($submoney_info['freeze_amount'] > 0.1){
                return ajaxmsg('该子账户还有资金未解冻，请等资金解冻后再审核',0);
            }
            
            $surplus_money = $submoney_info['avail'];//返回的可用余额
            $addmoney      = $submoney_info['stock_addmoney'];//累计追加保证金
            $drawprofit    = $submoney_info['stock_drawprofit'];//累计提取盈利

            $ret = Renewal::saveStop($id,$status,$info,$surplus_money,$addmoney,$drawprofit);
        }
        if($ret['status'] == 1){
            return ajaxmsg("审核成功！",200);
        }else{
            return ajaxmsg("审核失败！",0);
        }
    }
    /*
     * 修正子账户冻结金额和可用于我等信息
     */
    public function editBorrowAmount()
    {
        $data   = input();
        $status = input('status','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        
        if(empty($data['id'])) return ajaxmsg('缺少ID参数',0);
        //$status = 1 为解冻到可用余额，$status = 0 为直接抹除冻结资金
        $risk = [
            'freeze_amount' => '0.00',
            'avail'         => $status == 1 ? $data['avail'] + $data['freeze_amount'] : $data['avail'],
        ];
        //print_r($risk);exit;
        Db::startTrans();
    	$res = Db::name('stock_subaccount_money')->where(['id' => $data['id']])->update($risk);
    	if($res){
    	    Db::commit();
		    return ajaxmsg('操作成功',200);
		}
		Db::rollback();
		return ajaxmsg('操作失败',0);
    }
    /*
     * 查询配资子账户交易明细
     */
    public function getSubRecord()
    {
        $name    = input('name', '');
        $mobile  = input('mobile','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $account = input('account','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset  = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order   = 'r.create_time desc';
        if(!empty($name))    $where[] = ['m.name' ,'=', $name];
        if(!empty($mobile))  $where[] = ['m.mobile' ,'=', $mobile];
        if(!empty($account)) $where[] = ['s.sub_account ' ,'=', $account];
        $where[] = ['s.status' ,'=', 1];
        $data_list = SubAccount::getSubRecordList($where,$order,$offset);
        if(!$data_list) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$data_list);
    }
}