<?php

use think\Db;
use think\helper\Time;

/**
 * @name post请求
 * @param $url
 * @param $data
 * @return bool|string
 */
function curl_post($url, $data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $return = curl_exec($ch);
    curl_close($ch);
    return $return;
}

/**
 * @name get请求
 * @param $url
 * @return mixed
 */
function curl_get($url)
{
    $ch = curl_init();
    // 设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    } else {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);//严格校验
    }
    // 执行并获取HTML文档内容
    $output = curl_exec($ch);
    // 释放curl句柄
    $err_code = curl_errno($ch);
    curl_close($ch);

    return json_decode($output);
}

if(!function_exists('public_path')){
    function public_path($path){
        return CMF_ROOT."public/upload/".$path;
    }
}

/*************** 校验身份证 start *******************/
if(!function_exists('checkIdCard')){
    function checkIdCard($idc){
        if(empty($idc)){
            return false;
        }
        $idcard = $idc;
        $City = array(11=>"北京",12=>"天津",13=>"河北",14=>"山西",15=>"内蒙古",21=>"辽宁",22=>"吉林",23=>"黑龙江",31=>"上海",32=>"江苏",33=>"浙江",34=>"安徽",35=>"福建",36=>"江西",37=>"山东",41=>"河南",42=>"湖北",43=>"湖南",44=>"广东",45=>"广西",46=>"海南",50=>"重庆",51=>"四川",52=>"贵州",53=>"云南",54=>"西藏",61=>"陕西",62=>"甘肃",63=>"青海",64=>"宁夏",65=>"新疆",71=>"台湾",81=>"香港",82=>"澳门",91=>"国外");
        $iSum = 0;
        $idCardLength = strlen($idcard);
        //长度验证
        if(!preg_match('/^\d{17}(\d|x)$/i',$idcard) and !preg_match('/^\d{15}$/i',$idcard))
        {
            return false;
        }
        //地区验证
        if(!array_key_exists(intval(substr($idcard,0,2)),$City))
        {
            return false;
        }
        // 15位身份证验证生日，转换为18位
        if ($idCardLength == 15)
        {
            $sBirthday = '19'.substr($idcard,6,2).'-'.substr($idcard,8,2).'-'.substr($idcard,10,2);
            //    $d = new DateTime($sBirthday);
            //    $dd = $d->format('Y-m-d');
            //    if($sBirthday != $dd)
            if($sBirthday != $sBirthday)
            {
                return false;
            }
            $idcard = substr($idcard,0,6)."19".substr($idcard,6,9);//15to18
            $Bit18 = getVerifyBit($idcard);//算出第18位校验码
            $idcard = $idcard.$Bit18;
        }
        // 判断是否大于2078年，小于1900年
        $year = substr($idcard,6,4);
        if ($year<1900 || $year>2078 )
        {
            return false;
        }

        //18位身份证处理
        $sBirthday = substr($idcard,6,4).'-'.substr($idcard,10,2).'-'.substr($idcard,12,2);
        //    var_dump($sBirthday);
        //    $d = new DateTime($sBirthday);

        //    $dd = $d->format('Y-m-d');
        //    echo $dd;
        //    die();
        //    if($sBirthday != $dd)
        if($sBirthday != $sBirthday)
        {
            return false;
        }
        //身份证编码规范验证
        $idcard_base = substr($idcard,0,17);
        if(strtoupper(substr($idcard,17,1)) != getVerifyBit($idcard_base))
        {
            return false;
        }
        return true;
    }
}

// 计算身份证校验码，根据国家标准GB 11643-1999
if(!function_exists('getVerifyBit')){
    function getVerifyBit($idcard_base)
    {
        if(strlen($idcard_base) != 17)
        {
            return false;
        }
        //加权因子
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        //校验码对应值
        $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        $checksum = 0;
        for ($i = 0; $i < strlen($idcard_base); $i++)
        {
            $checksum += substr($idcard_base, $i, 1) * $factor[$i];
        }
        $mod = $checksum % 11;
        $verify_number = $verify_number_list[$mod];
        return $verify_number;
    }
}

function getTime($nian=0,$yue=0){
    if(empty($nian) || empty($yue)){
        $now = time();
        $nian = date("Y",$now);
        $yue =  date("m",$now);
    }
    $time['begin'] = mktime(0,0,0,$yue,1,$nian);
    $time['end'] = mktime(23,59,59,($yue+1),0,$nian);
    return $time;
}

/**
 * 发送站内信息
 */
