<?php
declare (strict_types = 1);

namespace app\apicom\controller;
use app\apicom\model\SubAccount;
use app\apicom\model\StockSubAccountSelf;
use app\apicom\model\Member;
use app\apicom\model\Borrow;
use app\apicom\model\SubAccountMoney;
use app\apicom\model\StockSubAccount;
use app\apicom\model\StockPosition;
use app\apicom\model\UpdatePostion;
use app\apicom\model\HistorySeacher;
use think\facade\Db;
use util\RedisUtil;
use util\SearchRedis;
use util\QuotationRedis;

class Market extends BaseController
{
    //本地数据库股票查询
    public function stockSearch()
    {
        $key    = input('key', '');
        $result = $this->validate(['keyword' => $key], 'Stock.search');
        if (!$result)  return ajaxmsg($result,0);
        // 搜索列表
        $data = SearchRedis::search($key);
        //print_r($data);exit;
        if (!$data) return ajaxmsg('查询失败',0);
        $res  = [];
        $self = new StockSubAccountSelf();
        if(!empty($data)){
            foreach ($data as $k=>$v){
                $res[$k]['market'] = $v['market'];
                $res[$k]['code']   = $v['code'];
                $res[$k]['name']   = $v['title'];
                $res[$k]['pin']    = $v['pinyin'];
                if($this->userId) {
					$ret = $self->myadd($this->userId, $v['code']) ?? 0;//查找是否存在
					$res[$k]['favorite'] = $ret ? 1 : 0;
				}
            }
        }
        return ajaxmsg('操作成功',1,$res);
    }
    /**
     * 搜索历史查询
     * $history 记录
     */
    public function getHistorySecher(){
        $history = Db::name('stock_history')->where(['status'=>1])->where('code_title', '<>', '')->order('count desc')->limit(12)->select();
        return ajaxmsg('操作成功',1,$history);
    }

