<?php
/**
 * 全局通用方法集合
 * ============================================================================
 * * 版权所有 蜘蛛出行 * *
 * 网站地址: http://www.zhizhuchuxing.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm Util.php
 * Create By 2017/2/22 19:44 $
 */


namespace common\util;


use yii\helpers\ArrayHelper;

class Util
{
    /**微信配置参数**/
    private static $weChatConfig = null;
    private static $siteConfig = null;

    /**
     * Des:获取配置参数
     * Name: getSiteConfig
     * @return null
     * @author 倪宗锋
     */
    public static function getSiteConfig()
    {
        if (static::$siteConfig == null) {
            static::$siteConfig = ArrayHelper::merge(
                require ROOT_PATH . '/common/config/siteConfig/' . YII_ENV . '/siteConfig.php',
                require ROOT_PATH . '/common/config/siteConfig.php'
            );
        }
        return static::$siteConfig;
    }

    /**
     * Des:设置siteConfig
     * Name: setSiteConfig
     * @param $array
     * @author 倪宗锋
     */
    public static function setSiteConfig($array)
    {
        $siteConfig = static::getSiteConfig();
        static::$siteConfig = ArrayHelper::merge(
            $siteConfig,
            $array
        );
    }

    /**
     * Function Description:返回成功Json数据到
     * Function Name: returnSu
     * @param string $msg 提示信息
     * @param string $url 跳转地址
     * @param string|array $data 需要传递的数据
     * @param string $code 错误码
     *
     * @return string
     *
     * @author 倪宗锋
     */
    public static function returnJsSu($msg = '', $data = '', $url = '', $code = '')
    {
        $return = array();
        $return['flag'] = true;
        $return['msg'] = $msg;
        $return['url'] = $url;
        $return['code'] = $code;
        $return['data'] = $data;
        return json_encode($return);
    }

    /**
     * Function Description:返回成功Json数据
     * Function Name: returnEr
     * @param string $msg 提示信息
     * @param string $url 跳转地址
     * @param string|array $data 需要传递的数据
     * @param string $code 错误码
     *
     * @return string
     *
     * @author 倪宗锋
     */
    public static function returnJsEr($msg = '', $data = '', $url = '', $code = '')
    {
        $return = array();
        $return['flag'] = false;
        $return['msg'] = $msg;
        $return['url'] = $url;
        $return['code'] = $code;
        $return['data'] = $data;
        return json_encode($return);
    }

    /**
     * Function Description:返回成功数组数据
     * Function Name: returnArrSu
     * @param string $msg 提示信息
     * @param string $url 跳转地址
     * @param string|array $data 需要传递的数据
     * @param string $code 错误码
     *
     * @return array
     *
     * @author 倪宗锋
     */
    public static function returnArrSu($msg = '', $data = '', $url = '', $code = '')
    {
        $return = array();
        $return['flag'] = true;
        $return['msg'] = $msg;
        $return['url'] = $url;
        $return['code'] = $code;
        $return['data'] = $data;
        return $return;
    }

    /**
     * Function Description:返回错误数组数据
     * Function Name: returnArrEr
     * @param string $msg 提示信息
     * @param string $url 跳转地址
     * @param string|array $data 需要传递的数据
     * @param string $code 错误码
     *
     * @return array
     *
     * @author 倪宗锋
     */
    public static function returnArrEr($msg = '', $data = '', $url = '', $code = '')
    {
        $return = array();
        $return['flag'] = false;
        $return['msg'] = $msg;
        $return['url'] = $url;
        $return['code'] = $code;
        $return['data'] = $data;
        return $return;
    }

    /**
     * Des:获取微信配置文件
     * Name: getWeChatConfig
     * @return null
     * @author 倪宗锋
     */
    public static function getWeChatConfig()
    {
        if (static::$weChatConfig == null) {
            static::$weChatConfig = require ROOT_PATH . '/common/config/wechatConfig/payConfig.php';
        }
        return static::$weChatConfig;
    }

