<?php
// 引入常量定义
include_once __DIR__ . DIRECTORY_SEPARATOR . 'define.php';
use think\facade\Db;
use Yurun\Util\Chinese;
use Yurun\Util\Chinese\Pinyin;
use util\RedisUtil;
use util\SystemRedis;

error_reporting(E_ERROR | E_WARNING | E_PARSE);
// 应用公共文件
/*
 * 验证交易时间
 */
if (!function_exists('checkTradeTime')) {
    function checkTradeTime($last_time='15:00:00')//15:00:00
    {
        $t  = time();//当前时间戳
        $t2 = strtotime(date("Y-m-d 09:29:50"));//早盘开盘时间
        $t3 = strtotime(date("Y-m-d 11:30:00"));//早盘停盘时间
        $t4 = strtotime(date("Y-m-d 12:00:00"));//下午开盘时间
        $t5 = strtotime(date("Y-m-d ".$last_time));//下午停盘时间
        if (!(($t > $t2 && $t < $t3) || ($t > $t4 && $t < $t5))) return false;//
        if (date('N', time()) > 5) return false;//周六周日
        $array = festival();//返回节假日
        if (in_array(date("md", $t), $array)) return false;//如果是节假日
        return true;
    }
}
/*
 * 获取网站基础设置
*/
if (!function_exists('sysConfig')) {
    function sysConfig($value = '')
    {
        $data = SystemRedis::getConfig();
        if(empty($value)) return $data ?: [];
        if(isset($data[$value])){ 
            return $data[$value] ?: [];
        }else{
            return false;
        }
    }
}
/*
**国家法定假日获取
*/
if (!function_exists('festival')) {
    function festival()
    {
    	$year = date('Y', time());
    	$data = cache('festival_' . $year);
    	if ($data) return $data;
    	$holiday = array();
    	$confDay = sysConfig('legal_holiday');
    	if (empty($confDay)) {
    		$confDay = curl('https://tool.bitefu.net/jiari/?d='.$year);
    		$confDay = json_decode($confDay);
    		if ($confDay && is_object($confDay->$year)) {
    			$n = 0;
    			foreach ($confDay->$year as $key => $value) {
    				$holiday[$n] = $key;
    				$n++;
    			}
    		}else{
    			return null;
    			$holiday = $confDay->$year;
    		}
    	}else {
    		$holiday = str_replace('，',',',$confDay);
    		$holiday = explode(',',$holiday);
    	}
    	cache('festival_' . $year, $holiday);
    	return $holiday;
    }
}
/*
 * 获取主目录路径
*/
if (!function_exists('getFilePath')) {
    function getFilePath($id = '', $type = 0)
    {
        if (is_array($id)) {
            $data_list = Db::name('admin_attachment')->where('id', 'in', $id)->select();
            $paths = [];
            foreach ($data_list as $key => $value) {
                if ($value['driver'] == 'local') {
                    $paths[$key] = ($type == 0 ? '/' : '').$value['path'];
                } else {
                    $paths[$key] = $value['path'];
                }
            }
            return $paths;
        } else {
            $data = Db::name('admin_attachment')->where('id', $id)->find();
            if ($data) {
                if ($data['driver'] == 'local') {
                    return ($type == 0 ? '/' : '').$data['path'];
                } else {
                    return $data['path'];
                }
            } else {
                return false;
            }
        }
    }
}
if (!function_exists('generate_rand_str')) {
    /**
     * 生成随机字符串
     * @param int $length 生成长度
     * @param int $type 生成类型：0-小写字母+数字，1-小写字母，2-大写字母，3-数字，4-小写+大写字母，5-小写+大写+数字
     * @return string
     */
    function generate_rand_str($length = 8, $type = 0) {
        $a = 'abcdefghijklmnopqrstuvwxyz';
        $A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $n = '0123456789';
        switch ($type) {
            case 1: $chars = $a; break;
            case 2: $chars = $A; break;
            case 3: $chars = $n; break;
            case 4: $chars = $a.$A; break;
            case 5: $chars = $a.$A.$n; break;
            default: $chars = $a.$n;
        }
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $str;
    }
}
/**
 * 时间格式转换
 */

