<?php

use App\Services\Common\CurlService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

//免费会员ID
define("DISABLE_ICO", 1);
if (!function_exists('theme_asset')) {

    /**
     * Generate an asset path for the application theme.
     *
     * @param  string $path
     * @param  bool $secure
     * @return string
     */
    function theme_asset($path, $secure = null)
    {
        $theme_root = 'themes/' . config('theme.theme') . '/assets/';
        return app('url')->asset($theme_root . $path, $secure);
    }
}

if (!function_exists('upload_asset')) {

    /**
     * Generate an asset path for the upload system.
     *
     * @param  string $path
     * @return string
     */
    function upload_asset($path)
    {
        return \Illuminate\Support\Facades\Storage::disk('public')->url($path);
    }
}

if (!function_exists('validator_check')) {

    /**
     * 根据验证规则返回值是否验证通过
     * @param $value
     * @param $rule
     * @return boolean
     */
    function validator_check($value, $rule)
    {
        $valid = validator(['check' => $value], ['check' => $rule]);
        if ($valid->fails()) {
            return false;
        }
        return true;
    }
}

if (!function_exists('render_template')) {

    /**
     * 渲染系统模板(短信,邮件)
     * @param string $template
     * @param array $params
     * @return mixed|string
     */
    function render_template(string $template, array $params)
    {
        if (empty($params)) {
            return $template;
        }
        preg_match_all('/\$\{(.*)\}/U', $template, $match_array);
        foreach ($match_array[0] as $key => $match) {
            $replace  = array_get($params, $match_array[1][$key], "({$match_array[1][$key]}未匹配)");
            $template = str_replace($match, $replace, $template);
        }
        return $template;
    }
}

/**
 *  移动端请求判断
 */
function isMobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备
    if (isset($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法,判断手机发送的客户端标志,兼容性有待提高
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = ['nokia',
                           'sony',
                           'ericsson',
                           'mot',
                           'samsung',
                           'htc',
                           'sgh',
                           'lg',
                           'sharp',
                           'sie-',
                           'philips',
                           'panasonic',
                           'alcatel',
                           'lenovo',
                           'iphone',
                           'ipod',
                           'blackberry',
                           'meizu',
                           'android',
                           'netfront',
                           'symbian',
                           'ucweb',
                           'windowsce',
                           'palm',
                           'operamini',
                           'operamobi',
                           'openwave',
                           'nexusone',
                           'cldc',
                           'midp',
                           'wap',
                           'mobile',
        ];
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法,因为有可能不准确,放到最后判断
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

function upload_img_path($path, $secure = null)
{
    if (preg_match('/^images\//', $path)) {
        $img_path = 'uploads/';
        return app('url')->asset($img_path . $path, $secure);
    } else {
        return $path;
    }

}

function upload_path($path, $secure = null)
{
    $img_path = 'uploads/';
    return app('url')->asset($img_path . $path, $secure);
}

function public_data_path($path, $secure = null)
{
    $img_path = '';
    return app('url')->asset($img_path . $path, $secure);
}

function change_datetime_format($datetime, $format = "Y-m-d H:i:s")
{
    $date = '';
    if ($datetime) {
        $date = date($format, strtotime($datetime));
    }
    return $date;
}

//截取字符
function cut_str($sourcestr, $cutlength, $start = 0, $dot = '')
{
    $returnstr     = '';
    $i             = 0;
    $n             = 0;
    $str_length    = strlen($sourcestr);
    $mb_str_length = mb_strlen($sourcestr, 'utf-8');
    while (($n < $cutlength) && ($i <= $str_length)) {
        $temp_str = substr($sourcestr, $i, 1);
        $ascnum   = ord($temp_str);
        if ($ascnum >= 224) {
            $returnstr = $returnstr . substr($sourcestr, $i, 3);
            $i         = $i + 3;
            $n++;
        } elseif ($ascnum >= 192) {
            $returnstr = $returnstr . substr($sourcestr, $i, 2);
            $i         = $i + 2;
            $n++;
        } elseif (($ascnum >= 65) && ($ascnum <= 90)) {
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i         = $i + 1;
            $n++;
        } else {
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i         = $i + 1;
            $n         = $n + 0.5;
        }
    }
    if ($mb_str_length > $cutlength) {
        $returnstr = $returnstr . $dot;
    }
    return $returnstr;
}

/**
 * [url_rewrite 伪静态]
 * @param  [type]    $alias     [description]
 * @param  [array]   $get       [传值]
 * @param  boolean $rewrite [是否开启伪静态]
 * @return [string]             [链接]
 */
function url_rewrite($alias = null, $get = null, $subsite_id = 0, $rewrite = true)
{
    //获取页面信息
    $page_list = App\Repositories\PageRepository::pageCache();
    $url       = $url_prefix = '';

    if (array_get($get, 'key') && config('aix.system.site_safety.site_vo_code.site_rewrite') == 1) {
        $get['key'] = urlencode($get['key']);
    }
    //$subsite_set = config('aix.system.site_safety.subsite.close_subsite');
    //$subsite_id = Cache::get('subsite_id');
    /*if (!$subsite_set) {
        $url_prefix = subsite_url($alias, $url, $subsite_id);
        preg_match("/^((https|http|ftp|rtsp|mms):\/\/)?([^(\/|\?)]+)/i", $url_prefix, $matches);
        $http_host = $matches ? $matches[3] : '';
    } else {
        $http_host = \Illuminate\Support\Facades\Request::server('HTTP_HOST');
    }*/
    $http_host = \Illuminate\Support\Facades\Request::server('HTTP_HOST');
    if ($page_list[$alias]['url'] == '0' || $rewrite == false) { //原始链接
        if ($page_list[$alias]->route && $page_list[$alias]->route != '/') {
            $url = route($page_list[$alias]->route);
        } else {
            $url = '/';
        }
    } else {
        if ($url = $page_list[$alias]['rewrite']) {
            if ($page_list[$alias]['pagetpye'] == '2' && empty($get['page'])) {
                $get['page'] = 1;
            }
            if ($get) {
                foreach ($get as $k => $val) {
                    $data['($' . $k . ')'] = $val;
                }
                $url = strtr($url, $data);
            }
            $url = preg_replace('/\(\$(\w+)\)/', '', $url);
        } else {
            if ($page_list[$alias]->route && $page_list[$alias]->route != '/') {
                $url = $page_list[$alias]->route;
                //$url = route($page_list[$alias]->route);
            } else {
                $url = '';
            }
        }
    }
    return $url_prefix . $url;
}

//添加手机端时需要修改
//后台配置分站信息时需要修改
function subsite_url($alias, $url, $subsite_id)
{
    return config('aix.system.site.site.site_domain') . $url;
}

/**
 * 友好时间
 */
function sub_day($endday, $staday, $range = '')
{
    $value = $endday - $staday;
    if ($value < 0) {
        return '';
    } elseif ($value >= 0 && $value < 59) {
        return ($value + 1) . "秒";
    } elseif ($value >= 60 && $value < 3600) {
        $min = intval($value / 60);
        return $min . "分钟";
    } elseif ($value >= 3600 && $value < 86400) {
        $h = intval($value / 3600);
        return $h . "小时";
    } elseif ($value >= 86400 && $value < 86400 * 30) {
        $d = intval($value / 86400);
        return intval($d) . "天";
    } elseif ($value >= 86400 * 30 && $value < 86400 * 30 * 12) {
        $mon = intval($value / (86400 * 30));
        return $mon . "月";
    } else {
        $y = intval($value / (86400 * 30 * 12));
        return $y . "年";
    }
}

/**
 * 时间转为上、下午
 */
if (!function_exists('PA')) {
    function PA($data)
    {
        $data = str_replace('AM', '上午', $data);
        $data = str_replace('PM', '下午', $data);
        return $data;
    }
}
/**
 * [获取职位所属分站subsite_id]
 * @return [数组] [job] 职位信息
 * 等后台设置了分站信息时再完善此功能
 */
function get_jobs_subsite_id($job)
{
    if (config('aix.system.site_safety.subsite.close_subsite')) {
        return '';
    } else {
        $subsite_id = 0;
    }
    return $subsite_id;
}

/**
 * 等后台设置了分站信息时再完善此功能
 */
function check_url($now_subsite_id, $subsite_id)
{
    if (!$subsite_id) {
        $subsite_id = 0;
    }
    if ($now_subsite_id != $subsite_id) {
        throw new ResponseException('页面不存在', [], '404');
    }
}

/**
 * 时间格式变换
 */
function daterange($endday, $staday, $format = 'Y-m-d', $color = '', $range = 3)
{
    $value = $endday - $staday;
    if ($value < 0) {
        return '';
    } elseif ($value >= 0 && $value < 59) {
        $return = ($value + 1) . "秒前";
    } elseif ($value >= 60 && $value < 3600) {
        $min    = intval($value / 60);
        $return = $min . "分钟前";
    } elseif ($value >= 3600 && $value < 86400) {
        $h      = intval($value / 3600);
        $return = $h . "小时前";
    } elseif ($value >= 86400) {
        $d = intval($value / 86400);
        if ($d > $range) {
            return date($format, $staday);
        } else {
            $return = $d . "天前";
        }
    }
    if ($color) {
        $return = "<span id=\"r_time\" style=\"color:{$color}\">" . $return . "</span>";
    }
    return $return;
}

function date_format_new($time)
{
    $sec = Carbon::now()->diffInSeconds(date('Y-m-d H:i:s', $time));
    return Carbon::now()->addSeconds($sec)->diffForHumans();

}

/**
 * 获取地区名
 * @param $id
 * @return mixed
 */
if (!function_exists('get_district_cn')) {
    function get_district_cn($id)
    {
        $district_cn = [];
        $district    = explode('.', $id);
        foreach ($district as $key => $val) {
            if ($val) {
                $dist_cn       = App\Models\CategoryDistrict::where('id', $val)->select(['name'])->first();
                $district_cn[] = $dist_cn['name'];
            }
        }
        return implode('/', $district_cn);
    }
}
if (!function_exists('get_tag_cn')) {
    function get_tag_cn($id)
    {
        $tag_cn = [];
        $tag    = explode(',', $id);
        foreach ($tag as $key => $val) {
            $job_tag_cn = App\Models\Category::where('id', $val)->select(['demand'])->first();
            $tag_cn[]   = $job_tag_cn['demand'];
        }
        return implode(',', $tag_cn);
    }
}

if (!function_exists('getDistrict')) {
    function getDistrict($id)
    {
        $parent_id = App\Models\CategoryDistrict::where('id', $id)->select(['parent_id', 'id'])->first();
        $parents   = App\Models\CategoryDistrict::where('id', $parent_id->parent_id)->select(['parent_id', 'id'])->first();
        return $parents->parent_id . '.' . $parent_id->parent_id . '.' . $id;
    }
}
if (!function_exists('get_job_category_cn')) {
    function get_job_category_cn($id)
    {
        $job_category = explode('.', $id);
        foreach ($job_category as $key => $val) {
            $category_cn = App\Models\CategoryJobs::where('id', $val)->select(['name'])->first();
            $cate_cn[]   = $category_cn['name'];

        }
        return implode('/', $cate_cn);
    }
}
if (!function_exists('get_job_category')) {
    function get_job_category($id)
    {
        $job_category = \App\Models\CategoryJobs::where('id', $id)->select(['name'])->first();
        return $job_category['name'];
    }
}

if (!function_exists('get_category')) {
    function get_category($id)
    {
        $category = \App\Models\Category::where('id', $id)->select(['demand'])->first();
        return $category ? $category['demand'] : null;
    }
}

if (!function_exists('get_category_major')) {
    function get_category_major($id)
    {
        $category = \App\Models\CategoryMajor::where('id', $id)->select(['name'])->first();
        return $category ? $category['name'] : null;
    }
}

/**
 * [ddate 时间差]
 */
function ddate($s, $e)
{
    $starttime    = strtotime($s);
    $endtime      = strtotime($e);
    $startyear    = date('Y', $starttime);
    $startmonth   = date('m', $starttime);
    $endyear      = date('Y', $endtime);
    $endmonth     = date('m', $endtime);
    $return       = '';
    $return_year  = $endyear - $startyear;
    $return_month = $endmonth - $startmonth;
    if ($return_month < 0) {
        $return_month += 12;
        $return_year  -= 1;
    }

    if ($return_year > 0) {
        $return .= $return_year . '年';
    }
    if ($return_month > 0) {
        $return .= $return_month . '个月';
    }
    return $return;
}

//两个时间相差天数
function diffBetweenTwoDays($day1, $day2)
{
    $day1    = date("Y-m-d", strtotime($day1));
    $day2    = date("Y-m-d", strtotime($day2));
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);

    if ($second1 < $second2) {
        $tmp     = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}

function _get_total_work_duration($list)
{
    $total_year  = 0;
    $total_month = 0;
    $return      = '';
    if (!empty($list)) {
        foreach ($list as $key => $value) {
            $current_duration = strpos($value['duration'], '年');
            if ($current_duration === false) {
                $total_month += intval($value['duration']);
            } else {
                $arr         = explode("年", $value['duration']);
                $total_year  += intval($arr[0]);
                $total_month += intval($arr[1]);
            }
        }
    }
    $add_year    = intval($total_month / 12);
    $total_year  += $add_year;
    $total_month = intval($total_month % 12);
    if ($total_year > 0) {
        $return .= $total_year . '年';
    }
    if ($total_month > 0) {
        $return .= $total_month . '个月';
    }
    return $return;
}

function _get_duration($list)
{
    if (!empty($list)) {
        foreach ($list as $key => $value) {
            $start                  = $value['startyear'] . '-' . $value['startmonth'];
            $end                    = $value['endyear'] . '-' . $value['endmonth'];
            $list[$key]['duration'] = ddate($start, $end);
        }
    }
    return $list;
}

function contact_hide($data, $IsWhat = 2)
{
    if ($IsWhat == 1) {
        return preg_replace('/([0[0-9]{2,3}[-]?[1-9]]|[1-9])[0-9]{2,4}([0-9]{3}[-]?[0-9]?)/i', '$1****$2', $data);
    } elseif ($IsWhat == 2) {
        return preg_replace('/(1[34578]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $data);
    } elseif ($IsWhat == 3) {
        $email_array = explode("@", $data);
        $n           = mb_strlen($email_array[0], 'utf-8');
        return str_pad(substr($email_array[0], 0, intval($n / 2)), $n, '*') . $email_array[1];
    } else {
        $n   = mb_strlen($data, 'utf-8');
        $str = str_pad('', intval($n / 2), '*');
        return str_replace(substr($data, intval($n / 4), intval($n / 2)), $str, $data);
    }
}

/**
 * 根据生日计算年龄
 * @param string $birthday 出生年月日
 * @return string
 */
if (!function_exists('birth_to_age')) {
    function birth_to_age($birthday)
    {
        $age = strtotime($birthday);
        if ($age === false) {
            return false;
        }
        list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
        list($y2, $m2, $d2) = explode("-", date("Y-m-d"));
        $age = $y2 - $y1;
        if ((int)($m2 . $d2) < (int)($m1 . $d1)) {
            $age -= 1;
        }

        return $age;
    }
}


/**
 * 时间转换
 * @param $time
 * @return bool|false|string
 */
if (!function_exists('fdate')) {
    function fdate($time)
    {
        $sec = Carbon::now()->diffInSeconds(date('Y-m-d H:i:s', $time));
        return Carbon::now()->addSeconds($sec)->diffForHumans();
    }
}


/**
 * 获取图片
 */
if (!function_exists('attach')) {
    function attach($attach, $type)
    {
        if (empty($attach)) {
            return false;
        }
        if (false === strpos($attach, 'http://')) {
            //本地附件
            return '/data/upload/' . $type . '/' . $attach;
        } else {
            //URL链接
            return $attach;
        }
    }
}

if (!function_exists('getCityInfo')) {
    function getCityInfo($ids)
    {
        if (!$ids) {
            return ['district' => '', 'district_cn' => ''];
        }
        $categoryDistrict = app('App\Repositories\CategoryDistrictRepository');
        $city             = $categoryDistrict->getDistrictCache('all');

        if (false == $city_cate = Cache::get('city_search_list')) {
            $city_cate = $categoryDistrict->citySearchCache();
        }
        $spell = $categoryDistrict->cityCateCache();
        foreach (explode(',', $ids) as $val) {
            $a = array_filter(explode('_', $city_cate[$val]));
            $c = count($a);
            if (!$c) {
                continue;
            } elseif ($c == 1) {
                $district_cn[] = $city[0][$a[0]];
            } elseif ($c > 1) {
                $district_cn[] = $city[$a[$c - 2]][$a[$c - 1]];
            }
            foreach ($a as $key => $v) {
                $b[] = $key == 0 ? $city[0][$v] : $city[$a[$key - 1]][$v];
                $s[] = $spell['id'][$v]['spell'];
            }
            $district_cn_all[] = implode('/', $b);
            $district[]        = implode('.', $a);
            $district_spell[]  = implode('.', $s);
        }
        return ['district' => implode(',', $district), 'district_cn_all' => implode(',', $district_cn_all), 'district_cn' => implode(',', $district_cn), 'district_spell' => implode(',', $district_spell)];
    }
}

/**
 * 访问百度api获取当前坐标
 */
function _get_baidumap_api()
{
    $api          = 'https://api.map.baidu.com/location/ip';
    $data['ip']   = '117.136.67.3';
    $data['ak']   = config('aix.system.map.map.map_ak');
    $data['coor'] = 'bd09ll';
    $data['s']    = 1;
    $result       = https_request($api, $data);
    return $result;
}

function https_request($url, $data = null,$header = null)
{
    if (function_exists('curl_init')) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        if(!empty($header)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            curl_setopt($curl, CURLOPT_HEADER, 0);//返回response头部信息
        }
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    } else {
        return false;
    }
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? [$ip, $long] : ['0.0.0.0', 0];
    return $ip[$type];
}

/**
 *计算坐标点周围某段距离的正方形的四个点
 * @param lng float 经度
 * @param lat float 纬度
 * @param distance float 该点所在圆的半径,该圆与此正方形内切,默认值为0.5千米
 * @return array 正方形的四个点的经纬度坐标
 */
function square_point($lng, $lat, $distance = 0.5)
{
    $earth_radius = 6378.138;
    $dlng         = 2 * asin(sin($distance / (2 * $earth_radius)) / cos(deg2rad($lat)));
    $dlng         = rad2deg($dlng);
    $dlat         = $distance / $earth_radius;
    $dlat         = rad2deg($dlat);
    return [
        'lt' => ['lat' => $lat + $dlat, 'lng' => $lng - $dlng],
        'rt' => ['lat' => $lat + $dlat, 'lng' => $lng + $dlng],
        'lb' => ['lat' => $lat - $dlat, 'lng' => $lng - $dlng],
        'rb' => ['lat' => $lat - $dlat, 'lng' => $lng + $dlng],
    ];
}


/**
 * @return string
 * @throws ErrorException
 */
function getAddressByIp()
{
    $ip = request()->ip();
    if (cache()->has($ip . "_address")) {
        return cache($ip . "_address");
    }
    $curl = new CurlService();
    $curl->setOpt(CURLOPT_HTTPHEADER, [
        'Content-Type:application/json',
        'charset=utf-8',  //编码
    ]);
    $curl->setTimeout(2);
    $curl->setOpt(CURLOPT_SSL_VERIFYHOST, 0);
    $curl->setOpt(CURLOPT_SSL_VERIFYPEER, 0);
    $res = $curl->get('http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip);
    try {
        $res = json_decode($res);
        if (isset($res->data->region)) {
            $address = $res->data->region . '-' . $res->data->city;
            cache()->put($ip . "_address", $address, 24 * 60);
            return $address;
        }
        return "未知";
    } catch (\Exception $exception) {
        return "未知";
    }
}

function isCreditNo($vStr)
{
    $vCity = [
        '11', '12', '13', '14', '15', '21', '22',
        '23', '31', '32', '33', '34', '35', '36',
        '37', '41', '42', '43', '44', '45', '46',
        '50', '51', '52', '53', '54', '61', '62',
        '63', '64', '65', '71', '81', '82', '91',
    ];
    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
    if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
    $vStr    = preg_replace('/[xX]$/i', 'a', $vStr);
    $vLength = strlen($vStr);
    if ($vLength == 18) {
        $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
    } else {
        $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
    }
    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
    if ($vLength == 18) {
        $vSum = 0;
        for ($i = 17; $i >= 0; $i--) {
            $vSubStr = substr($vStr, 17 - $i, 1);
            $vSum    += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
        }
        if ($vSum % 11 != 1) return false;
    }
    return true;
}

function getResumeStatus()
{
    if (config('aix.personal_set.per_set.show_set.resume_display') == 2) {
        $date = [1, 2];
    } else {
        $date = [2];
    }
    return $date;
}


function getJobsStatus()
{
    if (config('aix.companyset.comset.show_set.jobs_display') == 1) {
        $date = [1];
    } else {
        $date = [1, 2];
    }
    return $date;
}


function getLastDates($counts)
{
    $days = [];
    for ($i = $counts; $i >= 0; $i--) {
        $days[] = date("Y-m-d", strtotime('-' . $i . 'day'));
    }
    return $days;
}

function string_to_array($delimiters, $str, $default = [])
{
    if (empty($str)) {
        return $default;
    }
    $delimiter = is_array($delimiters) ? $delimiters[0] : $delimiters;
    if (is_array($delimiters)) {
        $str = str_replace($delimiters, $delimiter, $str);
    }
    return array_map('change_number_to_int', explode($delimiter, $str));
}

function change_number_to_int($val)
{
    if (is_numeric($val)) {
        return intval($val);
    }
    return $val;
}

/**
 * 触发搜索引擎更新事件
 * @param string $model
 * @param array|string $where
 * @param string $operate_type
 */
function event_search_update(string $model, $where, string $operate_type)
{
    event(new \App\Search\Events\SearchUpdateEvent($model, $where, $operate_type));
}

function getComUserName($company_id)
{
    $company = \App\Models\Company::where('id', $company_id)->select(['username'])->first();
    return $company->username;
}

function handle_seo_info($seoInfo)
{

    if (isset($seoInfo) || !is_array($seoInfo)) {
        return false;
    }
    //var_dump($pageSeo);
    $pageSeoJson = json_encode($seoInfo);
    //替换系统配置变量
    $searchs     = ['{#site_name}', '{#site_domain}', '{#site_keywords}', '{#site_description}'];
    $replaces    = [subsite_config('aix.system.site.site.site_name'),
                    config('aix.system.site.site.site_domain'),
                    subsite_config('aix.system.site.site.site_keyword'),
                    subsite_config('aix.system.site.site.site_description')];
    $pageSeoJson = str_replace($searchs, $replaces, $pageSeoJson);
    //var_dump($pageSeoJson);
    //替换传递变量
    $seoData = View::shared('seo_data', []);
    preg_match_all('/(?:\{\$)(.*?)(?:\})/', $pageSeoJson, $matchers);
    //var_dump($matchers);
    if ($matchers) {
        foreach ($matchers[1] as $index => $template) {
            $replace_value = "";
            if (count(explode('.', $template)) > 1) {
                list($subject, $property) = explode('.', $template, 2);
                $replace_value = isset($seoData[$subject][$property]) ? $seoData[$subject][$property] : "";
            }
            $pageSeoJson = str_replace($matchers[0][$index], $replace_value, $pageSeoJson);
        }
    }
    //var_dump(json_decode($pageSeoJson, true));
    return json_decode($pageSeoJson, true);
}

/**
 * 根据域名获取分站id
 * @return bool|int
 */
function get_subsite_id()
{
    $subsiteService = app('App\Services\SubsiteService');
    return $subsiteService->getSiteId();
}

function get_subsite_sitename($subsite_id)
{
    $subsiteRepository = app('App\Repositories\SubsiteRepository');
    $result            = $subsiteRepository->find($subsite_id);
    return $result->sitename;
}

/**
 * 根据域名获取分站域名
 * @return bool|int
 */
function get_subsite_domain($subsite_id = 0)
{
    $subsiteService = app('App\Services\SubsiteService');
    return $subsiteService->getSubsiteDomain($subsite_id);
}

/**
 * 根据用户获取剩余分站信息。
 * @param $user
 * @return mixed
 */
function get_subsite_by_user($user)
{
    $subsiteService = app('App\Services\SubsiteService');
    return $subsiteService->getSubsite($user);
}


/**
 * 根据所有站点信息。
 * @param $user
 * @return mixed
 */
function get_all_subsite()
{
    $subsiteService = app('App\Services\SubsiteService');
    return $subsiteService->getAllSubsite();
}

function get_subsite_open()
{
    return get_all_subsite() ? true : false;
}


/**
 * 下截文件到本地
 * @param $url
 * @param $path
 * @return string
 */
function download($url, $path)
{
    $content = file_get_contents($url);
    \Illuminate\Support\Facades\Storage::disk('public')->put($path, $content);
    return \Illuminate\Support\Facades\Storage::disk('public')->url($path);
}


if (!function_exists('get_sitename')) {
    function get_sitename($id)
    {
        $subsiteRepository = app('App\Repositories\SubsiteRepository');
        $result            = $subsiteRepository->findWhereIn('id', $id);
        foreach ($result as $key => $val) {
            $res[] = $val->sitename;
        }
        return implode(',', $res);
    }
}

/**
 * 判断是否是在微信公众号打开的
 */
if (!function_exists('is_weixin')) {
    function is_weixin()
    {
        if (Str::contains(request()->userAgent(), ["MicroMessenger"])) {
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 判断是否是在IE浏览器打开
 */
if (!function_exists('is_ie')) {
    function is_ie()
    {
        if (Str::contains(request()->userAgent(), ["Trident", "MSIE"])) {
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 是否访问手机端路由
 * @return bool
 */
function is_mobile_route()
{
    if (Str::contains(request()->route()->getPrefix(), 'mobile')) {
        return true;
    }
    return false;
}

/**
 * 是否访问硬件平板路由
 * @return bool
 */
function is_pad_route()
{
    if (Str::contains(request()->route()->getPrefix(), 'pad')) {
        return true;
    }
    return false;
}

/**
 * 是否访问才情系统
 * @return bool
 */
function is_statistics_route()
{
    if (Str::contains(request()->route()->getPrefix(), 'statistics')) {
        return true;
    }
    return false;
}


/**
 * 获取分站的配置,如果没有则返回正常的系统配置
 * @param $key
 * @param null $default
 * @param null $subsite_id 指定分站id,否则会自动获取
 * @return \Illuminate\Config\Repository|mixed
 */
function subsite_config($key, $default = null, $subsite_id = null)
{
    $subsiteService = app('App\Services\SubsiteService');
    return $subsiteService->getSubsiteConfig($key, $default, $subsite_id);
}

if (!function_exists('format_wage')) {
    function format_wage($wage)
    {
        $format_wae = preg_replace('/([\x80-\xff]*)/i', '', $wage);
        $format_wae = str_replace('/', '', $format_wae);
        return $format_wae;
    }
}

if (!function_exists('explode_wage')) {
    function explode_wage($wage)
    {
        if (preg_match_all('(\d+)', $wage, $reg)) {
            $reg = $reg[0];
            $min = $reg[0];
            if (count($reg) > 1) {
                $max = $reg[1];
            } else {
                $max = 0;
            }
        } else {
            $min = $wage;
            $max = 0;
        }
        $format_wae = [
            ['wage_min', '>=', $min],
            ['wage_max', '<=', $max],
        ];
        return $format_wae;
    }
}

/*
    字段单独验证
*/
function fieldRegex($value, $rule)
{
    $validate = [
        'require'  => '/.+/',
        'email'    => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
        'mobile'   => '/^13[0-9]{9}$|14[0-9]{9}$|15[0-9]{9}$|18[0-9]{9}$|17[0-9]{9}$|19[0-9]{9}$/',
        'tel'      => '/^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$/',
        'url'      => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
        'currency' => '/^\d+(\.\d+)?$/',
        'number'   => '/^\d+$/',
        'zip'      => '/^\d{6}$/',
        'integer'  => '/^[-\+]?\d+$/',
        'double'   => '/^[-\+]?\d+(\.\d+)?$/',
        'english'  => '/^[A-Za-z]+$/',
        'img'      => '(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/',
        'in'       => '/^(\d{1,10},)*(\d{1,10})$/',
        'qq'       => '/^[1-9]*[1-9][0-9]*$/',
    ];
    // 检查是否有内置的正则表达式
    if (isset($validate[strtolower($rule)]))
        $rule = $validate[strtolower($rule)];
    return preg_match($rule, $value) === 1;
}

if (!function_exists('dealContactPhone')) {
    function dealContactPhone($phone)
    {
        $landline_tel = explode('-', $phone);
        $tel_arr      = [];
        foreach ($landline_tel as $k => $v) {
            if ($v) {
                $tel_arr[] = $v;
            }
        }
        return implode('-', $tel_arr);
    }
}


function getCompanyName($company_id)
{
    $Company = \App\Models\Company::find($company_id);
    return $Company;
}

/**
 * @param $uid
 * @param $utype 1企业, 2个人
 * @return string
 */
function hashid_encode($uid, $utype)
{
    if ($utype == 1) {
        $uid = '10' . $uid;
    } else {
        $uid = '20' . $uid;
    }
    $hashid = new \Hashids\Hashids(config('app.name'), 16);
    return $hashid->encode($uid);
}

/**
 * @param $hash_id
 * @return mixed
 */
function hashid_decode($hash_id)
{
    $hashid = new \Hashids\Hashids(config('app.name'), 16);

    $uid = $hashid->decode($hash_id);
    if (!$uid) {
        return false;
    }
    $res['utype'] = substr($uid[0], 0, 1);
    $res['id']    = substr($uid[0], 2);
    return $res;
}

/**
 * 获取二维码
 * @param string $content 二维码内容
 * @param bool|string $useLogo 是否使用logo,默认使用网站logo,如果使用自定义可以传logo地址(绝对).
 * @param int $htmlSize img标签的大小
 * @param int $htmlMargin img标签的边距
 * @param int $imageSize 二维码图片的大小
 * @param int $imageMargin 二维码图片的边距
 * @return string 返回html img标签
 */
function get_qrcode_html(
    string $content,
    $useLogo = false,
    int $htmlSize = 250,
    int $htmlMargin = 0,
    int $imageSize = 300,
    int $imageMargin = 2
)
{
    if ($useLogo !== false && !file_exists($useLogo)) {
        $useLogo = public_path('images/logo.png');
    }

    $qrcode = \SimpleSoftwareIO\QrCode\Facades\QrCode::format('png')
        ->size($imageSize)
        ->margin($imageMargin)
        ->encoding('utf-8')
        ->errorCorrection("Q");
    if ($useLogo !== false) {
        $qrcode->merge($useLogo, 0.2, true);
    }
    $img = base64_encode($qrcode->generate($content));

    return "<img style='width:{$htmlSize}px;height:{$htmlSize}px;margin:{$htmlMargin};' src='data:image/png;base64,{$img}'>";
}


/**
 * 获取二维码
 * @param string $content 二维码内容
 * @param bool|string $useLogo 是否使用logo,默认使用网站logo,如果使用自定义可以传logo地址.
 * @param int $size 二维码图片大小
 * @param int $margin 二维码图片边距
 * @param string $saveFloder 保存的文件夹,相对路径,可以多层,例如 'image/','image/qrcode/'
 * @return string 返回图片的相对地址.
 */
function get_qrcode_file(string $content, $useLogo = false, int $size = 240, int $margin = 2, $saveFloder = '')
{
    if ($useLogo !== false && !file_exists($useLogo)) {
        $useLogo = public_path('images/logo.png');
    }
    //生成png,返回图片url
    $filename = 'qrcode/' . $saveFloder . md5($content . $useLogo . $size . $margin) . '.png';

    if (\Illuminate\Support\Facades\Storage::disk('public')->exists($filename)) {
        return $filename;
    }
    $qrcode = \SimpleSoftwareIO\QrCode\Facades\QrCode::format('png')
        ->size($size)
        ->margin($margin)
        ->encoding('utf-8')
        ->errorCorrection("Q");
    if ($useLogo !== false) {
        $qrcode->merge($useLogo, 0.2, true);
    }
    $img = $qrcode->generate($content);
    \Illuminate\Support\Facades\Storage::disk('public')->put($filename, $img);
    return $filename;
}

if (!function_exists('get_sex')) {
    /**
     *  根据身份证号码获取性别
     * @param string $idcard 身份证号码
     * @return int $sex 性别 1男 2女 0未知
     */
    function get_sex($idcard)
    {
        if (empty($idcard)) return null;
        $sexint = (int)substr($idcard, 16, 1);
        return $sexint % 2 === 0 ? '女' : '男';
    }
}

if (!function_exists('get_birthday')) {
    /**
     *  根据身份证号码获取生日
     * @param string $idcard 身份证号码
     * @return $birthday
     */
    function get_birthday($idcard)
    {
        if (empty($idcard)) return null;
        $bir  = substr($idcard, 6, 8);
        $year = (int)substr($bir, 0, 4);
        return $year;
    }
}


function apiAddress($address)
{
    $url = 'https://api.map.baidu.com/geocoder/v2/?address=' . $address . '&output=json&ak=' . subsite_config('aix.system.map.map.map_ak') . "&s=1";
    try {
        if ($result = file_get_contents($url)) {
            $data = [];
            $res  = json_decode($result, true);
            if ($res['status'] == 0) {
                $results     = $res['result'];
                $data['lng'] = $results['location']['lng'];
                $data['lat'] = $results['location']['lat'];
            }
            return $data;
        }
    } catch (Exception $exception) {
        return [];
    }

}

if (!function_exists('landline_tel')) {
    /**
     *  座机去掉最后一个-
     * @param string $landline_tel 座机号码
     * @return $landline_tel
     */
    function landline_tel($landline_tel)
    {
        if (empty($landline_tel)) return null;
        $arr_tel      = explode('-', $landline_tel);
        $landline_tel = '';
        if (isset($arr_tel[0]) && $arr_tel[0] != '') {
            $landline_tel .= $arr_tel[0];
        }
        if (isset($arr_tel[1]) && $arr_tel[1] != '') {
            $landline_tel .= '-' . $arr_tel[1];
        }
        if (isset($arr_tel[2]) && $arr_tel[2] != '') {
            $landline_tel .= '-' . $arr_tel[2];
        }
        return $landline_tel;
    }
}

if (!function_exists('getUser')) {
    /**
     *  获取登陆信息
     * @return $user
     */
    function getUser()
    {
        $user = [];
        if (auth('web-member')->check()) {
            $user = auth('web-member')->user();
        } elseif (auth('web-company')->check()) {
            $user = auth('web-company')->user();
        }
        return $user;
    }
}

if (!function_exists('getOrderType')) {
    /**
     *  获取订单类型
     * @return $user
     */
    function getOrderType($id)
    {
        $ordertype = [
            1 => "套餐升级", 2 => "充值积分", 3 => "简历置顶", 4 => "醒目标签", 5 => "简历模板", 6 => "简历包", 7 => "短信包", 8 => "职位置顶", 9 => "职位紧急", 10 => "企业模板", 12 => "预约刷新职位", 13 => "职位刷新", 14 => "简历下载", 15 => "职位包", 16 => "招聘会包",
        ];
        if (!isset($ordertype[$id])) {
            return "其他";
        } else {
            return $ordertype[$id];

        }
    }
}

if (!function_exists('isExpire')) {
    /**
     *  判断套餐是否到期
     * @return $user
     */
    function isExpire(\App\Models\MembersSetmeal $mySetmeal): bool
    {
        if (empty($mySetmeal)) {
            return true;
        }
        if (strtotime($mySetmeal->endtime) < time() && $mySetmeal->endtime != 0) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('getMsImg')) {
    /**
     *  获取套餐图片
     * @return $user
     */
    function getMsImg($mySetmeal_id = null): string
    {
        if (empty($mySetmeal_id)) {

            $user         = auth('web-company')->user();
            $MS           = \App\Models\MembersSetmeal::where('uid', $user->id);
            $mySetmeal_id = $MS->setmeal_img;

        }
        $result = Cache::get('setmeals' . $mySetmeal_id);

        if (null === $result) {
            $setmeal = \App\Models\Setmeal::find($mySetmeal_id);
            Cache::put('setmeals' . $mySetmeal_id, serialize($setmeal), 86400);

        } else {
            $setmeal = unserialize($result);
        }

        if (!empty($setmeal->setmeal_img)) { //上传图标不为空
            return "/storage/" . $setmeal->setmeal_img;
        } else {
            return attach($setmeal->id . '.png', 'setmeal_img');
        }


    }
}


/**
 * @param $data
 * @param int $code
 * @param string $status
 * @return \Illuminate\Http\JsonResponse
 * ajax 成功的请求返回
 */
if (!function_exists('AjaxSuccess')) {
    function AjaxSuccess($data, $code = 200, $message = "success")
    {
        return response()->json(['status' => $code, 'msg' => $message, 'data' => $data]);

    }
}
/**
 * @param $data
 * @param int $code
 * @param string $status
 * @return \Illuminate\Http\JsonResponse
 * ajax 失败的请求返回
 */
if (!function_exists('AjaxError')) {
    function AjaxError($data, $status = 0)
    {
        return response()->json(['status' => $status, 'msg' => $data]);
    }
}
function vali_person_reg($card_t_cn, $value)
{
    if ($card_t_cn == 306) {
        if (isCreditNo($value)) {
            return true;
        }
    } elseif ($card_t_cn == 307) {
        if (isCreditNo($value, $card_t_cn)) {
            return true;
        }
    } elseif ($card_t_cn == 308) {
        if (isCreditNo($value, $card_t_cn)) {
            return true;
        }
    } elseif ($card_t_cn == 309) {
        if (isCreditNo($value, $card_t_cn)) {
            return true;
        }
    } elseif ($card_t_cn == 310) {
        if (preg_match('/^H[0-9]{10}$/', $value)) {
            return true;
        }
    } elseif ($card_t_cn == 311) {
        if (preg_match('/^[0-9]{8}$/', $value)) {
            return true;
        }
    } elseif ($card_t_cn == 312) {
        if (preg_match('/^M[0-9]{10}$/', $value)) {
            return true;
        }
    } else {
        if (isCreditNo($value)) {
            return true;
        }
    }
    return false;
}