    /**
     * Function Description:校验字符串的正则
     * Function Name: checkPattern
     * @param $type string 已有正则的key
     * @param $str string 校验的字符串
     * @param string $Regex 校验规则 固若该值不为空 则使用该正则校验  $type失效
     *
     * @return bool
     *
     * @author 倪宗锋 2016-11-10
     */
    public static function checkPattern($type, $str, $Regex = '')
    {
        if ($Regex == '') {
            $pattern = require(ROOT_PATH . '/common/config/checkParams.php');
            if (empty($pattern[$type])) {//正则不存在 则验证失败
                return false;
            }
            $Regex = $pattern[$type];
        }
        if (preg_match($Regex, $str)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Function Description:json转换为xml
     * Function Name: jsonToXml
     * @param $json
     *
     * @return bool|string
     *
     * @author 倪宗锋
     */
    public static function jsonToXml($json)
    {
        if (empty($json)) {
            return false;
        }
        $array = json_decode($json);
        $xml = '';
        $xml .= self::arrayToXml($array);
        return $xml;
    }

    /**
     * Function Description:数组转换xml
     * Function Name: change
     * @param $array
     *
     * @return string
     *
     * @author 倪宗锋
     */
    public static function arrayToXml($array)
    {
        $string = '<xml>';
        foreach ($array as $k => $v) {
            $string .= '<' . $k . '>';
            if (is_array($v) || is_object($v)) {//判断是否是数组，或者，对像
                $string .= self::arrayToXml($v);//是数组或者对像就的递归调用
            } elseif (is_numeric($v)) {
                $string .= $v;
            } else {
                $string .= '<![CDATA[' . $v . ']]>';
            }
            $string .= '</' . $k . '>';
        }
        $string .= '</xml>';
        return $string;
    }

    /**
     * Function Description:xml转换为json
     * Function Name: xml_to_json
     * @param $source
     *
     * @return string
     *
     * @author 倪宗锋
     */
    public static function xmlToJson($source)
    {
        if (is_file($source)) { //传的是文件，还是xml的string的判断
            $xml_array = simplexml_load_file($source);
        } else {
            $xml_array = simplexml_load_string(trim($source));
        }
        $json = json_encode($xml_array, true);
        return $json;
    }

    /**
     * Function Description:xml转换成数组
     * Function Name: xmlToArray
     * @param $source
     *
     * @return mixed
     *
     * @author 倪宗锋
     */
    public static function xmlToArray($source)
    {
        libxml_disable_entity_loader(true);
        $getResult = json_decode(json_encode(simplexml_load_string(trim($source), 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $getResult;
    }

    /** Function Description:加密解密函数
     * Function Name: authCode
     * @param $string
     * @param string $operation
     * @param int $expiry
     * @return string
     * @author 倪宗锋
     */
    static function authCode($string, $operation = 'DECODE', $expiry = 0)
    {
        $key = 'udM5A8S50eg8veH15dd0m601de7073N8Bcn7d1I8Res7C7o7z274D6y342I4C7t7';
        $ckey_length = 4;    // 随机密钥长度 取值 0-32;
        // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
        // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
        // 当此值为 0 时，则不产生随机密钥

        $key = md5($key);
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if ($operation == 'DECODE') {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc . str_replace('=', '', base64_encode($result));
        }

    }

    /**
     * Des: 生成二维码
     * Name: addQRCode
     * @param $qCode string 生成的内容
     * @param $QRFile string 二维码图片路径
     * @param int $reType 1：返回成功或失败 2 返回图片数据流
     * @param bool|false $isCreate 生成的图片是否保留 当$reType=2才会有效
     * @param bool $logo 是否添加logo图
     * @param string $logoUrl logo图地址
     * @return array
     * @author 倪宗锋
     */
    public static function addQRCode($qCode, $QRFile, $reType = 1, $isCreate = false, $logo = false, $logoUrl = '')
    {
        include ROOT_PATH . '/common/util/phpqrcode/phpqrcode.php';
        $value = $qCode;//二维码内容
        $errorCorrectionLevel = 'H';//容错级别
        $matrixPointSize = 6;//生成图片大小
        //生成二维码图片
        \QRcode::png($value, $QRFile, $errorCorrectionLevel, $matrixPointSize, 2);
        $QR = imagecreatefromstring(file_get_contents($QRFile));
        if ($logo !== FALSE && $logoUrl != '') {
            $logoUrl = imagecreatefromstring(file_get_contents($logoUrl));
            $QR_width = imagesx($QR);//二维码图片宽度
            $logo_width = imagesx($logoUrl);//logo图片宽度
            $logo_height = imagesy($logoUrl);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logoUrl, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);
        }
        //只返回成功失败的话 则图片必须保存
        if ($reType == 1) {
            @ImagePng($QR, $QRFile);
            if (file_exists($QRFile)) {
                return Util::returnArrSu();
            }
            return Util::returnArrEr('图片生成失败！');
        } else {
            //输出图片
            Header("Content-type: image/png");
            ImagePng($QR);
            if ($isCreate == false) {//不保存图片则删除
                @unlink($QRFile);
            } else {//保存则需图片再生成一次
                @ImagePng($QR, $QRFile);
            }
            die;
        }
    }

    /**
     * Function Description:调用CS接口时的加密规则
     * Function Name: authCodeForCs
     *
     * @return string
     *
     * @author 娄梦宁
     */
    public static function authCodeForCs($request_time)
    {
        $siteConfig = static::getSiteConfig();
        $user = $siteConfig['adm_user'];
        $user_key = $siteConfig['adm_user_key'];
        //加密规则为 request_time(linux时间戳)前三位作为种子，调用srand生成随机数 + user + user_key,进行MD5加密后，换成大写字母
        $auth_code = strtoupper(md5(substr($request_time, 0, 3) . "|" . $user . "|" . $user_key . "|" . substr($request_time, strlen($request_time) - 3, 3)));
        return $auth_code;
    }

    /**
     * Des:发送验证码
     * Name: sendMessage
     * @param $msg
     * @param $phone
     * @return array
     * @author 倪宗锋
     */
    public static function sendMessage($msg, $phone)
    {
        $siteConfig = static::getSiteConfig();
        $send_data = array();
        $send_data["account"] = "dh78301";
        $send_data["password"] = strtolower(md5("jGRk34B7"));
        $send_data["sign"] = "【{$siteConfig['web_name']}】";
        $send_data["phones"] = $phone;
        $send_data["content"] = $msg;
        $url = 'http://www.dh3t.com/json/sms/Submit';
        $curlInterface = new CurlInterface($send_data, 1);
        $result = $curlInterface->execute($url, 'POST');
        if (isset($result['result']) && $result['result'] == '0') {
            return Util::returnArrSu('验证码发送成功');
        }
        return Util::returnArrEr('验证码发送失败');
    }

    /**
     * 检测是微信还是支付宝 1、微信 2、支付宝
     * @return string
     */
    public static function checkWeChatOrAliPay()
    {
        $header = \Yii::$app->request->getHeaders();
        $user_agent = $header['user-agent'];
        //判断是不是微信
        if (preg_match('/MicroMessenger/i', $user_agent)) {
            return 1;
        }
        if (preg_match('/AlipayClient/i', $user_agent)) {
            return 2;
        }
        return 3;
    }

    /**
     * Des:发送信息到RTX
     * Name: sendMsgRTX
     * @param string $receiverList
     * @param $title
     * @param $msg
     * @author 倪宗锋
     */
    public static function sendMsgRTX($receiverList = 'nizf', $title, $msg)
    {
        $arr = array(
            'title' => $title . '【' . date('Y-m-d H:i:s', time()) . '】',
            'receiver' => $receiverList,
            'msg' => substr($msg, 0, 1024),
        );
        $curl = new CurlInterface($arr, 5);
        $curl->execute('http://180.168.4.58:8012/SendNotify.cgi', 'POST');
    }

    /**
     * Des:调用蜘蛛出行接口
     * Name: interfaceZzcx
     * @param $data array 传递参数
     * @param $url string 接口地址
     * @param $timeout int 超时秒数
     * @return array
     * @author 倪宗锋
     */
    public static function interfaceZzcx($data, $url, $timeout = 0)
    {
        $time = time();
        $data['time'] = $time;
        $param = [
            'code' => Util::authCode(http_build_query($data), 'ENCODE'),
            'time' => $time
        ];
        $curl = new CurlInterface($param, 4);
        if ($timeout != 0) {
            $curl->setTimeOut($timeout);
        }
        $siteConfig = Util::getSiteConfig();
        $return = $curl->execute($siteConfig['zzcx_host'] . $url, 'POST');
        return $return;
    }

    /**
     * Des:添加订单日志
     * Name: addOrderLog
     * @param $uid
     * @param $u_type
     * @param $order_id
     * @param $name
     * @param $log_type
     * @author 倪宗锋
     */
    public static function addOrderLog($uid, $u_type, $order_id, $name, $log_type)
    {
        $data = [];
        $data['uid'] = $uid;
        $data['u_type'] = $u_type;
        $data['order_id'] = $order_id;
        $data['name'] = $name;
        $data['log_type'] = $log_type;
        $url = '/zzcx/interfaces/fx/add-order-log';
        static::interfaceZzcx($data, $url);
    }

    /**
     * Des:添加用户操作日志
     * Name: addUserOrderLog
     * @param $title string 标题
     * @param $memo string 内容
     * @param $uid int 用户ID
     * @param $u_type int 1管理员，2分销商，3微信用户，4cs系统',
     * @param $order_id string 订单ID
     * @param $source_type 资源类型 1、产品，2、订单
     * @author 倪宗锋
     */
    public static function addUserOrderLog($title, $memo, $uid, $u_type, $order_id,$source_type)
    {
        $data = [];
        $data['title'] = $title;
        $data['memo'] = $memo;
        $data['uid'] = $uid;
        $data['u_type'] = $u_type;
        $data['source_id'] = $order_id;
        $data['source_type'] = $source_type;
        $url = '/zzcx/interfaces/fx/add-user-log';
        static::interfaceZzcx($data, $url);
    }
}