<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace common\libs;

/**
 * Description of MyLib
 *
 * @author zengchaoxin
 */
class MyLib {
    //put your code here
    static public function randomStr($len,$isnum=false)
    {
        $str = '23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';//62个字符
        $strlen = strlen($str);
        if($isnum)
        {
            $str = '1234567890';
            $strlen = strlen($str);
        }
        while($len > $strlen){
            $str .= $str;
            $strlen += strlen($str);
        }
        $str = str_shuffle($str);
        return substr($str,0,$len);
    }
    
    static public function hashPwd($password,$salt)
    {
        return md5(md5($password).$salt);
    }

    static public function substr_cut($str_cut,$length)
    {
        $string = trim($str_cut);
        $len = mb_strlen($string, 'utf-8');
        if($length && $len > $length) {
            //utf8编码
            $wordscut = mb_substr($string, 0, $length);

            $string = $wordscut.'...';
        }
        return trim($string);
    }

    static public function getPageInfo($pagination)
    {
        $links = $pagination->getLinks();

        $str_page = "";
        if(isset($links['first'])) {
            $str_page = $str_page.' [<a href="'.$links['first'].'">首页</a>]';
        } else {
            $str_page = $str_page.' 首页';
        }
        if(isset($links['prev'])) {
            $str_page = $str_page.' [<a href="'.$links['prev'].'">上一页</a>]';
        } else {
            $str_page = $str_page.' 上一页';
        }
        if(isset($links['next'])) {
            $str_page = $str_page.' [<a href="'.$links['next'].'">下一页</a>]';
        } else {
            $str_page = $str_page.' 下一页';
        }
        if(isset($links['last'])) {
            $str_page = $str_page.' [<a href="'.$links['last'].'">末页</a>]';
        } else {
            $str_page = $str_page.' 末页';
        }
        $str_page = $str_page.' 页次：<strong><font color=""#990000"">'.($pagination->getPage()+1).'</font> / '.$pagination->getPageCount().' </strong>';
        $str_page = $str_page.' 共：<strong>'.$pagination->totalCount.'</strong> 条记录 <strong>'.$pagination->getPageSize().'</strong> 条/页 ';
        $str_page = $str_page.'转到<INPUT id=new_page  size=1 name=new_page value='.($pagination->getPage()+1).'>页<INPUT id=go onclick="{location.href=\''.str_replace('?page=1&','?',$pagination->createUrl(0)).'&page=\' + document.getElementById(\'new_page\').value + \'\';}" type=button value="GO" name=go>';

        return $str_page;
    }

    static public function getAjaxPageInfo($pagination,$idname)
    {
        $links = $pagination->getLinks();

        $str_page = "";
        if(isset($links['first'])) {
            $str_page = $str_page.' [<a href="javascript:;" onclick="gotoPage(\''.$links['first'].'\',\''.$idname.'\')">首页</a>]';
        } else {
            $str_page = $str_page.' 首页';
        }
        if(isset($links['prev'])) {
            $str_page = $str_page.' [<a href="javascript:;" onclick="gotoPage(\''.$links['prev'].'\',\''.$idname.'\')">上一页</a>]';
        } else {
            $str_page = $str_page.' 上一页';
        }
        if(isset($links['next'])) {
            $str_page = $str_page.' [<a href="javascript:;" onclick="gotoPage(\''.$links['next'].'\',\''.$idname.'\')">下一页</a>]';
        } else {
            $str_page = $str_page.' 下一页';
        }
        if(isset($links['last'])) {
            $str_page = $str_page.' [<a href="javascript:;" onclick="gotoPage(\''.$links['last'].'\',\''.$idname.'\')">末页</a>]';
        } else {
            $str_page = $str_page.' 末页';
        }
        $str_page = $str_page.' 页次：<strong><font color=""#990000"">'.($pagination->getPage()+1).'</font> / '.$pagination->getPageCount().' </strong>';
        $str_page = $str_page.' 共：<strong>'.$pagination->totalCount.'</strong> 条记录 <strong>'.$pagination->getPageSize().'</strong> 条/页 ';

        return $str_page;
    }

