<?php
namespace SRVX\Utils;


class Common 
{

    public static $set  = [];
    public static $skip = [];
    /**
     * 将数组或者字符串转为小驼峰或者下划线
     * @param  [type] $data    [description]
     * @param  string $outType [description]
     * @return [type]          [description]
     */
    public function camel_2_underline($data, $outType = 'camel')
    {
        if (is_string($data)) {
            return $this->$outType($data);
        }

        if (is_object($data) && (array)$data) {
            if (method_exists($data, 'toArray')) {
                $data = $data->toArray();
            } else {
                $data = (array)$data;
            }
        }

        if (is_array($data)) {
            foreach ($data as $key => $value) {
                $newKey = $this->camel_2_underline($key, $outType);
                if ($newKey != $key) {
                    unset($data[$key]);
                }

                // 填坑：数据里面保存了Url结尾的字段 比如image imageUrl(不需要的字段) 在循环里面后面的imageUrl会覆盖前面生成的imageUrl
                if (is_array($value) || (is_object($value) && (array)$value)) {  // 复合值
                    $data[$newKey] = $this->camel_2_underline($value, $outType);
                } else {  // 单值
                    // 已经有值了 不更新 防止覆盖前面生成好的
                    if (!array_key_exists($newKey, $data)) {  // 键已不存在
                        $data[$newKey] = $value;
                    }
                }

                /*if (!empty(self::$skip) && is_string($value) && $key == 'skip_identifier' && (strpos($value, 'pub.flutter') !== false) ) {
                    $data['skipName'] = !empty(self::$skip[$value]) ? self::$skip[$value] : '';
                }*/

                if (is_string($value) &&
                    !empty(self::$set) &&
                    ((strpos($value, '.png') !== false) || (strpos($value, '.gif') !== false) || (strpos($value, '.jpg') !== false) || (strpos($value, '.jpeg') !== false)) &&
                    (strpos($value, self::$set['file_bucket_host']) === false) &&
                    (strpos($value, 'http://') === false) &&
                    (strpos($value, 'https://') === false)
                ) {
                    $data[$newKey.'Url'] = self::$set['file_bucket_scheme'] . '://' . self::$set['file_bucket_host'] . '/' . $value;
                }

            }
        }

        return $data;
    }

    /**
     * 下划线转小驼峰
     */
    public function camel($string)
    {
        return preg_replace_callback(
            "/(_([a-z]))/",
            function ($match) {
                return strtoupper($match[2]);
            },
            $string
        );
    }

    /**
     * 小驼峰转下划线
     */
    public function underline($string)
    {
        return strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $string));
    }



    /**
     * [下载图片]
     * @param  [type] $url      [description]
     * @param  [type] $filename [description]
     * @return [type]           [description]
     */
    function download_img($url, $filename)
    {
        $savePath = dirname($filename);

        if (!is_dir($savePath)) {
            if (!mkdir($savePath, 0777, true)) {
                $returnData['status']  = false;
                $returnData['message'] = lang('l_error_create_file_directory');
                return $returnData;
            }
        }

        $fp = fopen($filename , 'w');
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $file = curl_exec($ch);
        curl_close($ch);
        fclose($fp);

        $returnData['status'] = true;
        $returnData['data']   = $filename;
        return $returnData;
    }

    /**
     * 阿拉伯数字转中文
     * @param $num
     * @return mixed|string
     */
    function numToWord($num)
    {
        $chiNum    = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
        $chiUni    = array('', '十', '百', '千', '万', '十', '百', '千', '亿');
        $chiStr    = '';
        $num_str   = (string)$num;
        $count     = strlen($num_str);
        $last_flag = true; //上一个 是否为0
        $zero_flag = true; //是否第一个
        $temp_num  = null; //临时数字
        $chiStr    = '';//拼接结果
        if ($count == 2) {//两位数
            $temp_num = $num_str[0];
            $chiStr   = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num] . $chiUni[1];
            $temp_num = $num_str[1];
            $chiStr   .= $temp_num == 0 ? '' : $chiNum[$temp_num];
        } else if ($count > 2) {
            $index = 0;
            for ($i = $count - 1; $i >= 0; $i--) {
                $temp_num = $num_str[$i];
                if ($temp_num == 0) {
                    if (!$zero_flag && !$last_flag) {
                        $chiStr    = $chiNum[$temp_num] . $chiStr;
                        $last_flag = true;
                    }

                    if ($index == 4 && $temp_num == 0) {
                        $chiStr = "万" . $chiStr;
                    }
                } else {
                    if ($i == 0 && $temp_num == 1 && $index == 1 && $index == 5) {
                        $chiStr = $chiUni[$index % 9] . $chiStr;
                    } else {
                        $chiStr = $chiNum[$temp_num] . $chiUni[$index % 9] . $chiStr;
                    }
                    $zero_flag = false;
                    $last_flag = false;
                }
                $index++;
            }
        } else {
            $chiStr = $chiNum[$num_str[0]];
        }
        return $chiStr;
    }

    public function group_by_key($array, $key)
    {
        $return = [];
        foreach($array as $val) {
            $return[$val[$key]][] = $val;
        }
        return $return;
    }

    public static function getRealIP()
    {
        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        }else{
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $ip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_IP')) {
                $ip = getenv('HTTP_CLIENT_IP');
            } else {
                $ip = getenv('REMOTE_ADDR');
            }
        }
        return $ip;
    }

    // 打印sql语句
    public static function toSql(\Phalcon\Mvc\Model\Query\BuilderInterface $builder) : string
    {
        $data = $builder->getQuery()->getSql();

        ['sql' => $sql, 'bind' => $binds, 'bindTypes' => $bindTypes] = $data;

        $finalSql = $sql;
        foreach ($binds as $name => $value) {
            $formattedValue = $value;

            if (\is_object($value)) {
                $formattedValue = (string)$value;
            }

            if (\is_string($formattedValue)) {
                $formattedValue = sprintf("'%s'", $formattedValue);
            }
            $finalSql = str_replace(":$name", $formattedValue, $finalSql);
        }

        return $finalSql;
    }
}