<?php
function getRealIp ($request) {
    $ipAddress = $request->ip();
 
    // 如果使用了代理，尝试获取真实IP
    if ($request->server('HTTP_X_FORWARDED_FOR')) {
        $ipAddress = $request->server('HTTP_X_FORWARDED_FOR');
    } elseif ($request->server('HTTP_CLIENT_IP')) {
        $ipAddress = $request->server('HTTP_CLIENT_IP');
    }
    $ipArray = explode(',',$ipAddress);
    return $ipArray[0];
}
function whereFunction($data,$type=1) {
    $shop_superior_id = DB::table('shop')
        ->where('shop_id', $data['user_info']->adm_shop_id)
        ->value('shop_superior_id');
    $bind_shop = DB::table('shop')
        ->where('shop_superior_id', $data['user_info']->adm_shop_id)
        ->select('shop_id')
        ->get()->toArray();
    $bind_shop_id = [];
    foreach ($bind_shop as $key => $value) {
        $bind_shop_id[] = $value->shop_id;
    }
    if ($type == 1) {//按分店id查询
        $res['string'] = $data['string'].'shop_id';
        $res['shop_id'][] = $data['user_info']->adm_shop_id;
    } elseif ($type == 2) {//总店id查询
        $res['string'] = $data['string'].'shop_id';
        $res['shop_id'][] = $shop_superior_id;
    } elseif ($type == 3) {//总店及此分店
        $res['string'] = $data['string'].'shop_id';
        if ($shop_superior_id == 0) {//总店及所有分店
            $res['shop_id'][] = $data['user_info']->adm_shop_id;
            if ($bind_shop_id) {
                foreach ($bind_shop_id as $key => $value) {
                    $res['shop_id'][] = $value;
                }
            }
        } else {
            $res['shop_id'][] = $data['user_info']->adm_shop_id;
            $res['shop_id'][] = $shop_superior_id;
        }
    }
    return $res;
}

function addMoudleNum ($user_info,$data) {
    $adm_shop_leave = DB::table('admin_shop_role')
        ->where('adm_id', $user_info->adm_id)
        ->where('shop_id', $user_info->adm_shop_id)
        ->value('adm_shop_leave');
    if ($adm_shop_leave == 1) {//店长
        $find_most = DB::table('moudle_statistics')
            ->where('most_shop_id', $user_info->adm_shop_id)
            ->where('most_adm_id', $user_info->adm_id)
            ->where('most_moudle_id', $data['most_moudle_id'])
            ->first();
        if ($find_most) {
            $add_res = DB::table('moudle_statistics')
                ->where('most_id', $find_most->most_id)
                ->increment('most_nums');
        }
    }
}

function shopFoldSize($shop_id) {
    $imagePath = storage_path() .'/app/public/image/'.$shop_id;
    $videoPath = storage_path() .'/app/public/video/'.$shop_id;
    $imageSize = 0;
    if (file_exists($imagePath)) {
        $imageSize = getFolderSize($imagePath);
    }
    $videoSize = 0;
    if (file_exists($videoPath)) {
        $videoSize = getFolderSize($videoPath);
    }
    $all_size = $imageSize + $videoSize;
    $roundedValue = ceil($all_size/1073741824 * 100) / 100;
    $formattedValue = number_format($roundedValue, 2);
    // $Gsize =  round($all_size/1073741824,4);
    return $formattedValue;
}

function getFolderSize($folderPath) {
    $output = shell_exec('du -sb ' . $folderPath);
    preg_match('/^(\d+)/', $output, $matches);
    if (isset($matches[1])) {
        $sizeInBytes = (int)$matches[1];
    } else {
        $sizeInBytes= 0;
    }
 
    return $sizeInBytes;
}
    /**
     * [addNewLog 添加操作日志]
     * @param [type] $user_info [用户信息]
     * @param [type] $oplo_ip        [操作ip]
     * @param [type] $oplo_module    [操作模块]
     * @param [type] $oplo_action    [操作功能]
     * @param [type] $oplo_content   [操作内容]
     */
function addNewLog(
    $user_info,
    $data
) {
    $user_info = json_decode(json_encode($user_info, true), true);
    $add_data = [
        'oplo_cid'=>$user_info['adm_cid'],
        'oplo_shop_id'=>$user_info['adm_shop_id'],
        'oplo_adm_id'=>$user_info['adm_id'],
        'oplo_adm_name'=>$user_info['adm_name'],
        'oplo_module'=>$data['oplo_module'],
        'oplo_action'=>$data['oplo_action'],
        'oplo_content'=>$data['oplo_content'],
        'oplo_ip'=>$data['oplo_ip'],
        'order_number'=>$data['order_number'],
        'work_number'=>$data['work_number'],
        'data_source'=>$data['data_source'],//操作来源  1 PC  2 小程序
    ];
    return DB::table('operation_log')->insert($add_data);
}

  /**
     * 是否发送短信
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-10-27
     * @param  [type]           $user_info [description]
     * @param  [type]           $type      [description]
     * @return boolean                     [description]
     */
    function isSend($user_info,$type)
    {
        $find_msg_config = DB::table('msg_config')
            ->where('msco_shop_id', $user_info->adm_shop_id)
            ->first();
        if (!$find_msg_config) {
            return false;
        }
        if ($find_msg_config->msco_is_send == 2) {
            return false;
        }
        $msco_send_detail = explode(',',$find_msg_config->msco_send_detail);
        if (!in_array($type,$msco_send_detail)) {
            return false;
        }
        return true;
    }

/**
 * [uploadBase64Img 上传base64图片]
 * @param  [type] $stream [base64数据]
 * @return [type]         [上传成功返回图片路径，失败返回false]
 */
function uploadBase64Img($stream)
{
    if (stristr($stream, 'data:image')) {
        $stream  = $stream;
    } else {
        $stream = "data:image/png;base64," . $stream;
    }
    //获取扩展名和文件名
    if (preg_match('/(?<=\/)[^\/]+(?=\;)/', $stream, $pregR)) {
        $streamFileType = '.' . $pregR[0];
    }

    $streamFileRand = time() . rand(11111, 99999); //产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
    // $pathName = "/public/storage/image/" ;
    $pathName = storage_path() . "/app/public/image/"; //获取上传图片路径

    // 创建文件夹
    if (!file_exists($pathName)) {
        mkdir($pathName, 0775, true);
        chmod($pathName, 0775);
    }
    $streamFilename = $pathName . $streamFileRand . $streamFileType; //上传到服务器图片路径

    //处理base64文本，用正则把第一个base64,之前的部分砍掉
    preg_match('/(?<=base64,)[\S|\s]+/', $stream, $streamForW);
    if (file_put_contents($streamFilename, base64_decode($streamForW[0])) === false) {
        return false;
    } else {
        // 返回路径
        $filePath = "storage/image/" . $streamFileRand . $streamFileType;
        return $filePath;
    }
}

