<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
mb_internal_encoding("UTF-8"); //解决汉字长度与字符长度不一致问题 验证length问题  开mb_string扩展
/**
 * 校验手机格式
 * @param $phone
 * @return int
 */
function check_mobile($phone){
    return preg_match("/1\d{10}$/",$phone);
}

/**
 * [check_email 校验邮箱格式]
 */
function check_email($email){
    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
    return preg_match($pattern,$email);
}

/**
 * 字符串截取,支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=false) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}

/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * @return string
 */
function think_encrypt($data, $key = '', $expire = 0) {
    $key  = md5(empty($key) ? config('app.encryption_key') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time():0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 (必须是think_encrypt方法加密的字符串)
 * @param  string $key  加密密钥
 * @return string
 */
function think_decrypt($data, $key = ''){
    $key    = md5(empty($key) ? config('app.encryption_key') : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);

    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

/**
 * 根据省份证号获取生日和性别
 * @param $idcard
 * @return array
 */
function get_birthday_sex_by_idcard($idcard){
    if(mb_strlen($idcard) != 18){
        return ['birthday'=>null,'gender'=>0];
    }
    $birthday = msubstr($idcard, 6, 8);
    $birthday = date('Y-m-d',strtotime($birthday));
    $gender = msubstr($idcard,16,1)%2;
    $gender = $gender?1:2;
    return ['birthday'=>$birthday,'gender'=>$gender];
}

/**
 * ajax 请求正确返回
 * @param string $msg
 * @param array $data
 * @return json
 */
function ajax_return_ok($data = array(),$msg = ''){
    $result['code'] = 0;
    $result['data'] = $data;
    $result['message'] = $msg ;
    header('Content-Type:application/json; charset=utf-8');
    if(version_compare(PHP_VERSION,'5.4.0','<')){
        exit(json_encode($result));
    }else{
        exit(json_encode($result,JSON_UNESCAPED_UNICODE)); //显示中文
    }
}

/**
 * ajax 请求错误返回
 * @param string $msg
 * @param string $code
 * @return json
 */
function ajax_return_error($msg = null,$code = 1){
    if ($msg == null){
        $msgDefault = config ( 'e_msg_default' );
        $result['msg'] = $msgDefault [$code];
    }else{
        $result['msg'] = $msg ;
    }
    $result['status'] = 0;
    $result['code'] = $code;
    header('Content-Type:application/json; charset=utf-8');
    if(version_compare(PHP_VERSION,'5.4.0','<')){
        exit(json_encode($result));
    }else{
        exit(json_encode($result,JSON_UNESCAPED_UNICODE)); //显示中文
    }
}

/**
 * AES 128 ecb 加密 与java加密保持一致
 * @param $data 加密字符串
 * @param $key 加密key
 * @return string 加密串
 */
function aes_encrypt($data) {
    $key = config('app.encryption_key');
    $data =  openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
    return base64_encode($data);
}

/**
 * AES 128 ecb 解密 与java加密保持一致
 * @param $data 解密字符串
 * @param $key 加密key
 * @return string 解密串
 */
function aes_decrypt($data) {
    $key = config('app.encryption_key');
    $encrypted = base64_decode($data);
    return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
}

/**
 * 下划线转驼峰
 * @param $str
 * @return string|string[]|null
 */
function line_to_hump($str){
    return preg_replace_callback('/(_[a-z])/', function ($match) {
        return ucfirst(trim($match[0], '_'));
    }, $str);
}

/**
 * 驼峰转下划线
 * @param $str
 * @return string|string[]|null
 */
function hump_to_line($str){
    return preg_replace_callback('/([A-Z])/', function ($match) {
        return '_' . lcfirst($match[0]);
    }, $str);
}

/**
 * 多维数组键值下划线转换为驼峰
 * @param $arr
 * @return array
 */
function array_change_line_to_hump($arr){
    $tem = [];
    foreach ($arr as $k=>$v){
        if(is_array($v)){
            $tem[line_to_hump($k)] = array_change_line_to_hump($v);
        }else{
            $tem[line_to_hump($k)] = $v;
        }
    }
    return $tem;
}

/**
 * 多维数组取某一字段
 * @param array $arr
 * @param string $field 要删除字段
 * @param string $child
 * @return array
 */
function array_delete_char($arr,$field,$child = 'depAndJobDtos'){
    $tem = [];
    foreach ($arr as $k=>$v){
        unset($v[$field]);
        if(!empty($v[$child])){
            $v[$child] = array_delete_char($v[$child],$field);
        }
        $tem[$k] = $v;
    }
    return $tem;
}

/**
 * 把返回的数据集转换成Tree  主要组织部门岗位人员树使用
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $child 子孙键名
 * @param int $root 父级值
 * @return array
 */
function list_to_tree($list, $pid = 'pid', $child = '_child', $root = 0)
{
    $tree = [];
    foreach($list as $k => $v){
        if($v[$pid] == $root){
            $children = list_to_tree($list, $pid, $child, $v['id']);
            if(!empty($v[$child])){
                $children = array_merge($children,$v[$child]);
            }
            $v[$child] = $children;
            $tree[] = $v;
        }
    }
    return $tree;
}

/**
 * 获取编号
 * @param $prefix
 * @return string
 */
function get_unique_id($prefix=''){
    return $prefix.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

// 获取9位随机数
function get_rand_num(){
    return mt_rand(100000000,999999999);
}

/**
 * flowjson排序
 * @param $flowJson
 * @param string $nodeid
 * @param array $result
 * @return array
 */
function sort_flow_json($flowJson,$nodeid='',&$result=[]){
    foreach ($flowJson as $k=>$v){
        if((!$nodeid && $v['type'] == 1) || $nodeid && $v['id'] == $nodeid){
            $result[] = $v;
            if(count($result) != count($flowJson)){
                sort_flow_json($flowJson,$v['nextId'],$result);
                break;
            }
        }
    }
    return $result;
}

/**
 * 获取合同编号
 * @param int $type 0=普通合同 1=追加合同
 * @param int $applyId 追加合同id
 */
function get_contact_sn($pre,$type=0,$applyId=0){
    return get_unique_id($pre);
}

/**
 *
 * @param $start
 * @param $end
 * @param $type
 * @return float|int
 */
function calculate_leave($start,$end,$type){
    $starts = explode(' ',$start);
    $ends = explode(' ',$end);
    $start = date('Ymd',strtotime($starts[0]));
    $stxt = $starts[count($starts) - 1]; // 去最后一个元素,以防日期与上下午之间存在多个空格,其中一端有这错误
    $end = date('Ymd',strtotime($ends[0]));
    $etxt = $ends[count($ends) - 1];
    if($start > $end){
        return 0;
    }

    $bxday = \think\Db::name('holiday')
        ->where('holiday',0)
        ->where('day','>=',date('Y-m-d',strtotime($starts[0])))
        ->where('day','<=',date('Y-m-d',strtotime($ends[0])))
        ->column('day');
    $bxday = $bxday?$bxday:[];

    $holiday = \think\Db::name('holiday')
        ->where('holiday',1)
        ->where('day','>=',date('Y-m-d',strtotime($starts[0])))
        ->where('day','<=',date('Y-m-d',strtotime($ends[0])))
        ->column('day');
    $holiday = $holiday?$holiday:[];

    $days = 0;
    $cday = (strtotime($end) - strtotime($start))/86400 + 1;
    for ($i=1;$i<=$cday;$i++){
        if($type == 1){ // 减去节假日
            $cur = strtotime($start) + ($i-1)*86400;
            $w = date('w',$cur);
            $itxt = date('Y-m-d',$cur);

            if($i == 1&&$stxt == '下午'){ // 开始日期
                $days += 0.5;
            } else if($i == $cday && $etxt == '上午'){
                $days += 0.5;
            }else{
                $days++;
            }

            /*if(($w == 6 || $w == 0) && in_array($itxt,$bxday)){ // 检查是否是补休日
                if($i == 1 && $stxt == '下午'){ // 开始日期
                    $days += 0.5;
                }else if($i == $cday && $etxt == '上午'){
                    $days += 0.5;
                }else{
                    $days++;
                }
            } else if($w >0 && $w < 6 && !in_array($itxt,$holiday)){
                if($i == 1&&$stxt == '下午'){ // 开始日期
                    $days += 0.5;
                } else if($i == $cday && $etxt == '上午'){
                    $days += 0.5;
                }else{
                    $days++;
                }
            }*/
        } else { // 不减节假日
            $days++;
        }
    }
    return $days;

}

/**
 * 计算社保比例金额
 * @param $money
 * @param $bl
 * @param $bl_type
 * @param $bl_extra
 * @param $free_bl
 * @return false|float
 */
function calculate_money($money,$bl,$bl_type,$bl_extra,$free_bl){
    $gjjp = $money*$bl;
    if($bl_extra > 0){
        if($bl_type == 1){ // 比例
            $gjjp += $money*$bl_extra;
        } else { // 整数
            $gjjp += $bl_extra;
        }
    }
    $gjjp = $gjjp*(1 - $free_bl);
    return round($gjjp,2);
}

/**
 * 极光推送
 * @param array $userids
 * @param string $msg
 * @param array $extras
 */
function send_jpush($userids,$msg='',$extras=array()){
    try { //不管推送成功与失败,不能影响正常业务流程
        $jpushconfig = config('app.jpush');
        $client = new \JPush\Client($jpushconfig['appkey'], $jpushconfig['mastersecret'],null);
        $push = $client->push();
        $push->setOptions(null,null,null, true);
        $push->setPlatform(array('ios', 'android'));
        foreach ($userids as $k=>$v){
            $userids[$k] = (string)$v;
        }
        $push->addAlias($userids);
        $push->androidNotification($msg, array(
            'extras' => $extras
        ));
        $sound = 'default';
        $push->iosNotification($msg, array(
            'sound' => $sound,
            'badge' => '+1',
            'extras' => $extras
        ));
        $ret = $push->send();
        trace($ret);
    } catch (Exception $e) {
        trace('push-error:',$e->getMessage());
    }
}

/**
 * 计算年龄/工龄
 * @param $date
 * @return false|mixed|string
 */
function calculate_age($date){
    list($year,$month,$day) = explode("-",$date);
    $year_diff = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff  = date("d") - $day;
    if($month_diff > 0){ // 生日已过
        return $year_diff;
    }else if($month_diff == 0){ // 生日已过
        if($day_diff >= 0){ //
            return $year_diff;
        }else{
            return $year_diff - 1;
        }
    }else{
        return $year_diff - 1;
    }
}

// 过滤以逗号分隔的内容,去掉空项
function check_exp_imp($data){
    if(!$data){
        return '';
    }
    $vals = explode(',',$data);
    $nr = [];
    foreach ($vals as $v){
        if($v && !in_array($v,$nr)){
            $nr[] = $v;
        }
    }
    return empty($nr)?'':implode(',',$nr);
}

function curl_post($url, $data=[]) {
    try{
        $ch = curl_init ();
        $header = array ("Accept-Charset: utf-8",'Expect:' );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
        curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );
        // 最好加上http_build_query 转换,防止有些服务器不兼容
        if($data){
            curl_setopt ( $ch, CURLOPT_POSTFIELDS, http_build_query ( $data ) );
        }
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        $result = curl_exec ( $ch );
        curl_close ( $ch );
        return $result;
    }catch (Exception $e){
        return false;
    }
}

function is_utf8($string) {

    // From http://w3.org/International/questions/qa-forms-utf-8.html
    return preg_match('%^(?:
          [\x09\x0A\x0D\x20-\x7E]            # ASCII
        | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
        |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
        |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
        |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
        | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
        |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
    )*$%xs', $string);

}

// 获取当前售卖日期
function get_dinner_day(){
    $week = date('w');
    $day = date('Y-m-d',time() + 24*60*60);
    if($week == 5){
        $day = date('Y-m-d',time() + 3*24*60*60);
    }else if($week == 6){
        $day = date('Y-m-d',time() + 2*24*60*60);
    }
    return $day;
}

/**
 * 根据日期获取上一月
 * @param $day
 */
function get_lastmonth_by_day($day){
    $year = date('Y',strtotime($day));
    $month = date('m',strtotime($day));
    if($month == 1){
        $lastmonth = ($year-1).'-12';
    }else if($month <= 10){
        $lastmonth = $year.'-0'.($month-1);
    }else{
        $lastmonth = $year.'-'.($month-1);
    }
    return $lastmonth;
}


function get_attentance_srecord($records,$val){
    $sarr = [];
    $ids = [];
    foreach ($records as $k => $v){
        $ct = strtotime($v['create_time']);
        $st = strtotime($val['stime']);
        $et = strtotime($val['etime']);
        if($ct < $et && $ct > $st){ // 迟到
            $v['cate'] = 1;
            $v['status'] = 1;
            $sarr[] = $v;
            $ids[] = $k;
            break;
        }else if($ct <= $st){ // 正常上班
            $v['cate'] = 1;
            $v['status'] = 0;
            $sarr[] = $v;
            $ids[] = $k;
            break;
        }else if($ct >= $et){ // 缺卡

        }
    }
    $lastrecords = [];
    foreach ($records as $k=>$v){
        if(!in_array($k,$ids)){
            $lastrecords[] = $v;
        }
    }

    return ['arr' => $sarr,'record' => $lastrecords];
}

function get_attentance_erecord($records,$val,$nstart=''){
    $sarr = [];
    $ids = [];
    foreach ($records as $k => $v){
        if(!$nstart){ // 最后一班
            $ct = strtotime($v['create_time']);
            $et = strtotime($val['etime']);
            $v['cate'] = 2;
            if($ct < $et){ // 早退
                $v['status'] = 2;
            }else if($ct >= $et){ // 正常下班
                $v['status'] = 0;
            }
            $sarr[] = $v;
            $ids[] = $k;
        }else{
            $ct = strtotime($v['create_time']);
            $et = strtotime($val['etime']);
            $nst = strtotime($nstart);
            $v['cate'] = 2;
            $v['status'] = 0;
            if($ct < $et){ // 早退
                $v['status'] = 2;
                $sarr[] = $v;
                $ids[] = $k;
            }else if($ct >= $et && $ct < $nst){ // 正常下班
                $v['status'] = 0;
                $sarr[] = $v;
                $ids[] = $k;
                break;
            }
        }

    }
    $lastrecords = [];
    foreach ($records as $k=>$v){
        if(!in_array($k,$ids)){
            $lastrecords[] = $v;
        }
    }

    return ['arr' => $sarr,'record' => $lastrecords];
}