     /*
     * 保存查询记录
     * 如果登陆保存token
     */
    public function  addHistory()
    {
        $market     = input('market', '');
        $code       = input('code', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $code_title = input('code_title', '');
        $res = HistorySeacher::add_histtory($market,$code,$code_title,$this-userId);
        if(!$res) return ajaxmsg('操作失败', 0);
        return ajaxmsg('操作成功', 1);
    }
    /*
     * market 实时行情接口函数
     * 可通过get或post方式访问返回json格式数据
     * @code 必传参数 股票代码 如果查询上证指数需要用sh000001
     */
    public function market()
    {
        $market = input('market', '');
        $code   = input('symbol', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if (!$code) return ajaxmsg('缺少参数code，操作失败',0);
        $data = RedisUtil::getQuotationData($code,$market);
        if (!$data) return ajaxmsg('操作失败',0);
        //新增检测是否是自选股票
        $self = new StockSubAccountSelf();
        if($this->userId){
            $ret = $self->myadd($this->userId, $code) ?? 0;//查找是否存在
            $res = HistorySeacher::add_histtory($market,$code,$data['name'],$this->userId);
            if ($ret) {
                $data['myFavorite'] = 1;
            }else{
                $data['myFavorite'] = 0;
            }
        }
        
        return ajaxmsg('操作成功',1,$data);

    }
    /*
     * 获取活跃股票列表
     */
    public function aliveStock ()
    {
        //QuotationRedis::getAliveStocks();
        $data = QuotationRedis::aliveStockList();
        return ajaxmsg('操作成功',1,$data);
    }
    /*
     * 行业涨幅板块
     */
    public function sinahy(){
        $output = curl('https://vip.stock.finance.sina.com.cn/q/view/newSinaHy.php');
		$findme = '{"';
		$pos = strpos($output, $findme) + 2;
		$output = substr($output, $pos, -2);
		$t2 = explode('","', mb_convert_encoding($output, 'utf-8', 'gbk'));
		$res = array();
		foreach ($t2 as $k => $v) {
			$res[$k] = explode(',', substr(explode(':', $v)[1], 1));
		}
        if (!$res) {
            return ajaxmsg('获取失败',0);
        }
        return ajaxmsg('操作成功',1,$res);
    }
    /*
     * 板块列表
     */
    public function industry() {
        $data=Db::name('stock_industry')->select();
        if (!$data) {
            return json(['data' => $data, 'status' => 0, 'message' => '操作失败']);
        }
        return json(['data' => $data, 'status' => 1, 'message' => '操作成功']);
    }
    /*
     * add_my_select 添加我的自选函数
     * @uid 必传参数 用户在用户表id
     * @name 必传参数 股票名称
     * @code 必传参数 股票代码
     */
    public function addFavorite()
    {
        $market = input('market', '');
        $name   = input('name', '');
        $code   = input('code', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $self   = new StockSubAccountSelf();
        $res    = '';
        if ($name && $code) {
            $ret = $self->myadd($this->userId, $code);//查找是否存在
            if ($ret) return ajaxmsg('已存在自选列表中',0);
            $res = $self->addMyselect($this->userId, $market, $name, $code);
        }
        if (!$res) return ajaxmsg('添加失败',0);
        $data = $self->myadd($this->userId, $code);
        if (!$data) return ajaxmsg('系统错误',0);
        //QuotationRedis::addAliveStocks($code);//添加到活跃列表缓存
        return ajaxmsg('添自选加成功', 1, $data);
    }

    /*
     * 删除我的自选函数
     * @id 我的自选股票id
     */
    public function delFavorite(){
        $code = input('code', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if (!$code === null) return ajaxmsg('缺少参数code，操作失败',0);
        $self = new StockSubAccountSelf();
        $res  = $self->delMyselectbycode($this->userId, $code);
        if (!$res) return ajaxmsg('删除失败',0);
        return ajaxmsg('删除自选成功',1);
    }

      /*
     * 删除我的自选函数 array 批量
     * @id 我的自选股票id
     */
    public function delFavoriteArr(){
        $code    = input('code', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $codeArr = explode(',',$code);
        if(!$codeArr || !is_array($codeArr)) return ajaxmsg('缺少参数或参数获取错误',0);
        $self = new StockSubAccountSelf();
        foreach($codeArr as $k=>$v){    
            $res = $self->delmyselectbycode($this->userId, intval($v));
        }
        if (!$res) return ajaxmsg('删除失败',0);
        return ajaxmsg('批量删除自选成功',1);
    }
    /*
     * my_select 我的自选函数
     * @uid 必传参数 用户在用户表id
     * 新增 根据自定义排序 sort
     */
    public function favorite()
    {
        $data = Db::name('stock_subaccount_self')->where('uid', $this->userId)->order("sort asc")->select()->toArray();
        if (!$data || count($data) === 0) return ajaxmsg('没有数据',0);
        $data = array_chunk($data,LOCAL_STOCK_COUNT,true);
        $code = "";
        foreach ($data[0] as $k => $v) {
            $dian = count($data[0]) == ($k+1) ? "" : ",";
            $code .= strtolower($v["market"]) . $v["gupiao_code"] . $dian;
        }
        $info  = getApiStock($code,'stocks');
        $jdata = [];
        foreach ($data[0] as $k => $item) {
            foreach ($info as $kk => $vv) {
                if (intval($item["gupiao_code"]) === intval($vv[2])) {
                    $jdata[$k]['market']= $vv[0];
                    $jdata[$k]['code']  = $vv[2];
    	            $jdata[$k]['name']  = $vv[1];
    	            $jdata[$k]['price'] = $vv[3];
    	            $jdata[$k]['rate']  = isset($vv[4])&&$vv[4]>0?round((($vv[3]-$vv[4])/$vv[4]*100),2):'';
                    break;
                }
            }
        }
        if($jdata) return ajaxmsg('操作成功', 1, $jdata);
        return ajaxmsg('操作失败', 0);
    }
    
    /**
     * 获取子账号信息
     */
    public function getSubAccount(){
        if(!$this->token || !$this->userId) return ajaxmsg('未登录',500);
        $where = [
            'member_id'=>$this->userId
        ];
        $order = 'b.id desc';
        $subList = Borrow::getListAll($where,$order,20);
        return ajaxmsg('子账号信息',1,$subList);
    }
    /**
     * 获取子账号交易明细信息
     */
    public function getSubRecord(){
        if(!$this->token || !$this->userId) return ajaxmsg('未登录',500);
        $subAc = input('sub_ac', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if(!$subAc) return ajaxmsg('缺少参数',0);
        $check = StockSubAccount::CheckMemberSub($this->userId,$subAc);
        if(!$check)  return ajaxmsg('该交易账户不属于您！',0);
        if(!empty($subAc)) $where[] = ['s.sub_account ' ,'=', $subAc];
        $where[] = ['s.status' ,'=', 1];
        $order   = 'r.create_time desc';
        $offset  = 20;
        //print_r($where);exit;
        $data_list = SubAccount::getSubRecordList($where,$order,$offset);
        if(!$data_list) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$data_list);
    }
    /*
     * 获取子账号对应的信息
     */
    public function getSubInfo()
	{
		if(!$this->token || !$this->userId) return ajaxmsg('未登录',500);
		$subId    = input('id', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
		if(!$subId) return ajaxmsg('缺少参数或参数获取错误' , 0);
		$subModel = new SubAccountMoney;
		$res      = $subModel->getAccountMoneyInf($subId);
		if(!$res) return ajaxmsg('操作失败' , 0);
		$res['available_amount'] >= 0 ? $res['available_amount'] : 0;
		$res = $subModel->ftoy($res);
		$pos = StockPosition::where(['sub_id'=>$subId, 'buying'=>0])->order('id desc')->select()->toArray();
		$res['return_money'] = 0;
		$res['market_value'] = 0;
		foreach ($pos as $k => $v ) {
			$data = RedisUtil::getQuotationData($v['gupiao_code'],$v['market'],true);
			if($data['Price'] == '') continue;
			$res['return_money'] += ($data['Price'] - $v['buy_average_price']) * $v['stock_count'];
			$res['market_value'] += $data['Price'] * $v['stock_count'];
		}
		//print_r(bcmul($res['market_value'],2));return;
		// 提盈额度计算
		$all    = $res['market_value'] + $res['avail'];
		$profit = bcsub(strval($all),bcadd(strval($res['borrow_money']),strval($res['deposit_money'])),2);
		if($profit > 0){
		    $res['available_amount'] = $profit < $res['available_amount'] ? $profit : $res['available_amount'];
		}else{
			$res['available_amount'] = 0;
		}
		//$res['available_amount'] = $res['available_amount'] > $res['avail'] ? $res['avail'] : $res['available_amount'];
		$res['available_amount'] = bcadd(strval($res['available_amount']),'0',2);
		// 去掉卖出委托的市值
		$weituo = 0;
		$weituo = Db::name('stock_trust')->where(['sub_id'=>$res['stock_subaccount_id'],'flag2'=>'卖出委托','status'=>'已委托'])->sum('amount');
		$res['return_money'] = bcadd(strval($res['return_money']),'0', 2); //加法，在原值上加0为了保留小数点后两位
		$res['market_value'] = bcsub(strval($res['market_value']),strval($weituo), 2);//减法
		$res['total_money']  = bcadd(strval($res['market_value']),bcadd(strval($res['avail']),strval($res['freeze_amount']),2), 2);//加法
		
		return ajaxmsg('操作成功',1, $res);
	}
    
    //第三方个股数据获取
    public function thirdMarkets()
    {
        $code = input('code', '');
		if(!$code) return false;
		$Qdata = RedisUtil::getQuotationData($code,toMarket($code));
		//$Qdata = getApiStock(strtolower(toMarket($code)).$code);
		//print_r($Qdata);exit;
		return ajaxmsg('操作成功', 1, $Qdata);
    }
    //第三方股票列表数据获取
    public function getApiStockList()
    {
		$Ldata = Eastmoney_HSJ_List();
		//$Ldata = apiStockList();
		if(!$Ldata) return ajaxmsg('操作失败', 0);
		return ajaxmsg('操作成功', 1, $Ldata);
    }
}