if (!function_exists('getTimeFormt')) {

    function getTimeFormt($time, $type = 0)
    {
        $f = "Y-m-d H:i:s";
        if ($type == 0) $f = "m-d H:i";
        if ($type == 1) $f = "Y-m-d H:i";
        if ($type == 3) $f = "m-d H:i";
        if ($type == 4) $f = "H:i:s";
        if ($type == 5) $f = "Y-m-d";
        if ($type == 6) $f = "H:i:s";
        if ($type == 7) $f = "Y-m-d H:i:s";
        return date($f, $time) ?? '';
    }
}
/**
 * 使用bootstrap-datepicker插件的时间格式来格式化时间戳
 * @param null $time 时间戳
 * @param string $format bootstrap-datepicker插件的时间格式 https://bootstrap-datepicker.readthedocs.io/en/stable/options.html#format
 * @return false|string
 */
if (!function_exists('format_date')) 
{
    function format_date($time = null, $format='yyyy-mm-dd') {
        $format_map = [
            'yyyy' => 'Y',
            'yy'   => 'y',
            'MM'   => 'F',
            'M'    => 'M',
            'mm'   => 'm',
            'm'    => 'n',
            'DD'   => 'l',
            'D'    => 'D',
            'dd'   => 'd',
            'd'    => 'j',
        ];
        // 提取格式
        preg_match_all('/([a-zA-Z]+)/', $format, $matches);
        $replace = [];
        foreach ($matches[1] as $match) {
            $replace[] = isset($format_map[$match]) ? $format_map[$match] : '';
        }
        // 替换成date函数支持的格式
        $format = str_replace($matches[1], $replace, $format);
        $time = $time === null ? time() : intval($time);
        return date($format, $time);
    }
}

if (!function_exists('build_rid_no')) {
    function build_rid_no()
    {
    	$numbers = mt_rand(100, 1000) + time();
    	return $numbers;
    }
}
/*处理网站设置里 字符串转数组*/
if (!function_exists('arrayEol')) {
    function arrayEol($string,$i=0)
    {
        $str_1 = explode(PHP_EOL,$string);
        $str_2 = array();
        foreach ($str_1 as $k => $v){
            $str_2[$k+1] = preg_replace('/\r|\n/', '', explode(':',$v)[$i]);
        }
        return $str_2;
    }
}
/*处理网站设置里 提示文字转数组*/
if (!function_exists('arrayEolTip')) {
    function arrayEolTip($string)
    {
        $str_1 = explode(PHP_EOL,$string);
        return $str_1;
    }
}
if (!function_exists('month_config')) {
	function month_config()
	{
		
		$config['month_loss'] = explode('|', sysConfig('month_loss'));
		$config['month_rate'] = arrayEol(sysConfig('month_rate'),1);
		$config['month_use_time'] = explode('|', sysConfig('month_use_time'));
		$config['month_position'] = arrayEol(sysConfig('month_position'));
		return $config;
	}
}

if (!function_exists('week_config')) {
	function week_config()
	{
		$config['week_loss'] = explode('|', sysConfig('week_loss'));
		$config['week_rate'] = arrayEol(sysConfig('week_rate'),1);
		$config['week_use_time'] = explode('|', sysConfig('week_use_time'));
		$config['week_position'] = arrayEol(sysConfig('week_position'));
		return $config;
	}
}

if (!function_exists('free_config')) {
	function free_config()
	{
		$config['free_loss'] = explode('|', sysConfig('free_loss'));
		$config['free_set']  = explode('|', sysConfig('free_set'));
		$config['day_position'] = arrayEol(sysConfig('day_position'));
		return $config;
	}
}

if (!function_exists('day_config')) {
	function day_config()
	{
		$config['day_loss'] = explode('|', sysConfig('day_loss'));
		$config['day_rate'] = arrayEol(sysConfig('day_rate'),1);
		$config['day_position'] = arrayEol(sysConfig('day_position'));
		$config['day_use_time'] = explode('|', sysConfig('day_use_time'));
		return $config;
	}
}

if (!function_exists('global_config')) {
	function global_config()
	{
		$config['money_range']  = explode('|', sysConfig('money_range'));
		//$config['limit_fee']    = sysConfig('limit_fee'); //最低佣金直接调用各个证券公司的设置
		//$config['commission']   = sysConfig('commission');//最低佣金比例直接调用各个证券公司的设置
		$config['stamp_duty']   = sysConfig('stamp_duty');
		$config['transfer_fee'] = sysConfig('transfer_fee');
		$config['profit_share'] = sysConfig('profit_share');
		$config['stop_fee']     = sysConfig('stop_fee');
		$config['stock_count']  = sysConfig('stock_count');
		$config['rebate']       = sysConfig('rebate');
		return $config;
	}
}
/*
 *
 */
