<?php
/**
 * Here is your custom functions.
 */

use support\Response;

if (!function_exists('http_post')) {
    function http_post($url, $params)
    {
        $ch = curl_init();
        $this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}

if (!function_exists('http_post_json')) {
    function http_post_json($url, $params)
    {
        try {
            $ch = curl_init();
            $this_header = array('Content-Type: application/json;charset=UTF-8');
            curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);

            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

            $output = curl_exec($ch);
            curl_close($ch);
            // 写日志
            if (is_json($output)) {
                \support\Log::info('模拟请求:', json_decode($output, true));
            } else {
                \support\Log::info('模拟请求，返回异常:', ['msg' => (string)$output]);
            }

            return $output;

        } catch (\Exception $e) {
            \support\Log::info('模拟请求失败:', ['msg' => $e->getMessage()]);
        }
    }
}

if (!function_exists('month_12')) {
    function month_12()
    {
        $months = [];
        for ($i = 0; $i < 12; $i++) {
            $months[$i] = date('Y/m', strtotime(date('Y-m-01') . "-" . $i . "month"));
        }

        return $months;
    }
}


/**
 * @Desc 管理员操作日志
 * @Author Gorden
 * @Date 2024/3/29 17:07
 *
 *  adminId = 1001 计划任务
 *
 *
 * @param $name
 * @param $operation
 * @return void
 */

if (!function_exists('_syslog')) {
    function _syslog($name, $operation, $operationData = false, $requestParams = false, $adminId = false)
    {
        try {
            $adminId = $adminId ? $adminId : \Tinywan\Jwt\JwtToken::getCurrentId();
        } catch (\Exception $e) {
            $adminId = 1001;
        }
        $logAdminId = $adminId;
        $model = new \app\model\SysLog();
        $model->log_admin_id = $logAdminId;
        $model->log_name = $name;
        $model->log_route = \request() && \request()->uri() ? \request()->uri() : (\request() && \request()->route && \request()->route->getPath() ? \request()->route->getPath() : '');
        $model->log_operation = $operation;
        $model->log_ip = \request() && \request()->getRealIp() ? \request()->getRealIp() : '0.0.0.0';
        $model->log_request_params = $requestParams ? json_encode($requestParams) : ($adminId == 1001 ? '[]' : json_encode(\request()->all()));
        $model->log_operation_data = $operationData ? json_encode($operationData) : null;
        $model->save();
    }
}

if (!function_exists('json_throw')) {
    function json_throw($code, $message, $data = '', $options = JSON_UNESCAPED_UNICODE)
    {
        $return = [
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ];

        return new \support\Response(200, ['Content-Type' => 'application/json'], json_encode($return, $options));
    }
}

if (!function_exists('json_success')) {
    function json_success($message, $data = '', $options = JSON_UNESCAPED_UNICODE)
    {
        $return = [
            'code' => 200,
            'message' => $message,
            'data' => $data,
        ];
        return new Response(200, ['Content-Type' => 'application/json'], json_encode($return, $options));
    }
}

if (!function_exists('json_fail')) {
    function json_fail($message, $options = JSON_UNESCAPED_UNICODE)
    {
        $return = [
            'code' => 0,
            'message' => $message,
            'data' => ''
        ];

        return new Response(200, ['Content-Type' => 'application/json'], json_encode($return, $options));
    }
}

if (!function_exists('format_string')) {
    function format_string($string)
    {
        return htmlspecialchars(strip_tags($string));
    }
}

if (!function_exists('random_string')) {
    function random_string($length, $type = 'all')
    {
        $string = 'abcdefghijklmnopqrstuvwxyz';
        $stringUp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $number = '0123456789';

        switch ($type) {
            case 'all':
                $result = $string . $number;
                break;
            case 'string':
                $result = $string;
                break;
            case 'up':
                $result = $stringUp . $number;
                break;
            case 'number':
                $result = $number;
                break;
            default:
                $result = '';
                break;
        }

        $return = '';
        $totalLength = strlen($result);
        for ($i = 0; $i < $length; $i++) {
            $return .= $result[mt_rand(0, $totalLength - 1)];
        }

        return $return;
    }
}

if (!function_exists('is_json')) {
    /**
     * @Desc 验证是否是json数据
     * @Author Gorden
     * @Date 2024/2/22 15:37
     *
     * @param $string
     * @return bool
     */
    function is_json($string)
    {
        if (!is_string($string)) {
            return false;
        }
        json_decode($string);
        if (json_last_error() === JSON_ERROR_NONE) {
            return true;
        }
        return false;
    }
}

if (!function_exists('chinese_week')) {
    /**
     * @Desc 周几-汉字
     * @Author Gorden
     * @Date 2024/3/5 17:29
     *
     * @param $week
     * @return string
     */
    function chinese_week($week)
    {
        $weekArray = ['日', '一', '二', '三', '四', '五', '六'];

        return '周' . $weekArray[$week];
    }
}

if (!function_exists('hexToRgb')) {
    /**
     * @Desc 颜色值转RGB
     * @Author Gorden
     * @Date 2024/5/15 17:22
     *
     * @param $hexColor
     * @return mixed
     */
    function hexToRgb($hexColor, $type = "string")
    {
        // 使用substr函数去掉前缀的'#'
        $hexColor = ltrim($hexColor, '#');

        // 使用hexdec函数将十六进制转换为十进制
        $red = hexdec(substr($hexColor, 0, 2));
        $green = hexdec(substr($hexColor, 2, 2));
        $blue = hexdec(substr($hexColor, 4, 2));
        if ($type == "string") {
            // rgb(46, 209, 153)
            return "rgb(" . $red . ", " . $green . ", " . $blue . ")";
        }

        return array('red' => $red, 'green' => $green, 'blue' => $blue);
    }
}


if (!function_exists('rgbToHex')) {
    function rgbToHex($rgb)
    {
        if (substr($rgb, 0, 3) == 'rgb') {
            $rgb = str_replace("rgb(", '', $rgb);
            $rgb = str_replace(")", "", $rgb);
            [$red, $green, $blue] = explode(',', $rgb);
            $hexRed = dechex($red);
            $hexGreen = dechex($green);
            $hexBlue = dechex($blue);

            // 如果颜色分量不足两位，前面补零
            $hexRed = strlen($hexRed) == 1 ? '0' . $hexRed : $hexRed;
            $hexGreen = strlen($hexGreen) == 1 ? '0' . $hexGreen : $hexGreen;
            $hexBlue = strlen($hexBlue) == 1 ? '0' . $hexBlue : $hexBlue;

            return "#" . $hexRed . $hexGreen . $hexBlue;
        }

        return "";
    }
}