/**
 * [uploadBase64ImgFolder 上传base64图片]
 * @param  [type]  $shop_id [总店id]
 * @param  [type]  $stream  [base64数据]
 * @param  integer $type    [类型1压缩图片2不压缩图片]
 * @return [type]           [description]
 */
function uploadBase64ImgFolder($shop_id, $stream, $type=1)
{
    if (stristr($stream, 'data:image')) {
        $stream  = $stream;
    } else {
        $stream = "data:image/png;base64," . $stream;
    }
    $free = '';
    if (isset($request['ord_order_number']) && !empty($request['ord_order_number'])) {
        $find_order = DB::table('order')
            ->where('ord_order_number', $request['ord_order_number'])
            ->first();
        if ($find_order && $find_order->ord_source == 5) {
            $free = 'free';
        }
    }
    if (empty($free)) {
        // $shop_use_space = shopFoldSize($request['shop_id']);
        // $find_shop = DB::table('shop')
        //     ->where('shop_id', $request['shop_id'])
        //     ->select('shop_free_space', 'shop_toll_space', 'shop_superior_id')
        //     ->first();
        // $space = $find_shop->shop_free_space + $find_shop->shop_toll_space;
        // if ($shop_use_space >= $space) {
        //     if ($find_shop->shop_superior_id) {//分店
        //         return response()->json(['code'=>501, 'msg'=>'空间不足，请联系总店购买空间后上传', 'data'=>'']);
        //     } else {//总店
        //         return response()->json(['code'=>502, 'msg'=>'空间不足，请购买空间后上传', 'data'=>'']);
        //     }
        // }
    }
    //获取扩展名和文件名
    if (preg_match('/(?<=\/)[^\/]+(?=\;)/', $stream, $ext)) {
        $stream_file_type = '.' . $ext[0];
    }
    $stream_file_rand = time() . rand(11, 99) .rand(111, 999); //产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
    $folder = $shop_id.date('/Y/m/d/');
    $path_name = storage_path() . '/app/public/'.$free.'image/'.$folder; //获取上传图片路径

    // 创建文件夹
    if (!file_exists($path_name)) {
        mkdir($path_name, 0775, true);
        chmod($path_name, 0775);
    }
    $stream_file_name = $path_name . $stream_file_rand . $stream_file_type; //上传到服务器图片路径

    //处理base64文本，用正则把第一个base64,之前的部分砍掉
    preg_match('/(?<=base64,)[\S|\s]+/', $stream, $stream_base);
    if (file_put_contents($stream_file_name, base64_decode($stream_base[0])) === false) {
        return false;
    } else {
        if ($type == 1) {
            // 压缩图片
            $new_stream_file_name = $path_name .'2'.$stream_file_rand . $stream_file_type; //上传到服务器图片路径
            imageCompress($stream_file_name, 1, $new_stream_file_name);
            // 删除原来的图片
            deleteImage([$stream_file_name]);
            $stream_file_rand = '2'.$stream_file_rand;
        }
        // 读取图片
        // 图片路径  http://mk.bluearp.com/storage/image/1/2020/12/02/159429003777298.png
        // 返回路径  storage/image/1/2020/12/02/159429003777298.png
        $file_path = 'storage/'.$free.'image/'.$folder. $stream_file_rand . $stream_file_type;
        return $file_path;
    }
}

/**
 * [deleteImage 删除图片]
 * @param  [type] $image_path [图片路径，数组]
 * @return [type]             [description]
 */
function deleteImage($image_path)
{
    if (empty($image_path)) {
        return true;
    }
    try {
        foreach ($image_path as $key => $value) {
            unlink($value);//删除图片
        }
    } catch (Exception $e) {
        
    }
    return true;
}

/**
 * [imageCompress 压缩图片]
 * @param  [type] $src                  [原来图片路径]
 * @param  [type] $percent              [压缩比例]
 * @param  [type] $new_stream_file_name [压缩图片路径]
 * @return [type]                       [description]
 */
function imageCompress($src, $percent, $new_stream_file_name)
{
    // 打开图片
    list($width, $height, $type, $attr) = getimagesize($src);
    $imageinfo = [
        'width'=>$width,
        'height'=>$height,
        'type'=>image_type_to_extension($type, false),
        'attr'=>$attr,
    ];
    $fun = 'imagecreatefrom'.$imageinfo['type'];
    $image = $fun($src);

    // 操作图片
    $new_width = $imageinfo['width'] * $percent;
    $new_height = $imageinfo['height'] * $percent;
    $image_thump = imagecreatetruecolor($new_width, $new_height);
    // 将原图复制带图片载体上面，并且按照一定比例压缩,极大的保持了清晰度
    imagecopyresampled($image_thump, $image,0,0,0,0, $new_width, $new_height, $imageinfo['width'], $imageinfo['height']);
    imagedestroy($image);
    $image = $image_thump;

    // 保存图片
    $dst_img_name = $new_stream_file_name;
    $allow_imgs = ['.jpg', '.jpeg', '.png', '.bmp', '.wbmp', '.gif'];//如果目标图片名有后缀就用目标图片扩展名 后缀，如果没有，则用源图的扩展名
    $dst_ext = strrchr($dst_img_name, '.');
    $sourse_ext = strrchr($src, '.');
    if (!empty($dst_ext)) {
        $dst_ext =strtolower($dst_ext);
    }
    if(!empty($sourse_ext)) {
        $sourse_ext = strtolower($sourse_ext);
    }
    // 有指定目标名扩展名
    if (!empty($dst_ext) && in_array($dst_ext, $allow_imgs)) {
        $dst_name = $dst_img_name;
    }elseif (!empty($sourse_ext) && in_array($sourse_ext, $allow_imgs)) {
        $dst_name = $dst_img_name.$sourse_ext;
    }else{
        $dst_name = $dst_img_name.$imageinfo['type'];
    }
    $funcs = 'image'.$imageinfo['type'];
    $funcs($image, $dst_name);
}

// 日志记录，记录操作数据
function logRecord($data, $file_name = 'log', $type = 1)
{
    // $file_path = "./Uploads/".$file_name.".txt";
    $file_path = storage_path() . "/logs/" . $file_name . ".txt";
    $myfile = fopen($file_path, "a");
    if ($type == 1) {
        $txt = json_encode($data) . "\r\n\r\n";
    }else{
        $txt = json_encode($data, JSON_UNESCAPED_UNICODE) . "\r\n\r\n";
    }
    fwrite($myfile, $txt);
    fclose($myfile);
}