if (!function_exists('getEndDay')) {
    function getEndDay($start = 'now', $offset = 0, $exception = '')
    {
    	$starttime = strtotime($start);
    	$endtime   = $starttime + $offset * 24 * 3600;
    	$end       = date('Y-m-d', $endtime);
    	$weekday   = date('N', $starttime);
    	$newoffset = 0;
    	for ($i = 1; $i <= $offset; $i++) {
    		$today = date('md', $starttime + $i * 24 * 3600);
    		switch (($weekday + $i) % 7) {
    		case 6:
    			$newoffset += 1;
    			break;
    		case 0:
    			$newoffset += 1;
    			break;
    		default:
    			if (is_array($exception)) {
    				if (in_array($today, $exception)) {
    					$newoffset += 1;
    				}
    			}elseif($today == $exception) {
    				$newoffset += 1;
    			}
    			break;
    		}
    	}
    	if (0 < $newoffset) {
    		return getEndDay($end, $newoffset, $exception);
    	}else{
    		return $end;
    	}
    }
}
/*
 *
 */
if (!function_exists('getEndDay2')) {
	function getEndDay2($start = 'now', $exception = '')
	{
		$starttime = strtotime($start);
		$weekday = date('N', $starttime);
		$tmpday = date('Y-m-d', $starttime);
		if(is_array($exception)) {
			$bfd = in_array($tmpday, $exception);
		}else{
			$bfd = $exception == $tmpday;
		}
		if($weekday <= 5 && !$bfd){
			$status = 1;
		}else{
			$status = 2;
		}
		return $status;
	}
}
/*
 * 计算利息
 */
if (!function_exists('calculate_rate')) {
	function calculate_rate($multiple, $rate, $type, $deposit_money, $endTime)
	{
		if ($type == 1 || $type == 2) {
			$duration     = 0;
			$durationTmp  = ceil(($endTime - mktime(0, 0)) / 3600 / 24);
			$durationDays = array();
			for ($i = 0; $i < $durationTmp; $i++) {
				$durationDays[$i] = date('Y-m-d', strtotime('+' . $i . ' day'));
			}
			if ($type == 1) {
				$hello = festival();
				foreach ($durationDays as $v) {
					if (getEndDay2($v, $hello) == 1) {
						$duration++;
					}
				}
			}
			if ($type == 2) {
				$duration = round($durationTmp / 7, 2);
			}
		}else{
			$durationTmp = ceil(($endTime - mktime(0, 0)) / 3600 / 24);
			$duration    = round($durationTmp / 30, 2);
		}
		$fee = round($deposit_money * $multiple * $duration * $rate / 100, 2);
		return $fee;
	}
}
/**
 * 返回本年、本周、本月、本日的开始和结束时间的时间戳
 *
 * @return array
 */
if (!function_exists("arrangeTime")) {
    function arrangeTime($type){
        switch ($type) {
            case 'month':
                $y = date("Y", time());
                $m = date("m", time());
                $d = date("d", time());
                $t0 = date('t');                   // 本月一共有几天
                $d0 = mktime(0, 0, 0, $m, 1, $y);       // 创建本月开始时间
                $d1 = mktime(23, 59, 59, $m, $t0, $y);  // 创建本月结束时间
                break;
            case 'week':
                $w = date("w", time());   //这天是星期几
                $d0 = mktime(0, 0, 0, date("m"), date("d") - $w, date("Y"));       //创建周开始时间
                $d1 = mktime(23, 59, 59, date("m"), date("d") - $w + 6, date("Y"));//创建周结束时间
                break;
            case 'day':
                $d0 = mktime(0, 0, 0, date("m"), date("d"), date("Y"));   //创建日开始时间
                $d1 = mktime(23, 59, 59, date("m"), date("d"), date("Y"));//创建日结束时间
                break;
            case 'year':
                $d0 = strtotime(date("Y", time()) . "-1" . "-1"); //本年开始
                $d1 = strtotime(date("Y", time()) . "-12" . "-31"); //本年结束
                break;
        }
        return array($d0, $d1);
    }
}
/*
*获取客户端IP
*/
if (!function_exists('getClientIp')) {
    function getClientIp() {
        return '0.0.0.0';
    }
}
/**
 * 生成随机字符串
 * @param int $length 生成长度
 * @param int $type 生成类型：0-小写字母+数字，1-小写字母，2-大写字母，3-数字，4-小写+大写字母，5-小写+大写+数字
 * @author 绿麻雀 
 * @return string
 */
