<?php
namespace app\apicom\model;
use app\apicom\model\StockSubAccount;
use app\apicom\model\SubAccountMoney;
use app\apicom\model\StockSubAccountRisk;
use think\Model;
use think\facade\Db;

use util\RedisUtil;
use util\QuotationRedis;

class TrustIpo extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'stock_trust_ipo';
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 买入时检查
    public static function execute($data)
    {
        //判断购买数量书否正确
		//if (($data['count'] % 1000) != 0) return ['status'=>0, 'message'=>'交易数量必须是1000的整数倍'];
		$bs_res = Db::name('stock_borrow')->where(array('stock_subaccount_id' => $data['subid']))->find();
		if (empty($bs_res)) {
			return ['status'=>0, 'message'=>'没有对应的配资'];
		}
		if ($bs_res['end_time'] <= time()){
			return ['status'=>0, 'message'=>'配资已经到期，不允许买入'];
		}
		$trade_money = $data['count'] * $data['price'];
		//检查子账户余额
		$moneyinfo = SubAccountMoney::getAccountMoney($data['subid']);
		if ($moneyinfo['avail'] < ($trade_money)){
			return ['status'=>0, 'message'=>'购买资金不足'];
		}
        
		$risk_res = StockSubAccountRisk::getRisk($data['subid']);
		if ($risk_res['prohibit_open'] == 0){
			return ['status'=>0, 'message'=>'您被禁止开新仓，请联系管理员咨询原因'];
		}
		
        $ipo_res = self::where(['gupiao_code'=>$data['code'],'sub_id'=>$data['subid'],'status'=>'申购中'])->find();
		if($ipo_res) return ['status'=>0, 'message'=>'您已申购过该股票'];
		//print_r($ipo_res);exit;
		$retData['trade_money'] = $trade_money;
		$retData['moneyinfo']   = $moneyinfo;
		$retData['price']       = $data['price'];
		
		return $retData;
    }
    /*
     * 存储申购委托记录
     */
    public static function add_trust_ipo($data, $price, $Trust_no)
    {
        $subres = StockSubAccount::getAccountById($data['subid']);
		$broker = StockSubAccount::getBroker($subres['account_id']);
		if (!$subres) return ['status'=>0, 'message'=>'子账号或证券公司不存在'];
        $row=array();
        $row[0]['sub_id']      = $data['subid'];
        $row[0]['lid']         = $broker['lid'];
        $row[0]['soruce']      = $broker['stockjobber'];
        $row[0]['login_name']  = $broker['user'];
        $row[0]['add_time']    = time();//委托日期
        $row[0]['trust_time']  = date('H:i:s',time());//委托时间
        $row[0]['gudong_code'] = "";//股东代码
        $row[0]['market']      = $data["market"];//帐号类别
        $row[0]['gupiao_code'] = $data['code'];//证券代码
        $row[0]['gupiao_name'] = $data['name'];//证券名称
        $row[0]['flag1']       = 0;//买卖标志1
        $row[0]['flag2']       = "新股申购";//买卖标志2
        $row[0]['trust_price'] = $price;
        $row[0]['trust_count'] = $data['count'];
        $row[0]['trust_no']    = $Trust_no;//委托编号
        $row[0]['volume']      = 0;//成交数量
        $row[0]['amount']      = 0;//成交金额
        $row[0]['status']      = "申购中";//状态说明
        $row[0]['trust_date']  = date('Y-m-d',time());//委托日期
        $row[0]['beizhu']      = "";
        $row[0]['info']        = "";
        $row[0]['type']        = 0;
        $row[0]['type_today']  = 1;
        $row[0]['cancel_order_flag']  = 0;//撤单标志 0、可撤
        $row[0]['cancel_order_count'] = 0;
        $result = self::insert($row[0],true);
        return $result;
    }
    /*
     * 返回子账号新股申购记录
     * $sub_id 子账号
     */
    public static function get_trust_ipo($action, $sub_id, $offset=20)
    {
        //$endday   = $endday   ? $endday   : date("Y-m-d",time());
        //$beginday = $beginday ? $beginday : date("Y-m-d",time());
        switch ($action) {
            case 'apply':
                $status = '申购中';
                break;
            case 'codes':
                $status = '已中签';
                break;
            default:
                return false;
                break;
        }
        $res = Db::view('stock_trust_ipo trust')
            ->view('stock_subaccount sub','sub_account','sub.id = trust.sub_id')
            ->where(['trust.sub_id'=>$sub_id,'trust.status'=>$status])
            ->order('id desc')
            ->paginate($offset, false, ['query' => request()->param()]);
        
        return $res;
    }
}