// 日志记录，自定义文件夹，记录操作数据
function logFileRecord($data, $file_name = 'log', $type = 1)
{
    // $file_path = "./Uploads/".$file_name.".txt";
    $file_path = storage_path() . "/logs/" . $file_name . ".txt";
    $pathName = substr($file_path, 0, strripos($file_path, '/') + 1);
    // 创建文件夹
    if (!file_exists($pathName)) {
        mkdir($pathName, 0775, true);
        chmod($pathName, 0775);
    }
    
    $myfile = fopen($file_path, "a");
    if ($type == 1) {
        $txt = json_encode($data) . "\r\n\r\n";
    }else{
        $txt = json_encode($data, JSON_UNESCAPED_UNICODE) . "\r\n\r\n";
    }
    fwrite($myfile, $txt);
    fclose($myfile);
}

/**
 * [getListButton 获取当前列表下按钮]
 * @param  [type] $api_token [用户token]
 * @param  [type] $pri_id    [当前列表权限id]
 * @return [type]            [description]
 */
function getListButton($api_token, $pri_id)
{
    $role_info = DB::table('login_temporary')
        ->where('api_token', '=', $api_token)
        ->select('role_auth')
        ->first();
    $role_auth = json_decode($role_info->role_auth, true);

    // 获取到当前列表下的按钮
    foreach ($role_auth as $key => $value) {
        if ($value['pri_fid'] == $pri_id && $value['pri_show'] == 1) {
            $list_button[] = $value;
        }
    }
    if (empty($list_button)) {
        return false;
    }
    return $list_button;
}

/**
 * [getListButton 小程序获取当前列表下按钮]
 * @param  [type] $api_token [用户token]
 * @param  [type] $pri_id    [当前列表权限id]
 * @return [type]            [description]
 */
function getAppletListButton($api_token, $pri_id)
{
    $role_info = DB::table('login_wechat_applet')
        ->where('api_token', '=', $api_token)
        ->select('role_auth')
        ->first();
    $role_auth = json_decode($role_info->role_auth, true);
    // 获取到当前列表下的按钮
    foreach ($role_auth as $key => $value) {
        if ($value['pri_fid'] == $pri_id && $value['pri_show'] == 1 && $value['have_pri'] == 1) {
            $list_button[] = $value;
            $pri_sord[] = $value['pri_sord'];
            $pri_ids[] = $value['pri_id'];
        }
    }
    if (empty($list_button)) {
        return false;
    }
    array_multisort($pri_sord, SORT_NUMERIC, SORT_DESC, $pri_ids, SORT_NUMERIC, SORT_DESC, $list_button);
    return $list_button;
}

// 获取验证码接口
function sendSmsCode($mobile, $content)
{
    // return 1;
    //配置文件中的账号密码
    $sms_account = config('apisystem.sms_account');
        
    $username = $sms_account[0]['account'];
    $pwd = $sms_account[0]['password'];

    $password = md5($username . "" . md5($pwd));
    $url = "http://www1.jc-chn.cn/smsSend.do?";

    $param = http_build_query(
        array(
            'username' => $username,
            'password' => $password,
            'mobile' => $mobile,
            // 'content'=>iconv("GB2312","UTF-8",$content)
            'content' => $content
        )
    );
    /*
        短信发送返回的状态码,状态码大于0的算发送成功
        1 提交成功
        0 失败
        -1 用户名或者密码不正确
        -2 必填选项为空
        -3 短信内容0个字节
        -5 余额不够
        -10 用户被禁用
        -11 短信内容超过500字
        -12 无扩展权限(ext 字段需填空)
        -13 IP校验错误
        -14 内容解析异常
        -990 未知错误
    */

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

// 小程序-用户消息新增
function addUserMessage($data)
{
    $add_data['weus_id'] = $data['weus_id'];
    $add_data['shop_id'] = $data['shop_id'];
    $add_data['primary_id'] = $data['primary_id'];//单据的主键id
    $add_data['primary_type'] = $data['primary_type'];//单据类型：1订单2工单3预约单4售后单
    $add_data['adm_type'] = isset($data['adm_type']) ? $data['adm_type'] : 1;//1门店2合作商
    $add_data['read_state'] = $data['read_state'];//阅读状态：1未读2已读
    $add_data['title'] = $data['title'];//消息标题
    $add_data['content'] = $data['content'];//操作内容
    $add_data['create_adm_name'] = $data['create_adm_name'];//操作人姓名
    $add_data['create_adm_id'] = $data['create_adm_id'];//操作人id
    $add_data['create_time'] = date('Y-m-d H:i:s');
    $add_data['update_time'] = date('Y-m-d H:i:s');
    $add_data_res = DB::table('user_message')->insert($add_data);
    if ($add_data_res) {
        return ['code'=>200, 'msg'=>'新增消息成功', 'data'=>'新增消息成功'];
    } else {
        return ['code'=>500, 'msg'=>'新增消息失败', 'data'=>'新增消息失败'];
    }
}

// 小程序-技师消息新增
function addAdminMessage($data)
{
    $add_data['adm_id'] = $data['adm_id'];
    $add_data['shop_id'] = $data['shop_id'];
    $add_data['primary_id'] = $data['primary_id'];//单据的主键id
    $add_data['primary_type'] = $data['primary_type'];//单据类型：1订单2工单3预约单4售后单
    // $add_data['message_type'] = 1;
    $add_data['message_type'] = $data['message_type'];
    // $add_data['primary_wor_state'] = isset($data['primary_wor_state'])?$data['primary_wor_state']:'';
    $add_data['title'] = $data['title'];//标题
    $add_data['content'] = $data['content'];//操作内容
    $add_data['read_state'] = $data['read_state'];//阅读状态：1未读2已读
    $add_data['create_adm_name'] = $data['create_adm_name'];//操作人姓名
    $add_data['create_adm_id'] = $data['create_adm_id'];//操作人id
    $add_data['create_time'] = date('Y-m-d H:i:s');
    $add_data['update_time'] = date('Y-m-d H:i:s');
    $add_data_res = DB::table('admin_message')->insert($add_data);
    if ($add_data_res) {
        return ['code'=>200, 'msg'=>'新增消息成功', 'data'=>'新增消息成功'];
    } else {
        return ['code'=>500, 'msg'=>'新增消息失败', 'data'=>'新增消息失败'];
    }
}

// APP推送消息
function pushMessage($audience, $notification, $type = 1)
{
    $audience['tag'] = $audience['alias'];//推送标签
    $data = [
        // 'platform'=>'all',//推送到所有平台
        // 'audience'=>'all', //针对于所有人
        // 'audience'=>["alias"=>[ "张利峰"]], //针对于某一个人
        // 'notification'=>['alert'=>'请注意：工单70176347917370即将到预约时间'],
        'platform' => ['android', 'ios'], //指定特定推送平台
        'audience' => $audience, //针对于某一个人
        'notification' => [
            "android" => [
                'alert' => $notification,
                // 自定义字段
                "extras" => [
                    // APP提示音类型：1新工单2催单3售后催单4工单预约提醒5速电锁定6系统锁定7速电取消锁定8系统取消锁定9审核改单10速电撤销
                    "type" => $type
                ]
            ],
            "ios" => [
                'alert' => [
                    'title' => '',
                    'body' => $notification
                ],
                "sound" => "sound.caf",
                "extras" => [
                    "type" => $type
                ]
            ],
        ],
        "options" => [
            "apns_production" => config('apisystem.apns_production'), //apns_production 字段来设定推送环境。True 表示推送生产环境，False 表示要推送开发环境； 如果不指定则为推送生产环境；一次只能推送给一个环境。
        ]
    ];
    $return_data = curlPost(json_encode($data));
    return json_decode($return_data, true);
}

function curlPost($data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1); //请求方式为POST
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //绑定POST要发送的数据
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //TRUE 将curl_exec()获取的信息以字符串返回，而不是直接输出。
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Basic Mjk1ODk5N2VmMmJkNDdkMDZlMmIyYmQxOmQ2Y2YzNGZjNWJlM2FkN2M1YjhhYTJiZQ==',
    ));
    curl_setopt($ch, CURLOPT_HEADER, 0); //返回response头部信息
    curl_setopt($ch, CURLINFO_HEADER_OUT, true); //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 关闭SSL验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 关闭SSL验证
    curl_setopt($ch, CURLOPT_URL, 'https://api.jpush.cn/v3/push');
    $result = curl_exec($ch);
    $err = curl_error($ch);
    if ($err) {
        return "错误：" . $err;
    } else {
        return $result;
    }
}