if (!function_exists('generate_rand_str')) {
    function generate_rand_str($length = 8, $type = 0) {
        $a = 'abcdefghijklmnopqrstuvwxyz';
        $A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $n = '0123456789';
        switch ($type) {
            case 1: $chars = $a; break;
            case 2: $chars = $A; break;
            case 3: $chars = $n; break;
            case 4: $chars = $a.$A; break;
            case 5: $chars = $a.$A.$n; break;
            default: $chars = $a.$n;
        }
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $str;
    }
}
/**
 * 生成6位验证码
 *
 * @return string
 */
if (!function_exists('create_captcha')) {
    function create_captcha(){
        $str = mt_rand(1, 1000000000) . mt_rand(100, 1000000000);
        return substr($str, 0, 6);
    }
}
/*
*二维数组去重
*/
if (!function_exists('array_unique_fb')) {
    function array_unique_fb($array2D = [], $keys = []) {
        $temp_1 = [];
        $temp_2 = [];
        foreach ($array2D as $k => $v){  
            $v = join(',',$v);  
            $temp_1[$k] = $v;  
        }  
        $temp = array_unique($temp_1) ?? [];
        foreach ($temp as $k => $v){  
            $array=explode(',',$v);
            foreach($keys as $index => $key){    
                $temp_2[$k][$key] = $array[$index];  
            }  
        }  
        return $temp_2;
    }
}
/*
 * 获取城市地区数据并写入缓存
 * @param  intval $reid 上级id
 * @param  intval $id   地区id
 * @return [type]       [description]
 */
if(!function_exists("areaList")) {
    function areaList($reid = null, $id = null){
        $area = cache('area');
        if (!$area) {
            $area_arr = Db::name('area')->select()->toArray();
            foreach ($area_arr as $value) {
                $area[$value['id']] = $value;
            }
            cache('area', $area);
        }
        if ($reid) {
            foreach ($area as $val) {
                $val['reid'] == $reid && $data[] = $val;
            }
            return $data;
        }
        if ($id) {
            return $area[$id];
        }
        return null;
    }
}
/**
 * 资金单位为分转换其他单位
 * @param  [type] $value [description]
 * @return [type]        [description]
 */
if(!function_exists('money_convert')){
    function money_convert($value=0, $unit='元'){
        $money = bcdiv(strval($value), '1', 2);
        if($unit=='万' && $value > 100000){
            $money = bcdiv(strval($value), '10000', 2);
        }
        return $money;
    }
}
/*
 * 分析交易所代码
 */
if (!function_exists('toMarket')){
    function toMarket($code){
        if($code == '000001'){
            return 'SZ';
        }
        if(in_array(substr($code, 0, 1),array('6', '9'))){
    	    return 'SH';
    	}
    	if(in_array(substr($code, 0, 1),array('0', '2', '3'))){
    	    return 'SZ';
    	}
    	if(in_array(substr($code, 0, 1),array('4', '8'))){
    	    return 'BJ';
    	}
    }
}
/*
 * 判断是否为A股股票
 */
/* if (!function_exists('marketType')) {
    function marketType($code){
        switch (substr($code,0,1)){
            case '0':return 1;break;
            case '3':return 1;break;
            case '1':return 1;break;
            case '2':return 1;break;
            case '6':return 2;break;
            case '5':return 2;break;
            case '9':return 2;break;
            case '4':return 3;break;
            case '8':return 3;break;
            default: return 5;break;//5、出错
        }
    }
} */
/*
 * 判断交易所名称
 */
