<?php
namespace app\apicom\model;
use think\Model;
use think\facade\Db;
use util\RedisUtil;
class StockDeliveryOrder extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'stock_delivery_order';
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    /*
     * 返回对应交割单
     * $sub_id 子账号
     */
    public static function get_delivery_order($sub_id,$beginday="",$endday="", $page=1, $offset=15)
    {
        $endday   = $endday ? $endday : date("Y-m-d",time());
        $beginday = $beginday ? $beginday : date("Y-m-d",time());
        
        $res=self::view('stock_delivery_order deli')
            ->view('stock_subaccount sub','id,uid,sub_account','sub.id = deli.sub_id')
            ->where(['deli.sub_id'=>$sub_id])
            ->where(['deli.status'=>1])
            //->whereTime('deli.deal_date', 'between', [$beginday, $endday])
            ->order('deli.id desc')
            ->paginate($offset, false, ['query' => request()->param()])
            ->each( function($item, $key){
                $item->fees = round(($item->transfer_fee + $item->commission),2);
            });
        return $res;
    }
    /*
     * 返回子账号和股票代码对应的交割单
     * $sub_id 子账号
     * $code 股票代码
     */
    public static function get_code_delivery_order($sub_id,$code)
    {
        $res=self::where(['sub_id'=>$sub_id,'gupiao_code'=>$code])
            ->where(['status'=>1])
            ->order('id desc')
            ->select();
        return $res;
    }

    /*
     * 添加卖出模拟交割单记录
     * $data 持仓数据
     * $sub_id 子账号
     * $lid 安全模式id号
     * $user 证券账户
     * $soure 证券来源
     */
    public static function sell_m_delivery_order($code,$count,$price,$sub_id,$commission,$Transfer,$Trust_no,$stamp,$avail,$amount,$model)
    {
        $submodel = new StockSubAccount();
		$sub_res  = $submodel->getAccountById($sub_id);
		$broker   = $submodel->getBroker($sub_res['account_id']);
		if (!$sub_res) return ['status'=>0, 'message'=>'子账号或证券公司不存在'];
        $stockinfo = RedisUtil::getQuotationData($code,toMarket($code));
        $data=array();
        $data[0]['sub_id']        = $sub_id;
        $data[0]['lid']           = $broker['lid'];
        $data[0]['soruce']        = $broker['stockjobber'];
        $data[0]['login_name']    = $broker['user'];
        $data[0]['gupiao_code']   = $stockinfo["code"];
        $data[0]['gupiao_name']   = $stockinfo["name"];
        $data[0]['deal_date']     = date('Y-m-d',time());
        $data[0]['business_name'] = "证券卖出";
        $data[0]['deal_price']    = $price;
        $data[0]['volume']        = intval($count);
        $data[0]['amount']        = $amount;
        $data[0]['residual_quantity']  = intval($count)*intval($price);//成交金额
        $data[0]['liquidation_amount'] = intval($count)*intval($price)-$commission-$Transfer-$stamp;//清算金额
        $data[0]['residual_amount'] = $avail;
        $data[0]['stamp_duty']      = $stamp;
        $data[0]['transfer_fee']    = $Transfer;
        $data[0]['commission']      = $commission;
        $data[0]['transaction_fee'] = 0;
        $data[0]['front_desk_fee']  = 0;
        $data[0]['trust_no']        = $Trust_no;
        $data[0]['deal_no']         = $Trust_no+521;
        $data[0]['gudong_code']     = "";//股东代码 无法模拟暂时空
        $data[0]['type']            = 0;//帐号类别
        $data[0]['market']          = $stockinfo["market"];//股票类别
        $data[0]['status']          = 0;//状态 0、未确认 1、已确认
        $result = self::insertall($data,true);
        return $result;

    }
    /*
     * 存储模拟交割单记录
     * $data 持仓数据
     * $sub_id 子账号
     * $lid 安全模式id号
     * $user 证券账户
     * $soure 证券来源
     */
    public static function add_m_delivery_order($code,$count,$price,$sub_id,$commission,$Transfer,$Trust_no,$avail,$amount,$model)
    {
        //return "佣金: ".$commission." 过户费: ".$Transfer." 总计：".$avail;
        $submodel = new StockSubAccount();
		$sub_res  = $submodel->getAccountById($sub_id);
		$broker   = $submodel->getBroker($sub_res['account_id']);
		if (!$sub_res) return ['status'=>0, 'message'=>'子账号或证券公司不存在'];
        $stockinfo = RedisUtil::getQuotationData($code,toMarket($code));
        $data=array();
        $data[0]['sub_id']        = $sub_id;
        $data[0]['lid']           = $broker['lid'];
        $data[0]['soruce']        = $broker['stockjobber'];
        $data[0]['login_name']    = $broker['user'];
        $data[0]['gupiao_code']   = $stockinfo["code"];
        $data[0]['gupiao_name']   = $stockinfo["name"];
        $data[0]['deal_date']     = date('Y-m-d',time());
        $data[0]['business_name'] = "证券买入";
        $data[0]['deal_price']    = $price;
        $data[0]['volume']        = $count;
        $data[0]['amount']        = $amount;
        $data[0]['residual_quantity']  = ($count*$price);
        $data[0]['liquidation_amount'] = ($count*$price)+$commission+$Transfer;//清算金额
        $data[0]['residual_amount'] = $avail;
        $data[0]['stamp_duty']      = 0;
        $data[0]['transfer_fee']    = $Transfer;
        $data[0]['commission']      = $commission;
        $data[0]['transaction_fee'] = 0;
        $data[0]['front_desk_fee']  = 0;
        $data[0]['trust_no']        = $Trust_no;
        $data[0]['deal_no']         = $Trust_no+521;
        $data[0]['gudong_code']     = "";//股东代码 无法模拟暂时空
        $data[0]['type']            = 0;//帐号类别
        $data[0]['market']          = $stockinfo["market"];//股票类别
        $data[0]['status']          = 0;//状态 0、未确认 1、已确认
        $result = self::insertall($data,true);
        return $result;
    }

    public static function getDeliveryOrder($subid,$code,$daycount=1)
    {
        $count = self::where(['sub_id' => $subid, 'gupiao_code' => $code,'status' => 1,'business_name' => '证券买入'])
            ->whereDay('deal_date')
            ->sum('volume');
        if($daycount == 2){
            $count_2 = self::where(['sub_id' => $subid, 'gupiao_code' => $code,'status' => 1,'business_name' => '证券买入'])
                ->whereDay('deal_date','yesterday')
                ->sum('volume');
            $count = $count + $count_2;
        }
        return $count;
    }
}