/**
 * [模拟post提交]
 * @param  [string] $url       [base64数据]
 * @param  [array]  $param    路径 存放哪一个文件夹下
 * @return [bool]   成功返回true
 */
function doPost($param, $url, $type=1)
{
    // 模拟提交数据函数
    $post_data = ToUrlencode($param);
    $post_data=urldecode(json_encode($post_data));
    // logFileRecord($post_data, 'doPost', 2);
    // Common::write_log($param, $type);
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据，json格式
}

/**
 * [ConvertGDToBD 高德地图经纬度转百度地图经纬度]
 * @param [type] $lat [纬度]
 * @param [type] $lng [经度]
 */
function convertGDToBD($lat, $lng)
{
    $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    $x = $lng;
    $y = $lat;
    $z = sqrt($x * $x + $y * $y) + 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) + 0.000003 * cos($x * $x_pi);
    $lat = $z * sin($theta) + 0.006;
    $lng = $z * cos($theta) + 0.0065;
    return array('lat' => $lat, 'lng' => $lng);
}

/**
 *  计算两组经纬度坐标 之间的距离
 *   params ：lat1 纬度1； lng1 经度1； lat2 纬度2； lng2 经度2； len_type （1:km or 2:m);
 *   return m or km
 */
function getDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2)
{
    if(!defined('EARTH_RADIUS')){
        define('EARTH_RADIUS', 6378.137); //地球半径，假设地球是规则的球体
    }
    if(!defined('PI')){
        define('PI', 3.1415926535898);
    }
    $radLat1 = $lat1 * PI() / 180.0;   //PI()圆周率
    $radLat2 = $lat2 * PI() / 180.0;
    $a = $radLat1 - $radLat2;
    $b = ($lng1 * PI() / 180.0) - ($lng2 * PI() / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * EARTH_RADIUS;
    $s = round($s * 1000);
    if ($len_type == 1) {
        $s = $s / 1000;
    }
    return $s;
}

/**
 * 订单操作记录信息
 * @param  $user_info           string      用户信息
 * @param  $ord_id              int         订单id
 * @param  $wor_id              int         工单id
 * @param  $content             string      操作内容
 * @return json
 */
function orderLog($user_info, $ord_id, $wor_id, $content)
{
    $data['orlo_cid'] = $user_info->adm_cid; //企业id
    $data['orlo_superior_shop_id'] = $user_info->shop_superior_id; //总店id
    $data['orlo_shop_id'] = $user_info->adm_shop_id; //所属门店id
    $data['orlo_ord_id'] = $ord_id; //订单id
    $data['orlo_wor_id'] = $wor_id; //工单id
    $data['orlo_content'] = $content; //操作内容
    $data['orlo_create_adm_name'] = $user_info->adm_name; //操作人姓名
    $data['orlo_create_adm_id'] = $user_info->adm_id; //操作人id
    $data['orlo_time'] = date('Y-m-d H:i:s'); //操做时间
    return DB::table('order_log')->insert($data);
}

/**
 * 商品操作记录信息
 * @param  $user_info           string      用户信息
 * @param  $pait_id              int         商品id
 * @param  $content             string      操作内容
 * @param  $remark             string      备注
 * @return json
 */
function paitLog($user_info, $pait_id, $content, $remark)
{
    $data['palo_cid'] = $user_info->adm_cid; //企业id
    $data['palo_shop_id'] = $user_info->adm_shop_id; //所属门店id
    $data['palo_pait_id'] = $pait_id; //商品id
    $data['palo_content'] = $content; //操作内容
    $data['palo_remark'] = $remark; //备注
    $data['palo_create_name'] = $user_info->adm_name; //操作人姓名
    $data['palo_create_id'] = $user_info->adm_id; //操作人id
    $data['palo_create_time'] = date('Y-m-d H:i:s'); //操做时间
    return DB::table('pait_log')->insert($data);
}

/**
 * 单据类型操作记录信息
 * @param  $user_info           string      用户信息
 * @param  $primary_id          int         单据主键id
 * @param  $type                int         单据类型：1预约单2售后单
 * @param  $content             string      操作内容
 * @param  $ord_id          int         订单id
 * @param  $wor_id          int         工单id
 * @return json
 */
function orderLogType($user_info, $primary_id=0, $type=0, $content, $ord_id=0, $wor_id=0)
{
    $user_info = (array) $user_info;
    $data['orlo_cid'] = $user_info['adm_cid']; //企业id
    $data['orlo_superior_shop_id'] = $user_info['shop_superior_id']; //总店id
    $data['orlo_shop_id'] = $user_info['adm_shop_id']; //所属门店id
    $data['orlo_ord_id'] = $ord_id; //订单id
    $data['orlo_wor_id'] = $wor_id; //工单id
    $data['orlo_primary_id'] = $primary_id; //单据主键id
    $data['orlo_primary_type'] = $type; //单据类型：1预约单2售后单
    $data['orlo_content'] = $content; //操作内容
    $data['orlo_create_adm_name'] = $user_info['adm_name']; //操作人姓名
    $data['orlo_create_adm_id'] = $user_info['adm_id']; //操作人id
    $data['orlo_time'] = date('Y-m-d H:i:s'); //操作时间
    return DB::table('order_log')->insert($data);
}

/**
 * 速电操作订单记录信息
 * @param  $user_info           string      用户信息
 * @param  $ord_id              int         订单id
 * @param  $wor_id              int         工单id
 * @param  $content             string      操作内容
 * @return json
 */
function sdOrderLog($ord_data, $ord_id, $wor_id, $content)
{
    $data['orlo_cid'] = $ord_data->ord_cid; //企业id
    $data['orlo_superior_shop_id'] = $ord_data->ord_superior_shop_id; //总店id
    $data['orlo_shop_id'] = $ord_data->ord_shop_id; //所属门店id
    $data['orlo_ord_id'] = $ord_id; //订单id
    $data['orlo_wor_id'] = $wor_id; //工单id
    $data['orlo_content'] = $content; //操作内容
    $data['orlo_create_adm_name'] = '速电'; //操作人姓名
    $data['orlo_create_adm_id'] = 0; //操作人id
    $data['orlo_time'] = date('Y-m-d H:i:s'); //操做时间
    return DB::table('order_log')->insert($data);
}

// 阿拉伯数字金额转中文大写金额
function num_to_rmb($num)
{
    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";

    //精确到分后面就不要了，所以只留两个小数位

    $num = round($num, 2);

    //将数字转化为整数

    $num = $num * 100;

    if (strlen($num) > 10) {
        return "金额太大，请检查";
    }
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            // 获取最后一位数字
            $n = substr($num, strlen($num) - 1, 1);
        } else {
            $n = $num % 10;
        }   //每次将最后一位数字转换为中文

        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        //去掉数字最后一位了

        $num = $num / 10;

        $num = (int) $num;
        //结束循环

        if ($num == 0) {
            break;
        }
    }
    $j = 0;
    $slen = strlen($c);
    while ($j <= $slen) {
        //utf8一个汉字相当3个字符
        $m = substr($c, $j, 6);
        //处理数字中很多0的情况,每次循环去掉一个汉字“零”

        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);

            $right = substr($c, $j + 3);

            $c = $left . $right;

            $j = $j - 3;

            $slen = $slen - 3;
        }

        $j = $j + 3;
    }

    if (substr($c, strlen($c) - 3, 3) == '零') {
        $c = substr($c, 0, strlen($c) - 3);
    }
    if (empty($c)) {
        return "零元整";
    } else {
        return $c . "整";
    }
}