/* if (!function_exists('exChange')) {
    function exChange($code){
        switch (substr($code, 0, 1)) {
            case '0':  $data['d'] = 0;$data['exchange'] = "深交所";  break;
            case '3':  $data['d'] = 0;$data['exchange'] = "深交所";  break;
            case '1':  $data['d'] = 0;$data['exchange'] = "深交所";  break;
            case '2':  $data['d'] = 0;$data['exchange'] = "深交所";  break;
            case '6':  $data['d'] = 1;$data['exchange'] = "上交所";  break;
            case '5':  $data['d'] = 1;$data['exchange'] = "上交所";  break;
            case '9':  $data['d'] = 1;$data['exchange'] = "上交所";  break;
            case '4':  $data['d'] = 2;$data['exchange'] = "北交所";  break;
            case '8':  $data['d'] = 2;$data['exchange'] = "北交所";  break;
            default : return [];
        }
        return $data;
    }
} */

/*
 * 计算佣金
 */
if (!function_exists('commission')) {
    function commission($money,$scale,$min){
        $commission = round(($money * $scale) / 10000, 2);//佣金
        $commission = $commission < $min ? $min : $commission;
		return $commission;
    }
}
/*
 * 计算印花税
 */
if(!function_exists('stamps')) {
    function stamps($money){
        $stamps = round($money * sysConfig('stamp_duty') / 1000, 2);
        return $stamps ?? 0;
    }
}
/* 
 * 计算过户费
 */
if(!function_exists('transfer')) {
    function transfer($money){
        if(!sysConfig('transfer_fee') || sysConfig('transfer_fee') == 0){ //当该值未设置或值为0时表示关闭，则返回0
            return 0;
        }elseif(sysConfig('transfer_fee') > 1){ //当值大于1时表示具体数值，则返回该数值
            return sysConfig('transfer_fee');
        }else{
            $transfer = round(($money / 1000) * sysConfig('transfer_fee'), 2) ?? 0;
        }
		return $transfer;
    }
}

/*
 * 通过API接口获取行情
 */
if(!function_exists('getApiStock')) {
    function getApiStock($code,$model='stock'){
        //$recData['data'] = ThirdMarket($code,$model);
        /**********************腾讯证券网********************/
        $recData['data'] = TencentMarkets($code);
        //$recData['data'] = east_market($code,$model);
        switch ($model) {
    		case 'stock' ://单个股票
    		    $stockData = isset($recData['data']) ? $recData['data'][0] : [];
    		    break;
    		case 'stocks' ://多个股票
    		    $stockData = isset($recData['data']) ? $recData['data'] : [];
    		    break;
    		default :
    		    $stockData = isset($recData['data']) ? $recData['data'][0] : [];
    		    break;
        }
        return $stockData;
    }
}
if(!function_exists('ThirdMarket')) {
    function ThirdMarket($code){
        $url    = "http://".LOCAL_STOCK_HOST."/market";
        $data   = ['codes'=> $code];
    	$result = curls($url,$data);
    	//print_r($result);exit;
        $data   = json_decode($result, true);
        $json   = isset($data['data']) ? $data['data'] : [];
        return $json;
    }
}
//腾讯数据获取
if(!function_exists('TencentMarkets')) {
    function TencentMarkets($code){
    	$url = 'https://qt.gtimg.cn/q=' . $code;
    	//print_r($url);exit;
    	$output = curl($url);
    	$str  = mb_convert_encoding($output, 'utf-8', 'gbk');
    	$str  = str_replace(array("\r\n", "\r", "\n"), "", $str);
    	$t2   = explode('";', $str);
    	$json = [];
    	foreach ($t2 as $key => $val) {
            $array = explode("~", $val);
            if(isset($array[2])&&isset($array[3])&&isset($array[4])){
                $json[] = jsonQuotation(explode("~", $val));
            }else{
                continue;
            }
        }
    	return $json;
    }
}

//腾讯数据解析
if(!function_exists('jsonQuotation')) {
    function jsonQuotation($item) {
        $item[0]  = isset($item[0])?substr(str_replace('v_','', $item[0]), 0, 2):'';//交易所代号
        $item[80] = isset($item[30]) ? strtotime($item[30]) : time();
        return $item;
    }
}
/*
 * 通过API接口获取全部股票列表
 */
if(!function_exists('apiStockList')) {
    function apiStockList(){
        $url    = "http://".LOCAL_STOCK_HOST.":".LOCAL_STOCK_PORT."/api/market/getStockList";
    	$result = curls($url);
        $data   = json_decode($result, true);
        $json   = isset($data['data']) ? $data['data'] : [];
        return $json;
    }
}
/*
 * 获取新浪热门行业
 */