function siteMessage($content='',$siteurl='',$user_id=0,$type=1,$distributor_id=0,$membership_id=0){
    if(empty($content))
        return;
    if(!isset($user_id)||empty($user_id)){
        return;
    }
    $data['user_id']=$user_id;
    $data['add_time']=time();
    $data['content']=$content;
    $data['siteurl']=$siteurl;
    $data['type']=$type;
    $data['distributor_id']=$distributor_id;
    $data['membership_id']=$membership_id;
    Db::name('user_message')->insert($data);
    return true;
    //}
}

/**
 * 获取七天记录
 */
function week7(){
    $week=array();
    for($i=0;$i<7;$i++){
        array_push($week,Time::daysAfter(-$i));
    }

    return $week;
}

/**
 * 获取七天记录
 */
function week7_day(){
    $week=array();
    for($i=1;$i<7;$i++){
        array_push($week,date('Y-m-d',Time::daysAfter(-$i)));
    }

    return $week;
}

function get_date1($start,$end){
    $start_time=strtotime($start);
    $end_time=strtotime($end);
    $date=array();
    $days=($end_time - $start_time) / 86400;
//    $weekArr=array('星期日','星期一','星期二','星期三','星期四','星期五','星期六');
    for($i=0;$i<=$days;$i++){
//        $num_week=date("w",$start+($i*86400));
      //  echo date('Y-m-d',$start+($i*86400)).'-----'.$weekArr[$num_week].'</br>';
        array_push($date,date('Y-m-d',$start_time+($i*86400)));
    }

    return $date;
}

/***
 * @param $fields 驼峰对象
 * @return array
 */
function CamelToUnderLineArr($fields)
{
    $newArr = [];
    if (!is_array($fields) || !array_values($fields))  return $newArr;

    foreach ($fields as $key => $v) {
        $keyTmp = strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $key));
        $newArr[$keyTmp] = $v;
        unset($fields->$key);
    }

    return $newArr;
}


/***
 * @param $fields 下划线数组
 * @return \stdClass
 */
function underLineArrTOCamel($fields)
{

    $newObj = new \stdClass();
    if(!is_array($fields) || !$fields) return null;
    foreach ($fields as $key => $v) {
        $keyTmp = array_reduce(explode('_',$key), function($v1, $v2) {
            return ucfirst($v1).ucfirst($v2);
        });
        $keyTmp = lcfirst($keyTmp);
        $newObj->$keyTmp = $v;
        unset($fields[$key]);
    }
    return $newObj;
}


/*
 * 下划线转驼峰
 */
function convertUnderline($str)
{
    $str = preg_replace_callback('/([-_]+([a-z]{1}))/i',function($matches){
        return strtoupper($matches[2]);
    },$str);
    return $str;
}

/*
 * 驼峰转下划线
 */
function humpToLine($str){
    $str = preg_replace_callback('/([A-Z]{1})/',function($matches){
        return '_'.strtolower($matches[0]);
    },$str);
    return $str;
}

function xoc($xoc,&$res=0,$y=1){

    $a = str_split($xoc, 2);
    $num=count($a);
    //echo $y;
    $b = $a[$y];
    if($res==0){
        $i =hexdec($a[0]) ;
    }else{
        $i=$res;
    }

    //var_dump($i .'^'.hexdec($b));
    $c = $i ^ hexdec($b);
    if($y<$num-1){
        return xoc($xoc,$c,$y+1);
    }else{
        return dechex($c);
    }
}

/**
 **字符串转16进制
 **/
function String2Hex($string){
    $hex='';
    for ($i=0; $i < strlen($string); $i++){
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}

/**
 **16进制转字符串
 **/

function Hex2String($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}


#@param check_code|校验码 为空是计算校验码，不为空为验证校验码
function bcc($msg, $check_code = '') {
    //按两位字符切割字符串
    $check_str_array = str_split($msg, 2);
    $str_len = count($check_str_array);

    $xor = hexdec($check_str_array[0]);

    for ($i = 1; $i < $str_len; $i++) {
        $xor ^= hexdec($check_str_array[$i]);
    }
    $xor = dechex($xor);
    $xor = str_pad($xor, 2, 0, STR_PAD_LEFT); #不足两位前面填充0
    if (!$check_code) {
        return $xor;
    }
    return $xor == $check_code;
}

/**
 * @name 企业微信
 * @param $config
 */
function work(array $config){
    return \EasyWeChat\Factory::work($config);
}