// 将汉字转换为拼音和得到词语首字母
// function getfirstchar($s0)
// {
//     $fchar = ord($s0{
//     0});
//     if ($fchar >= ord("A") and $fchar <= ord("z")) {
//         return strtoupper($s0{
//     0});
//     }
//     $s1 = @iconv("UTF-8", "gb2312", $s0);
//     $s2 = @iconv("gb2312", "UTF-8", $s1);
//     if ($s2 == $s0) {
//         $s = $s1;
//     } else {
//         $s = $s0;
//     }
//     $asc = ord($s{
//     0}) * 256 + ord($s{
//     1}) - 65536;
//     if ($asc >= -20319 and $asc <= -20284) {
//         return "A";
//     }
//     if ($asc >= -20283 and $asc <= -19776) {
//         return "B";
//     }
//     if ($asc >= -19775 and $asc <= -19219) {
//         return "C";
//     }
//     if ($asc >= -19218 and $asc <= -18711) {
//         return "D";
//     }
//     if ($asc >= -18710 and $asc <= -18527) {
//         return "E";
//     }
//     if ($asc >= -18526 and $asc <= -18240) {
//         return "F";
//     }
//     if ($asc >= -18239 and $asc <= -17923) {
//         return "G";
//     }
//     if ($asc >= -17922 and $asc <= -17418) {
//         return 'H';
//     }
//     if ($asc >= -17922 and $asc <= -17418) {
//         return "I";
//     }
//     if ($asc >= -17417 and $asc <= -16475) {
//         return "J";
//     }
//     if ($asc >= -16474 and $asc <= -16213) {
//         return "K";
//     }
//     if ($asc >= -16212 and $asc <= -15641) {
//         return "L";
//     }
//     if ($asc >= -15640 and $asc <= -15166) {
//         return "M";
//     }
//     if ($asc >= -15165 and $asc <= -14923) {
//         return "N";
//     }
//     if ($asc >= -14922 and $asc <= -14915) {
//         return "O";
//     }
//     if ($asc >= -14914 and $asc <= -14631) {
//         return "P";
//     }
//     if ($asc >= -14630 and $asc <= -14150) {
//         return "Q";
//     }
//     if ($asc >= -14149 and $asc <= -14091) {
//         return "R";
//     }
//     if ($asc >= -14090 and $asc <= -13319) {
//         return "S";
//     }
//     if ($asc >= -13318 and $asc <= -12839) {
//         return "T";
//     }
//     if ($asc >= -12838 and $asc <= -12557) {
//         return "W";
//     }
//     if ($asc >= -12556 and $asc <= -11848) {
//         return "X";
//     }
//     if ($asc >= -11847 and $asc <= -11056) {
//         return "Y";
//     }
//     if ($asc >= -11055 and $asc <= -10247) {
//         return "Z";
//     }
//     return null;
// }

function pinyin1($zh)
{
    $ret = "";
    $s1 = iconv("UTF-8", "gb2312", $zh);
    $s2 = iconv("gb2312", "UTF-8", $s1);
    if ($s2 == $zh) {
        $zh = $s1;
    }
    for ($i = 0; $i < strlen($zh); $i++) {
        $s1 = substr($zh, $i, 1);
        $p = ord($s1);
        if ($p > 160) {
            $s2 = substr($zh, $i++, 2);
            $ret .= getfirstchar($s2);
        } else {
            $ret .= $s1;
        }
    }
    return $ret;
}

/**
 * 打印sql语句
 * @return [string] [sql语句]
 */