if(!function_exists('getSinahy')) {
    function getSinahy(){
		$output = curl('https://vip.stock.finance.sina.com.cn/q/view/newSinaHy.php');
		if($output){ 
    		$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));
    		}
    		return $res ?: false;
		}else{
		    return false;
		}
	}
}
//新浪股票热门行业分类排行
if(!function_exists('getSinaNodeclass')) {
	function getSinaNodeclass($node,$page=1,$num=50){
        $url  = 'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page='.$page.'&num='.$num.'&sort=symbol&asc=1&node='.$node;
        $json = curl($url);
        $data = json_decode($json, true);
        return $data ?: false;
    }
}
/*
 * 远程访问
 */
if (!function_exists('curls')) {
    function curls($url, $data=[]) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Access-Token:' . LOCAL_TRADING_TOKEN,
            'Client-Host:'  . RedisUtil::getClientHost(),
        ));
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}
/*协程方式Curl*/
if(!function_exists('curl')){
    function curl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
/*****************************************东方财富网接口**********************************************/
/*东方财富网获取个股数据*/
if(!function_exists('east_market')){
    function east_market($code,$lineModel){
        $data = east_line($code,$lineModel);
        //print_r($url);exit;
        return $data;
    }
}
/*东方财富网线路选择*/
if (!function_exists('east_line')) {
	function east_line($code,$lineModel){
	    switch ($lineModel) {
    		case 'stock'://单个股票地址
    		    $url  = "https://push2.eastmoney.com/api/qt/stock/details/get?secid=".fenxi_east($code)."&forcect=1&fields1=f1,f2,f3,f4,f5&fields2=f51,f52,f53,f54,f55&pos=-14&iscca=1&invt=2";
    		    $str  = curl($url);
    	        $str  = json_decode($str,true);
    	        $data = $str['data'];
    		    break;
    	    case 'stocks'://多个股票查询地址
    	        $codearr = explode(",",$code);
    	        $num = '';
    	        foreach ($codearr as $k => $v) {
    	            $num .= fenxi_east($v).",";
    	        }
    	        $url = "https://push2.eastmoney.com/api/qt/ulist/get?np=1&fltt=2&invt=2&fields=f2,f3,f4,f12,f13,f14,f18,f128&pn=1&pz=30&fid=&po=1&secids=".$num;
    	        $str = curl($url);
    	        $str = json_decode($str,true);
    	        foreach ($str['data']['diff'] as $k => $v) {
    	            $data[$k]['code'] = $v['f12'];
    	            $data[$k]['name'] = $v['f14'];
    	            $data[$k]['current_price']   = $v['f2'];
    	            $data[$k]['yesterday_price'] = $v['f18'];
    	            $data[$k]['price_rate']      = $v['f3'];
    	        }
    	        break;
	        default :
	            $data = [];
	            break;
	    }
	    
	    return $data;
	}
}
/*东方财富网分析前缀参数*/
if (!function_exists('fenxi_east')) {
	function fenxi_east($code){
		switch (substr($code, 0, 1)) {
		case '0':
			$d = '0.' . $code;
			break;
		case '3':
			$d = '0.' . $code;
			break;
		case '1':
			$d = '0.' . $code;
			break;
		case '2':
			$d = '0.' . $code;
			break;
		case '6':
			$d = '1.' . $code;
			break;
		case '5':
			$d = '1.' . $code;
			break;
		case '9':
			$d = '1.' . $code;
			break;
        case '4':
			$d = '0.' . $code;
			break;
		case '8':
			$d = '0.' . $code;
			break;
		}
		return $d;
	}
}
/*东方财务网获取全部沪深京A股股票列表*/
if(!function_exists('Eastmoney_CN_List')) {
    function Eastmoney_HSJ_List() {
        $host     = "http://43.push2.eastmoney.com";
        $url      = $host."/api/qt/clist/get?pn=1&pz=6000&po=1&np=1&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048&fields=f12,f13,f14";
    	$output   = curl($url);
        $response = json_decode($output,true);
        if(!$response['data']['diff']) return false;
        //dump($response['data']);exit;
        if(isset($response['data']['diff']) && !empty($response['data']['diff'])){
            $json['count'] = $response['data']['total'];
            foreach ($response['data']['diff'] as $item) {
                $cacheData['code']   = trim($item['f12']);
                $cacheData['name']   = $item['f14'];
                $cacheData['market'] = toMarket($item['f12']);
                $cacheData['pinyin'] = strtoupper(getPinYin($item['f14']));
                $json['items'][]       = $cacheData;
            }
        }
        return $json;
    }
}
/*东方财务网获取全部港股股票列表*/
if(!function_exists('Eastmoney_HK_List')) {
    function Eastmoney_HK_List() {
        $host     = "http://43.push2.eastmoney.com";
        $url      = $host."/api/qt/clist/get?pn=1&pz=5000&po=1&np=1fltt=2&invt=2&fid=f3&fs=m:128+t:3,m:128+t:4,m:128+t:1,m:128+t:2&fields=f12,f13,f14";
    	$output   = curl($url);
        $response = json_decode($output,true);
        if(!$response['data']['diff']) return false;
        //dump($response['data']);exit;
        if(isset($response['data']['diff']) && !empty($response['data']['diff'])){
            $json['count'] = $response['data']['total'];
            foreach ($response['data']['diff'] as $item) {
                $cacheData['code']   = trim($item['f12']);
                $cacheData['name']   = $item['f14'];
                $cacheData['market'] = toMarket($item['f12']);
                $cacheData['pinyin'] = strtoupper(getPinYin($item['f14']));
                $json['items'][]       = $cacheData;
            }
        }
        return $json;
    }
}
/*东方财务网获取全部美股股票列表*/
if(!function_exists('Eastmoney_US_List')) {
    function Eastmoney_US_List() {
        $host     = "http://43.push2.eastmoney.com";
        $url      = $host."/api/qt/clist/get?pn=1&pz=12000&po=1&np=1&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048&fields=f12,f13,f14";
    	$output   = curl($url);
        $response = json_decode($output,true);
        if(!$response['data']['diff']) return false;
        //dump($response['data']);exit;
        if(isset($response['data']['diff']) && !empty($response['data']['diff'])){
            $json['count'] = $response['data']['total'];
            foreach ($response['data']['diff'] as $item) {
                $cacheData['code']   = trim($item['f12']);
                $cacheData['name']   = $item['f14'];
                $cacheData['market'] = toMarket($item['f12']);
                $cacheData['pinyin'] = strtoupper(getPinYin($item['f14']));
                $json['items'][]       = $cacheData;
            }
        }
        return $json;
    }
}
/******************************************************************************************/
if(!function_exists('toType')) {
    function getPinYin($zh){
        // 特殊字符替换
        $search  = [
            ' ', '　', 'Ａ', 'Ｂ', 'Ｃ', 'Ｄ', 'Ｅ', 'Ｆ', 'Ｇ', 'Ｈ', 'Ｉ', 'Ｊ', 'Ｋ', 'Ｌ', 'Ｍ', 'Ｎ', 'Ｏ', 'Ｐ', 'Ｑ', 'Ｒ', 'Ｓ', 'Ｔ', 'Ｕ', 'Ｖ', 'Ｗ', 'Ｘ', 'Ｙ', 'Ｚ',
            'ａ', 'ｂ', 'ｃ', 'ｄ', 'ｅ', 'ｆ', 'ｇ', 'ｈ', 'ｉ', 'ｊ', 'ｋ', 'ｌ', 'ｍ', 'ｎ', 'ｏ', 'ｐ', 'ｑ', 'ｒ', 'ｓ', 'ｔ', 'ｕ', 'ｖ', 'ｗ', 'ｘ', 'ｙ', 'ｚ',
        ];
        $replace = [
            '', '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        ];
        $ret     = Chinese::toPinyin($zh, Pinyin::CONVERT_MODE_PINYIN_FIRST);
        $initial = implode('', $ret['pinyinFirst'][0]);
        $initial = strtoupper(str_replace($search, $replace, $initial));
        preg_match_all('/[a-zA-Z]+/',$initial,$result);
        return join('',$result[0]);
    }
}
if(!function_exists('get_between')) {
    function get_between($input, $start, $end)
    {
        $substr = substr($input, strlen($start) + strpos($input, $start), (strlen($input) - strpos($input, $end)) * (-1));
        return $substr;
    }
}