<?php
declare (strict_types = 1);

namespace app\apicom\controller;
use app\apicom\model\StockSubAccount;
use app\apicom\model\StockPosition;
use app\apicom\model\StockDeliveryOrder as Delivery;
use app\apicom\model\SubAccountMoney;
use app\apicom\model\TrustIpo;
use think\facade\Db;
use util\RedisUtil;
class Ipo extends BaseController
{
    /*
     * 获取购买资格
     */
    public function getIpolimit()
    {
        $subid = input('subid', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);//子账户ID
		if(!$subid) return ajaxmsg('参数不正确',0);
		$res = StockSubAccount::getAccountById($subid);
		if (!$res) return ajaxmsg('不存在的子账号',0);
		if (empty($res['account_id'])) return ajaxmsg('证券公司不存在', 0);
        //print_r($subid);exit;
        $sh_data  = StockPosition::where(['sub_id' => $subid,'buying' => 0,'market'=>'SH'])->order('id desc')->select();
        $sh_value = self::getValues($subid,$sh_data,'SH') ?: 0;
        
        $sz_data  = StockPosition::where(['sub_id' => $subid,'buying' => 0,'market'=>'SZ'])->order('id desc')->select();
        $sz_value = self::getValues($subid,$sz_data,'SZ') ?: 0;
        
        $bj_data  = StockPosition::where(['sub_id' => $subid,'buying' => 0,'market'=>'BJ'])->order('id desc')->select();
        $bj_value = self::getValues($subid,$bj_data,'BJ') ?: 0;
        
        $kc_data  = StockPosition::where(['sub_id' => $subid,'buying' => 0,'market'=>'KC'])->order('id desc')->select();
        $kc_value = self::getValues($subid,$kc_data,'KC') ?: 0;
        
        $json = [
            'SH' => $sh_value,
            'SZ' => $sz_value,
            'BJ' => $bj_value,
            'KC' => $kc_value,
        ];
		return ajaxmsg('操作成功',1,$json);
    }
    /*
     * 提交申购申请
     */
    public function applyIpoData()
    {
        $data  = [
            "subid"  => input('subid','', ['trim', FILTER_SANITIZE_NUMBER_INT]),//子账户ID,
    	    "code"   => input('code' ,'', ['trim', FILTER_SANITIZE_NUMBER_INT]),//股票代码
    	    "name"   => input('name' ,''),//股票名称
    	    "market" => input('market',''),//交易所代码
    	    "count"  => input('count', 0, ['trim', FILTER_SANITIZE_NUMBER_INT]),//购买数量
    	    "price"  => input('price', 0, ['trim']),
        ];
        if(!$data['subid'])  return ajaxmsg('参数不正确',0);
        $res = StockSubAccount::getAccountById($data['subid']);
		if (!$res) return ajaxmsg('不存在的子账号',0);
		//验证数据
        $result = $this->validate($data, 'Ipo.creat');
        if(!$result) return ajaxmsg($result,0);
        $tradeipo  = TrustIpo::execute($data);
        if(isset($tradeipo['status'])&&!$tradeipo['status']) return ajaxmsg($tradeipo['message'],0);
        $trade_money = $tradeipo['trade_money'];
		$moneyinfo   = $tradeipo['moneyinfo'];
		$price       = $tradeipo['price'];
        //计算佣金
		$commission  = commission($trade_money,$moneyinfo['commission_scale'],$moneyinfo['min_commission']);
		//计算过户费
		$transfer    = transfer($trade_money);
		//写入子账户资金变化表
		try {
		    Db::startTrans();
    		$effectMoney = $trade_money + $commission + $transfer;
    		/*(子账户ID, 金额*100, 买卖方向[1：买入 2：卖出], 盈亏金额, 实盘相关, 股票代码)*/
    		$ret  = SubAccountMoney::upMoneyLog($data['subid'], $effectMoney, 91, 0, 0, $data['code']);
    		if (!$ret){
    			Db::rollback();
    			return ajaxmsg('新股申购失败!',0);
    		}
    		$Trust_no  = mt_rand(101010, 999999) . substr(strval(time()), 1);
    		//添加到委托表
    		$Trust_res = TrustIpo::add_trust_ipo($data, $price, $Trust_no);
    		if(!$Trust_res){
    			Db::rollback();
    			return ajaxmsg('申购失败!',0);
    		}
		} catch ( \Exception $e ) {
		    Db::rollback();
			return ajaxmsg('新股申购失败!',0);
		}
		Db::commit();
		return ajaxmsg('新股申购已提交',1);
    }
    /*
     * 市值计算（用于新股申购资格判断）
     */
    public function getValues($subid,$data,$market)
    {
        if(!$data) return false;
        $value = 0;
        $todayCount = 0;
        foreach ($data as $k => $item){
            //查询当天交易的数量 T+1 交易
            $todayCount = Delivery::getDeliveryOrder($subid,$item["gupiao_code"],2);
            //查询股票最新行情
            $Qdata = RedisUtil::getQuotationData($item["gupiao_code"],$item["market"],true);
            //市值 = 当前价格*数量
            $value += round($Qdata['Price']*($item['stock_count']-$todayCount),2);
        }
        //查看申购表中数量
        $ipo_res  = TrustIpo::where(['sub_id'=>$subid,'market'=>$market,'status'=>'申购中'])->sum('trust_count') ?: 0;
        return intval($value/10) - intval($ipo_res);
    }
    /*
     * 获取申购记录
     */
    public function getIpoRecord()
    {
        $sub_id    = input('sub_id', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $action    = input('action', '');
		//$startDate = input('start_date', '');
		//$endDate   = input('end_date', '');
		$page      = input('page', 1, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset    = ($page-1) * 20;
        if(!$sub_id) return ajaxmsg('子账号不能为空',0);
		$res       = StockSubAccount::getAccountById($sub_id);
		if(!$res['account_id']) return ajaxmsg('不存在的子账号',0);
		$data      = TrustIpo::get_trust_ipo($action,$sub_id,$offset);
		if(!$data) return ajaxmsg('没有数据',0);
		return ajaxmsg('操作成功',1,$data);
    }
}