function print_sql()
{
    DB::listen(function ($query) {
        $bindings = $query->bindings;
        $sql = $query->sql;
        foreach ($bindings as $replace) {
            $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
            $sql = preg_replace('/\?/', $value, $sql, 1);
        }
        dump($sql);
        die;
    });
}

/**
 * SQL语句日志记录
 * @return [string] [sql语句]
 */
function sqlLog()
{
    DB::listen(function ($query) {
        $bindings = $query->bindings;
        $sql = $query->sql;
        foreach ($bindings as $replace) {
            $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
            $sql = preg_replace('/\?/', $value, $sql, 1);
        }
        $path = storage_path() . "/logs/sqlLog/"; //日志路径
        // 创建文件夹
        if (!file_exists($path)) {
            mkdir($path, 0775, true);
            chmod($path, 0775);
        }
        // 将SQL语句存入日志文件
        $file_path = storage_path() . "/logs/sqlLog/" . date('Y-m-d') . ".txt";
        $myfile = fopen($file_path, "a");
        $txt = date('Y-m-d H:i:s').' '.json_encode($sql) . "\r\n\r\n";
        fwrite($myfile, $txt);
        fclose($myfile);
    });
}

/**
 * [truncateFill 截取填充固定位数]
 * @param  [type] $number [不定长的数字]
 * @param  [type] $digit  [要保留的固定位数]
 * @return [type]         [返回截取填充后的数据]
 */
function truncateFill($number, $digit)
{
    return str_pad(substr($number, '-' . $digit), $digit, 0, STR_PAD_LEFT);
}

/**
 * 将 去除所有空格换行符等其他符号
 * @param [type] $data [description]
 */
function RemoveLineFeed($data)
{
    if (is_array($data)) {
        foreach ($data as $key => $val) {
            $data[$key] = RemoveLineFeed($val);
        }
        return $data;
    } else {
        $data = str_replace(array("\r\n", "\r", "\n", "\t", " "), " ", $data);
        $data = trim($data, " ");
        return $data;
    }
}

/**
 * 记录错误日志
 * @param [type] $data 内容
 * @param string $path 路径
 */
function LogInfo($data, $path = "")
{
    if ($path != "") {
        $monolog = \Log::getMonolog();
        $monolog->popHandler();
        \Log::useDailyFiles(storage_path('logs/' . $path . '.log'));
    }
    \Log::info($data);
}

/**
 * 将 null 替换为 ""
 * @param [type] $data [description]
 */
function RemoveNull($data)
{
    if (is_array($data)) {
        foreach ($data as $key => $val) {
            $data[$key] = RemoveNull($val);
        }
        return $data;
    } else {
        if ($data === null) {
            return "";
        } else {
            return trim($data);
        }
    }
}

/**
 * [simulationPost 模拟post提交数据函数]
 * @param  [type] $url   [请求网址]
 * @param  array  $param [参数]
 * @return [type]        [description]
 */
function simulationPost($url, array $param)
{
    $post_data = toUrlencode($param);
    $post_data = urldecode(json_encode($post_data));
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl); //捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据，json格式
}

function toUrlencode($arr)
{
    $temp = array();
    if (is_array($arr)) {
        foreach ($arr as $key => $row) {
            $temp[$key] = $row;
            if (is_array($temp[$key])) {
                $temp[$key] = toUrlencode($temp[$key]);
            } else {
                $temp[$key] = urlencode($row);
            }
        }
    } else {
        $temp = $arr;
    }
    return $temp;
}

//判断工单状态
function stateSetting($state)
{
    if (in_array($state, [1, 2, 3])) {
        $state = 1;
    } else {
        switch ($state) {
            case 4:
                $state = 2;
                break;
            case 5:
                $state = 3;
                break;
            case 6:
                $state = 4;
                break;
            case 7:
                $state = 5;
                break;
            case 8:
                $state = 6;
                break;
            case 9:
                $state = 7;
                break;
            case 10:
                $state = 8;
                break;
            case 11:
                $state = 9;
                break;
            case 12:
                $state = 10;
                break;
            default:
                $state = 0;
                break;
        }
    }
    return $state;
}

/**
 * 订单售后操作记录信息
 * @param  $user_info           string      用户信息
 * @param  $ord_id              int         订单/工单/售后单id
 * @param  $type                int         类型1订单2工单3售后单
 * @param  $content             string      操作内容
 * @return json
 */
function orderAfterLog($user_info, $ord_id, $type, $content)
{
    $data['oral_cid'] = $user_info->adm_cid; //企业id
    $data['oral_superior_shop_id'] = $user_info->shop_superior_id; //总店id
    $data['oral_shop_id'] = $user_info->adm_shop_id; //所属门店id
    $data['oral_ord_id'] = $ord_id; //订单id
    $data['oral_type'] = $type; //工单id
    $data['oral_content'] = $content; //操作内容
    $data['oral_create_adm_name'] = $user_info->adm_name; //操作人姓名
    $data['oral_create_adm_id'] = $user_info->adm_id; //操作人id
    $data['oral_time'] = date('Y-m-d H:i:s'); //操做时间
    return DB::table('order_after_log')->insert($data);
}

// 判断售后单状态
function stateAfterSetting($state)
{
    if (in_array($state, [1])) {
        $state = 1;
    } else {
        switch ($state) {
            case 2:
                $state = 2;
                break;
            case 3:
                $state = 3;
                break;
            case 4:
                $state = 1;
                break;
            case 5:
                $state = 2;
                break;
            case 6:
                $state = 3;
                break;
            case 7:
                $state = 5;
                break;
            case 8:
                $state = 6;
                break;
            case 9:
                $state = 7;
                break;
            case 10:
                $state = 8;
                break;
            case 11:
                $state = 10;
                break;
            default:
                $state = 0;
                break;
        }
    }
    return $state;
}

/**
 * [addInformationHint 添加信息提示]
 * @param [type] $user_info [用户信息]
 * @param [type] $add_data  [单号信息]
 * @param [type] $type      [单号类型：1订单]
 */
function addInformationHint($user_info, $add_data, $type)
{
    // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
    $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

    $inhi_data['inhi_cid'] = $user_info->adm_cid;
    $inhi_data['inhi_shop_id'] = $user_info->adm_shop_id;
    $inhi_data['inhi_shop_superior_id'] = $shop_id;
    $inhi_data['inhi_adm_id'] = $user_info->adm_id;
    $inhi_data['inhi_original_adm_id'] = $add_data['inhi_original_adm_id'];//原始单号创建人
    $inhi_data['inhi_original_id'] = $add_data['inhi_original_id'];//原始单id
    $inhi_data['inhi_original_number'] = $add_data['inhi_original_number'];//原始单号
    $inhi_data['inhi_original_state'] = $add_data['inhi_original_state'];//原始单状态
    $inhi_data['inhi_original_operation'] = $add_data['inhi_original_operation'];//操作
    $inhi_data['inhi_operation_state'] = $add_data['inhi_operation_state'];//操作状态：1新订单
    $inhi_data['inhi_type'] = $type;//单号类型:1订单2工单3速电网单
    $res = DB::table('information_hint')->insert($inhi_data);
    return $res;
}

