<?php
namespace app\apicom\model;

use think\Model;
use think\facade\Db;
use app\apicom\model\StockDeliveryOrder as Delivery;
use util\RedisUtil;
/**
 * 会员模型
 */
class StockPosition extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'stock_position';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    /*
     * 存储持仓记录
     * $data 持仓数据
     * $sub_id 子账号
     * $lid 安全模式id号
     * $user 证券账户
     * $soure 证券来源
     */
    public static function add_position_broker($data,$lid,$user,$soure){
        $row=array();
        foreach ($data as $k => $value) {
            $row[$k]['lid'] = $lid;
            $row[$k]['soruce'] = $soure;
            $row[$k]['login_name'] = $user;
            $row[$k]['gupiao_code'] = $value[0];
            $row[$k]['gupiao_name'] = $value[1];
            $row[$k]['count'] = $value[2];
            $row[$k]['stock_count'] = $value[3];
            $row[$k]['canbuy_count'] = $value[4];
            $row[$k]['ck_price'] = $value[5];
            $row[$k]['buy_average_price'] = $value[6];
            $row[$k]['ck_profit_price'] = $value[7];
            $row[$k]['now_price'] = $value[8];
            $row[$k]['market_value'] = $value[9];
            $row[$k]['ck_profit'] = $value[10];
            $row[$k]['profit_rate'] = $value[11];
            $row[$k]['buying'] = $value[12];
            $row[$k]['selling'] = $value[13];
            $row[$k]['gudong_code'] = $value[14];
            $row[$k]['type'] = $value[15];
            $row[$k]['jigou_type'] = $value[15];
            $row[$k]['jiyisuo'] = $value[16]==0? "深交所":"上交所";
            $row[$k]['info'] = $value[17];
        }
        $result = Db::name('stock_position_broker')->insertall($row,true);
        return $result;
    }
    /*
     * 返回子账号指定股票持仓数据-带最新市值
     * $sub_id 子账号
     */
    public static function getPositionFind($sub_id='',$code='')
    {
        if($sub_id) $map[] = ['sub_id','=',$sub_id];
        if($code)   $map[] = ['gupiao_code','=',$code];
        $map[] = ['buying','=',0];
        
        $res=Db::view('stock_position p')->view('stock_subaccount s','sub_account','s.id=p.sub_id')->where($map)->order('id desc')->select()->toArray();
        foreach ($res as $k =>$v){
            //查询股票最新行情
	        $Qdata = RedisUtil::getQuotationData($v['gupiao_code'],toMarket($v['gupiao_code']));
            $res[$k]['now_price'] = $Qdata["Price"];
            $res[$k]['code']      = $Qdata["code"];
            $res[$k]['name']      = $Qdata["name"];
            $res[$k]['market_value'] = round($Qdata["Price"] * $v['stock_count'],2);//最新市值
            $res[$k]['ck_profit']    = $v['stock_count'] > 0 ? bcmul(strval($Qdata["Price"]-$v['buy_average_price']),strval($v['stock_count']),2) : 0;//参考浮动盈亏
            //$res[$k]['profit_rate']  = $v['stock_count'] > 0 ? bcdiv(strval($res[$k]['ck_profit']),strval($v['buy_average_price']*$v['stock_count']*100),2) : 0;//盈亏比例
        }
        return $res;
    }
    /*
     * 返回子账号和股票代码对应的持仓
     * $sub_id 子账号
     * $code 股票代码
     */
    public static function getCodePosition($sub_id,$code){
        $res=self::where(['sub_id'=>$sub_id,'gupiao_code'=>$code,'buying'=>0])->find();
        if(empty($res)) return false;
        $Qdata = RedisUtil::getQuotationData($code,toMarket($code),true);
        $res['now_price']    = $Qdata["Price"];
        $res['market_value'] = $Qdata["Price"]*$res['canbuy_count'];//最新市值
        $res['ck_profit']    = $res['stock_count'] > 0 ? bcmul(strval($Qdata["Price"]-$res['buy_average_price']),strval($res['canbuy_count']),2) : 0;//参考浮动盈亏
        //$res['profit_rate']  = $res['stock_count'] > 0 && $res['ck_profit'] ? bcdiv(strval($res['ck_profit']),strval($res['buy_average_price']*$res['canbuy_count']*100),2) : 0;//盈亏比例
        return $res;
    }
    /*
     * 返回子账号和股票代码对应持仓的可卖数量
     * $sub_id 子账号
     * $code 股票代码
     */
    public static function getCanbuyCount($sub_id,$code){
        $res = Db::name('stock_position')
            ->field('canbuy_count,stock_count')
            ->where(['sub_id'=>$sub_id,'gupiao_code'=>$code,'buying'=>0])
            ->find();
        //print_r($res);exit;
        if(empty($res)) return 0;
        $res_d1 = Db::name('stock_delivery_order')
            ->where(['sub_id'=>$sub_id,'gupiao_code'=>$code,'status'=>1,'business_name'=>'证券买入'])
            ->whereDay('deal_date')
            ->sum('volume');
        $res_d2 = Db::name('stock_delivery_order')
            ->where(['sub_id'=>$sub_id,'gupiao_code'=>$code,'status'=>0,'business_name'=>'证券卖出'])
            ->whereDay('deal_date')
            ->sum('volume');
        //如果时T+0模式，就不计算当天的股票数量
        if(TRUST_MODEL_TIME == 0) $res_d1 = $res_d2 = 0;
        $res['canbuy_count'] = $res['stock_count'] - $res_d1 - $res_d2;
        //print_r($res);exit;
        return $res['canbuy_count'];
    }
    /*
     * 添加卖出模拟持仓记录
     * $data 持仓数据
     * $sub_id 子账号
     * $lid 安全模式id号
     * $user 证券账户
     * $soure 证券来源
     * *************************************************************************************************************
     */
    public static function sell_m_position($stockinfo,$count,$price,$sub_id,$model,$Trust_no,$commission,$Transfer,$stamp){
        $position_res = self::getCodePosition($sub_id, $stockinfo["code"]);
        if(empty($position_res)) return false;
        if(!$model) $model = 2;
        $data = $position_res;
        $canbuy_count = $position_res['canbuy_count'] - $count;
        $stock_count  = $position_res['stock_count']  - $count;
        $fee = $commission+$Transfer+$stamp;
        if($canbuy_count>0){
            if($model==1){
                $data['canbuy_count'] = $canbuy_count;
            }
            if($model==2){
                $new_price=round(($position_res['canbuy_count']*$position_res['buy_average_price']-$count*$price-$fee)/$canbuy_count,3);
                $data['count'] =$stock_count;
                $data['stock_count'] =$stock_count;
                $data['canbuy_count'] = $canbuy_count;
                $data['ck_price'] = $new_price;//参考成本价
                $data['buy_average_price'] = $new_price;//买入均价
                $data['ck_profit_price'] = $new_price;//参考盈亏成本价
                $data['now_price'] = $stockinfo["Price"];//'当前价'
                $data['market_value'] = $stockinfo["Price"]*$canbuy_count;//最新市值
                $data['ck_profit']    = $canbuy_count >0 ? round(($stockinfo["Price"]-$new_price)*$canbuy_count,2) : 0;//参考浮动盈亏
                $data['profit_rate']  = $canbuy_count >0 ? round($data['ck_profit']/($new_price*$canbuy_count)*100,2) : 0;//盈亏比例
            }
            $result = Db::name('stock_position')
                ->where(['sub_id'=>$sub_id,'gupiao_code'=>$stockinfo["code"]])
                ->where(['buying'=>0])
                ->update($data);
            Log::write(date('y-m-d H:i:s',time())."::子账户".$sub_id."委托卖出".$count."股".$stockinfo["code"]."股票");
        }elseif($canbuy_count==0){
            if($model==2){
                $info=Db::name('stock_temp')
                    ->where(['sub_id'=>$sub_id])
                    ->where(['gupiao_code'=>$stockinfo["code"]])
                    ->where(['deal_no'=>null])
                    ->find();
                if(empty($info)) {
                    $result = Db::name('stock_position')
                        ->where(['sub_id' => $sub_id, 'gupiao_code' => $stockinfo["code"]])
                        ->where(['buying' => 0])
                        ->delete();
                }else{
                    $new_price=round(($position_res['stock_count']*$position_res['buy_average_price']-$count*$price-$fee)/$stock_count,3);
                    $data['count'] =$stock_count;
                    $data['stock_count'] =$stock_count;
                    $data['canbuy_count'] = 0;
                    $data['ck_price'] = $new_price;//参考成本价
                    $data['buy_average_price'] = $new_price;//买入均价
                    $data['ck_profit_price'] = $new_price;//参考盈亏成本价
                    $data['now_price'] = $stockinfo["Price"];//'当前价'
                    $data['market_value'] = $stockinfo["Price"]*$canbuy_count;//最新市值
                    $data['ck_profit']    = $canbuy_count >0 ? round(($stockinfo["Price"]-$new_price)*$canbuy_count,2) : 0;//参考浮动盈亏
                    $data['profit_rate']  = $canbuy_count >0 ? round($data['ck_profit']/($new_price*$canbuy_count)*100,2) : 0;//盈亏比例
                    $result = Db::name('stock_position')
                        ->where(['sub_id'=>$sub_id,'gupiao_code'=>$stockinfo["code"]])
                        ->where(['buying'=>0])
                        ->update($data);
                }
            }elseif($model==1){
                $data['canbuy_count']=0;
                $result = Db::name('stock_position')
                    ->where(['sub_id'=>$sub_id,'gupiao_code'=>$stockinfo["code"]])
                    ->where(['buying'=>0])
                    ->update($data);
            }else{
                $result = false;
            }

        }else{
            $result = false;
        }
        return $result;
    }
    /*
     * 存储模拟持仓记录
     * $data 持仓数据
     * $sub_id 子账号
     * $lid 安全模式id号
     * $user 证券账户
     * $soure 证券来源
     */
    public static function add_m_position($code,$count,$sub_id,$lid,$user,$soure,$ck_price,$Trust_no)
    {
        //if(!$count) return false;
        //$canbuy    = self::getCanbuyCount($sub_id,$code);
        $stockinfo = RedisUtil::getQuotationData($code,toMarket($code));
        $data      = array();
        $data[0]['sub_id']            = $sub_id;
        $data[0]['lid']               = $lid;
        $data[0]['soruce']            = $soure;
        $data[0]['login_name']        = $user;
        $data[0]['gupiao_code']       = $stockinfo["code"];
        $data[0]['gupiao_name']       = $stockinfo["name"];
        $data[0]['count']             = $count;
        $data[0]['stock_count']       = $count;
        $data[0]['canbuy_count']      = $count;
        $data[0]['ck_price']          = self::calculate($sub_id,$code,'price');//参考成本价
        $data[0]['buy_average_price'] = self::calculate($sub_id,$code,'average');//买入均价
        $data[0]['ck_profit_price']   = '';//参考盈亏成本价
        $data[0]['now_price']         = $stockinfo["Price"];//'当前价'
        $data[0]['market_value']      = $stockinfo["Price"] * $count;//最新市值
        $data[0]['ck_profit']         = $count > 0 ? bcmul(strval($stockinfo["Price"] - $ck_price),strval($count),2) : 0; //参考浮动盈亏
        $data[0]['profit_rate']       = $count > 0 && $ck_price > 0 ? bcdiv(strval($data[0]['ck_profit']),strval($ck_price * $count * 100),2) : 0; //盈亏比例
        $data[0]['buying']            = 0;//买入成功
        $data[0]['selling']           = 0;//1、在途卖出
        $data[0]['gudong_code']       = "";//股东代码 无法模拟暂时空
        $data[0]['type']              = 0;//帐号类别
        $data[0]['market']            = toMarket($code);//股票类别
        $data[0]['jigou_type']        = 1;
        $data[0]['jiyisuo']           = toMarket($code)=='SZ'? "深交所":"上交所";//交易所
        $data[0]['info']              = "";
        $position = self::getCodePosition($sub_id, $code);
        /***********************************************************************************/
        if(TRUST_MODEL_TIME === 1){ // 交易模式为T+1时，不能立即更新可卖数量
            unset($data[0]['canbuy_count']);
        } 
        /***********************************************************************************/
        if(!empty($position)){
            $result = self::where(['id'=>$position['id']])->update($data[0]);
        }else{
            $result = self::strict(false)->insert($data[0],true);
        }
        return $result;
    }
    
    public static function calculate($sub_id,$code,$variable)
    {
        if(!$sub_id || !$code || !$variable) return 0;
        switch ($variable) {
            case 'price':
                $order = Db::name('stock_delivery_order')->where(['sub_id' => $sub_id, 'gupiao_code' => $code,'status' => 1,'business_name' => '证券买入']);
                $amount = $order->sum('liquidation_amount');
                $volume = $order->sum('volume');
                $result =  bcdiv(strval($amount),strval($volume),3);
                break;
             case 'average':
                $order = Db::name('stock_delivery_order')->where(['sub_id' => $sub_id, 'gupiao_code' => $code,'status' => 1,'business_name' => '证券买入']);
                $amount = $order->sum('residual_quantity');
                $volume = $order->sum('volume');
                $result =  bcdiv(strval($amount),strval($volume),3);
                break;
            default:
                $result = 0;
                break;
        }
        return $result;
    }
}