    static public function Get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }

    static public function Post($curlPost, $url, $cookie_flag = false, $headers = [])
    {
        $cookie = \Yii::$app->getRuntimePath() . '/cookie_tmp.txt';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        if(!$cookie_flag) {
            curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
        } else {
            curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie); //读取cookie
        }
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (count($headers) > 0) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }

    static public function getIP()
    {
        global $HTTP_SERVER_VARS;
        if (isset($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]))
        {
            $ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
        }
        elseif ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])
        {
            $ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
        }
        elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"])
        {
            $ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        }
        elseif (getenv("HTTP_X_FORWARDED_FOR"))
        {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        }
        elseif (getenv("HTTP_CLIENT_IP"))
        {
            $ip = getenv("HTTP_CLIENT_IP");
        }
        elseif (getenv("REMOTE_ADDR"))
        {
            $ip = getenv("REMOTE_ADDR");
        }
        else
        {
            $ip = "Unknown";
        }
        return $ip ;
    }

    static public function encrypt($string, $operation = 'ENCODE', $key = '', $expiry = 0){
        if($operation == 'DECODE') {
            $string =  str_replace('_', '/', $string);
            $string =  str_replace('%20', '+', $string);
        }
        $key_length = 4;
        $fixedkey = md5($key);
        $egiskeys = md5(substr($fixedkey, 16, 16));
        $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
        $keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
        $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));

        $i = 0; $result = '';
        $string_length = strlen($string);
        for ($i = 0; $i < $string_length; $i++){
            $result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
        }
        if($operation == 'ENCODE') {
            $retstrs =  str_replace('=', '', base64_encode($result));
            $retstrs =  str_replace('/', '_', $retstrs);
            return $runtokey.$retstrs;
        } else {
            if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        }
    }
    static public function zhifufs($cx){
        $cn = '未知';
        if($cx==1) {
            $cn='上门收费';
        }elseif($cx==2){
            $cn='在线支付';
        }elseif($cx==3){
            $cn='客户自上门';
        }
        return $cn;
    }
    static public function payers($cx){

        if($cx==1) {
            $cn='公司支付';
        }elseif($cx==2){
            $cn='客户支付';
        }elseif($cx==3){
            $cn='合作方支付';
        }
        return $cn;
    }
    static public function duizhang($cx){

        if($cx==1) {
            $cn='未支付';
        }elseif($cx==2) {
            $cn = '已支付';
        }
        return $cn;
    }
    static public function hkstatus($cx){

        if($cx==1) {
            $cn='未回款';
        }elseif($cx==2) {
            $cn = '已回款';
        }
        return $cn;
    }

    /**
     * 操作失败时。yangchangdong
     */
    public static function error3($msg,$param=[],$code=400)
    {
        $result = array();
        $result['code'] = $code;
        $result['msg'] = $msg;
        $result['param'] = $param;

        return $result;
    }
    /**
     * 操作成功时。yangchangdong
     */
    public static function ok3($data,$msg="操作成功")
    {
        $result = array();
        $result['code'] = 200;
        $result['msg'] = $msg;
        $result['data'] = $data;

        return $result;
    }

    static public function phoneCenterStatus($cx){
        if($cx=='ANSWERED') {
            $cn='通话成功';
        }elseif($cx=='BUSY') {
            $cn = '被叫忙';
        }elseif($cx=='NO_ANSWER') {
            $cn = '被叫无应答';
        }elseif($cx=='REJECT') {
            $cn = '被叫拒接';
        }elseif($cx=='HANGUP') {
            $cn = '主叫提前挂机';
        }elseif($cx=='INVALID_NUMBER') {
            $cn = '空号';
        }elseif($cx=='POWER_OFF') {
            $cn = '关机';
        }elseif($cx=='UNAVAILABLE') {
            $cn = '暂时无法接听';
        }elseif($cx=='SUSPEND') {
            $cn = '停机';
        }elseif($cx=='TP_NO_BINDING') {
            $cn = '无绑定关系';
        }elseif($cx=='TP_TIMEOUT') {
            $cn = '号码查询接口超时';
        }elseif($cx=='BLACK') {
            $cn = '黑名单号码';
        }elseif($cx=='YKT_BLACK') {
            $cn = '平台黑名单';
        }elseif($cx=='TP_ERROR') {
            $cn = '号码查询接口解析错误';
        }elseif($cx=='NO_URL_QUERY') {
            $cn = '企业未配置查询接口';
        }elseif($cx=='CALLED_BLACK') {
            $cn = '被叫不支持';
        }elseif($cx=='CALL_FORWARD') {
            $cn = '呼叫转移';
        }elseif($cx=='B_DISABLED') {
            $cn = '企业账户异常';
        }elseif($cx=='N_DISABLED') {
            $cn = '号码异常，本次通话虚号异常(被投诉或其他原因)，已冻结 ';
        }elseif($cx=='HIGH_FREQUENCY') {
            $cn = '高频呼叫标识';
        }elseif($cx=='CS_ILLEGAL') {
            $cn = '主显号码不支持，显示号码(被叫来电号码)不支持';
        }elseif($cx=='INSUFFICIENT') {
            $cn = '企业余额不足';
        }elseif($cx=='CALLED_RISKY') {
            $cn = '被叫存在风险';
        }elseif($cx=='OTHER') {
            $cn = '其他失败情形';
        }
        return $cn;
    }

    static public function HMSByTime($time){
        $h=$i=$s=0;
        if($time >= 3600){
            $h = floor($time/3600);
            $time = ($time%3600);
        }
        if($time >= 60){
            $i = floor($time/60);
            $time = ($time%60);
        }
        $s = floor($time);
        return $h.':'.$i.':'.$s;
    }

    static public function HMSByTimeBuy($time)
    {
        $i = 0;
        if($time > 0 && $time <60){
            $i = 1;
        }elseif($time >= 60){
            $i = ceil($time/60);
        }
        return $i;
    }

    static public function StartsWith($haystack, $needle){
        return strncmp($haystack, $needle, strlen($needle)) === 0;
    }

    static public function EndsWith($haystack, $needle)
    {
        return $haystack != '' && $needle != '' && substr_compare($haystack, $needle, -strlen($needle)) === 0;
    }
}