/**
 * 订单工单备注信息
 * @param  $user_info           string      用户信息
 * @param  $ord_id              int         订单id
 * @param  $wor_id              int         工单id
 * @param  $content             string      操作内容
 * @param  $module              string      操作模块
 * @return json
 */
function orderRemark($user_info, $ord_id, $wor_id, $content, $module = '')
{
    $time = date('Y-m-d H:i:s');
    $data['orre_cid'] = $user_info->adm_cid; //企业id
    $data['orre_superior_shop_id'] = $user_info->shop_superior_id; //总店id
    $data['orre_shop_id'] = $user_info->adm_shop_id; //所属门店id
    $data['orre_ord_id'] = $ord_id; //订单id
    $data['orre_wor_id'] = !empty($wor_id) ? $wor_id :0; //工单id
    $data['orre_content'] = $content; //操作内容
    $data['orre_create_adm_name'] = $user_info->adm_name; //操作人姓名
    $data['orre_create_adm_id'] = $user_info->adm_id; //操作人id
    $data['orre_time'] = $time; //操做时间
    $data['orre_module'] = $module; //操作模块
    
    if(!empty($ord_id)){
        DB::table('order')
            ->where('ord_id',$ord_id)
            ->update(['ord_remark'=>$content,'ord_update_time'=>$time]);
    }
    if(!empty($wor_id)){
        DB::table('work_order')
            ->where('wor_id',$wor_id)
            ->update(['wor_remark'=>$content,'wor_update_time'=>$time]);
    }

    return DB::table('order_remarks')->insert($data);
}

/**
 * 订单工单备注信息
 * @param  $user_info           string      用户信息
 * @param  $primary_id              int         单据的主键id
 * @param  $primary_type              int         单据类型：1预约单2售后单
 * @param  $content             string      操作内容
 * @param  $module              string      操作模块
 * @param  $ord_id              int         订单id
 * @param  $wor_id              int         工单id
 * @return json
 */
function orderRemarkType($user_info, $primary_id, $primary_type, $content, $module = '', $ord_id=0, $wor_id=0)
{
    $time = date('Y-m-d H:i:s');
    $data['orre_cid'] = $user_info->adm_cid; //企业id
    $data['orre_superior_shop_id'] = $user_info->shop_superior_id; //总店id
    $data['orre_shop_id'] = $user_info->adm_shop_id; //所属门店id
    $data['orre_primary_id'] = $primary_id; //单据的主键id
    $data['orre_primary_type'] = $primary_type; //单据类型：1预约单2售后单
    $data['orre_ord_id'] = $ord_id; //订单id
    $data['orre_wor_id'] = $wor_id; //工单id
    $data['orre_content'] = empty($content)?'':$content; //操作内容
    $data['orre_create_adm_name'] = $user_info->adm_name; //操作人姓名
    $data['orre_create_adm_id'] = $user_info->adm_id; //操作人id
    $data['orre_time'] = $time; //操做时间
    $data['orre_module'] = $module; //操作模块
    
    if(!empty($ord_id)){
        DB::table('order')
            ->where('ord_id',$ord_id)
            ->update(['ord_remark'=>$content,'ord_update_time'=>$time]);
    }
    if(!empty($wor_id)){
        DB::table('work_order')
            ->where('wor_id',$wor_id)
            ->update(['wor_remark'=>$content,'wor_update_time'=>$time]);
    }

    return DB::table('order_remarks')->insert($data);
}

/**
 * [substituteCharacter 替换字符-中文字符]
 * @param  [type] $character [字符]
 * @return [type]            [description]
 */
function substituteCharacter($character)
{
    // 获取字符串的长度
    $length = mb_strlen($character, 'utf-8');
    // 获取第一个字符
    $mb_first = mb_substr($character, 0, 1, 'utf-8');
    if($length >= 3){
        // 获取最后一个字符
        $mb_last = mb_substr($character, $length-1, 1,'utf-8');
    } else {
        $mb_last = '*';
    }
    return $mb_first.'****'.$mb_last;
}

/**
 * [ 替换字符-中文字符]
 * @param  [type] ord_type      [int]
 * @return [type]            [description]
 */
function ordType($ord_type)
{
    switch ($ord_type) {
        case 1:
            $ord_type = '服务单';
            break;
        case 2:
            $ord_type = '销售单';
            break;
        case 3:
            $ord_type = '换货单';
            break;
        case 4:
            $ord_type = '退货单';
            break;
        case 5:
            $ord_type = '发货单';
            break;
        case 6:
            $ord_type = '结清单';
            break;
        case 7:
            $ord_type = '救援单';
            break;
        default:
            $ord_type = '未知';
            break;
    }
    return $ord_type;
}

/**
 * [dateSomeMonthsLater 几个月后的时间]
 * @param  [type] $now_time    [日期，格式年月日 时分秒]
 * @param  [type] $some_months [几个月]
 * @return [type]              [description]
 */
function dateSomeMonthsLater($now_time, $some_months)
{
    $end_time = date('Y-m-d H', strtotime( '+'.$some_months.' months', strtotime($now_time)));
    return $end_time;
}

// function isCarLicense($license)
// {
//     if (empty($license)) {
//         return false;
//     }
//     // 匹配民用车牌和使馆车牌
//     // 1，第一位为汉字省份缩写
//     // 2，第二位为大写字母城市编码
//     // 3，后面是5位仅含字母和数字的组合
//     // $regular = "/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新使]{1}[A-Z]{2}[0-9a-zA-Z]{6}$/u";
//     $regular = "/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新使]{1}[0-9a-zA-Z]{5,7}$/u";
//     $result = preg_match($regular, $license, $match);
//     if ($result) {
//         return true;
//     }
//     return false;
// }

function isCarLicense($license)
{
    if (empty($license)) {
        return false;
    }
    // 匹配民用车牌和使馆车牌
    // 1，第一位为汉字省份缩写
    // 2，第二位为大写字母城市编码
    // 3，后面是5位仅含字母和数字的组合
    $regular = "/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新使]{1}[A-Z]{1}[0-9a-zA-Z]{5}$/u";
    $result = preg_match($regular, $license, $match);
    if ($result) {
        return true;
    }
    // 匹配特种车牌(挂,警,学,领,港,澳)
    $regular = '/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[A-Z]{1}[0-9a-zA-Z]{4}[挂警学领港澳]{1}$/u';
    $result = preg_match($regular, $license, $match);
    if ($result) {
        return true;
    }
    // 匹配武警车牌
    $regular = '/^WJ[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]?[0-9a-zA-Z]{5}$/ui';
    $result = preg_match($regular, $license, $match);
    if ($result) {
        return true;
    }
    // 匹配军牌
    $regular = "/[A-Z]{2}[0-9]{5}$/";
    $result = preg_match($regular, $license, $match);
    if ($result) {
        return true;
    }
    // 匹配新能源车辆6位车牌
    # $regular = "/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[A-Z]{1}[DF]{1}[0-9a-zA-Z]{5}$/u";// 小型新能源车
    $regular = "/[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[0-9a-zA-Z挂学警港澳]{5,7}$/u";// 小型新能源车
    $result = preg_match($regular, $license, $match);
    if ($result) {
        return true;
    }
    $regular = "/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[A-Z]{1}[0-9a-zA-Z]{5}[DF]{1}$/u";//大型新能源车
    $result = preg_match($regular, $license, $match);
    if ($result) {
        return true;
    }
    return false;
}

function addHistory($data)
{
    $add_data['wohi_primary_id'] = $data['wohi_primary_id'];
    $add_data['wohi_state_name'] = $data['wohi_state_name'];
    $add_data['wohi_state'] = $data['wohi_state'];
    $add_data['wohi_type'] = $data['wohi_type'];////1订单2工单
    $add_data['wohi_create_time'] = date('Y-m-d H:i:s');
    $add_res = DB::table('work_order_history')->insert($add_data);
    return $add_res;
}

function computeTime($begin_time , $end_time = '' ){
    if($begin_time < $end_time){
        $starttime = $begin_time;
        $endtime = $end_time;
    }else{
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $starttime = strtotime($starttime);
    $endtime = strtotime($endtime);
    //计算天数
    $timediff = $endtime-$starttime;
    $days = intval($timediff/86400);
    //计算小时数
    $remain = $timediff%86400;
    $hours = intval($remain/3600);
    //计算分钟数
    $remain = $remain%3600;
    $mins = intval($remain/60);
    //计算秒数
    $secs = $remain%60;
    $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
    return $days.'天'.$hours.'小时'.$mins.'分钟';
}

function addHttpurl($url) {
    if (substr($url, 0, 4) != 'http') {
        $url = config('apisystem.server_name_https').'/'.$url;
    }
    return $url;
}

// 等比例复制图片
function copyImage($src, $newname)
{
    ini_set("memory_limit","-1");
    $filename=str_replace("images","image",$newname);
    $size = getimagesize($src);
    if (!$size){
        return false;
    }
    list($src_w, $src_h, $src_type) = $size;

    $src_mime = $size['mime'];
    switch ($src_type) {
        case 1 :
            $img_type = 'gif';
            break;
        case 2 :
            $img_type = 'jpeg';
            break;
        case 3 :
            $img_type = 'png';
            break;
        case 15 :
            $img_type = 'wbmp';
            break;
        default :
            return false;
    }

    //等比例缩放
    if (!isset($width)){
        $width = $src_w;
    }
    if (!isset($height)){
        $height = $src_h;
    }
    //根据上传的文件的类型来调用不同函数
    $imagecreatefunc = 'imagecreatefrom' . $img_type;
    $src_img = $imagecreatefunc($src);
    //新建一个真彩色图像
    $dest_img = imagecreatetruecolor($width, $height);
    //重采样拷贝部分图像并调整大小
    /**
     imagecopyresampled() 将一幅图像中的一块正方形区域拷贝到另一个图像中，平滑地插入像素值，
     因此，尤其是，减小了图像的大小而仍然保持了极大的清晰度。
     如果源和目标的宽度和高度不同，则会进行相应的图像收缩和拉伸。坐标指的是左上角。
     本函数可用来在同一幅图内部拷贝（如果 dst_image 和 src_image 相同的话）区域，但如果区域交迭的话则结果不可预知。
    */
    imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $width, $height, $src_w, $src_h);

    $imagefunc = 'image' . $img_type;
    if ($filename) {
        $imagefunc($dest_img, $filename);
    } else {
        header('Content-Type: ' . $src_mime);
        $imagefunc($dest_img);
    }

    //销毁文件资源
    imagedestroy($src_img);
    imagedestroy($dest_img);
    return true;


    /**
     * @name 修改图片大小 按照指定大小压缩
     * @param $filename：文件名
     * @param$tmpname：文件路径，如上传中的临时目录
     * @param $percent 为缩小比例
     * @param $img
     * @param $size
     * @param $tmpname
     * @param $xmax
     * @param $ymax
     * @param $type 是否删除原图片1删除2不删除
     * @author du
     * @date 2023/1/2
     * @Time: 9:07
     */
    function resizeImage($img,$size,$tmpname,$type = 1){
        //获取图片大小
        $s = @filesize($img); //echo $s; exit;
        $img_size = ceil($s/ 1000) . "k"; //获取文件大小

        if($img_size>$size){
            $percent = 0.7;
            list($width, $height) = getimagesize($img);

            $ii = getimagesize($img);
            $iimagen = explode('/', end($ii))[1];

            $new_width = $width * $percent;
            $new_height = $height * $percent;
            $image_p = @imagecreatetruecolor($new_width, $new_height);
            // $image = imagecreatefromjpeg($img);
            $image = getImgN($img,$iimagen);
            //print_r($image);
            @imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            $new_img = $tmpname.uniqid().'.'.$iimagen;
            @imagejpeg($image_p,$new_img); //输出保存图片
            if(file_exists($new_img)){
                if($type == 1) {
                    unlink($img);
                }
                return resizeImage($new_img,$size,$tmpname);
            }else{
                \App\Services\CommonService::addLog('新图片不存在', $new_img, '1111111111111','新图片不存在');
            }
        }else{
            return $img;
        }
    }
    //获取图片后缀名
    function getImgN($filename,$iimagen){
        switch($iimagen){
            case "png":
                $img_r = imagecreatefrompng($filename);
                break;
            case "jpg":
                $img_r = imagecreatefromjpeg($filename);
                break;
            case "jpeg":
                $img_r = imagecreatefromjpeg($filename);
                break;
            case "gif":
                $img_r = imagecreatefromgif($filename);
                break;
        }
        return $img_r;
    }
}
