<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function array_unique_fb($array2D)
{
    foreach ($array2D as $v)
    {
        $v = join(",",$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[] = $v;
    }
    $temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v)
    {
        $temp[$k] = explode(",",$v); //再将拆开的数组重新组装
    }
    return $temp;
}

function my_array_unique($array, $keep_key_assoc = false)
{
    $duplicate_keys = array();
    $tmp         = array();

    foreach ($array as $key=>$val)
    {
        // convert objects to arrays, in_array() does not support objects
        if (is_object($val))
            $val = (array)$val;

        if (!in_array($val, $tmp))
            $tmp[] = $val;
        else
            $duplicate_keys[] = $key;
    }

    foreach ($duplicate_keys as $key)
        unset($array[$key]);

    return $keep_key_assoc ? $array : array_values($array);
}

//根据URL获取月份
function getaqiMonth($url){
    $monArr = array('January','February','March','April','May','June','July','August','September','October','November','December');
    $monObj = array(
        'January' => '01',
        'February' => '02',
        'March' => '03',
        'April' => '04',
        'May' => '05' ,
        'June' => '06',
        'July' => '07',
        'August' => '08',
        'September' => '09',
        'October' => '10',
        'November' => '11',
        'December' => '12');
    $urlarr = explode("/",$url);
    $tmp = $urlarr[(count($urlarr)-1)];
    $tmp = ucfirst(str_ireplace('.htm','',$tmp));
    //$d=strtotime("00:01am ".$tmp." 15 2015");
    if(in_array($tmp,$monArr)){
        return $monObj[$tmp];
    }else{
        return false;
    }
}
/*!
 * @Author: LYT
 * @Date: 2019-06-27 10:32:11
 * @Desc: 异步的curl,1秒超时,被请求的地址需要设置: ignore_user_abort(true);
 */
function async_curl($url, $second = 1)
{
    log_message('error','Webht Async Call: '. $url);
    $ch = curl_init();
    $curlVersion = curl_version();
    $ua = "Webht (".PHP_OS.") PHP/".PHP_VERSION." CURL/".$curlVersion['version']." " . "AsyncJob";
    //设置超时
    curl_setopt($ch, CURLOPT_TIMEOUT, $second);
    curl_setopt($ch,CURLOPT_URL, $url);
    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);//严格校验
    }
    curl_setopt($ch,CURLOPT_USERAGENT, $ua);
    //设置header
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    //运行curl
    $data = curl_exec($ch);
    if (curl_errno($ch) && !in_array(curl_errno($ch),array(0,28)) ) {
        log_message('error',"Webht Async Curl Call 出错，错误码:" . curl_errno($ch) . ": " . curl_error($ch) . ",  url: " . $url);
    }
    if (!in_array(curl_getinfo($ch, CURLINFO_HTTP_CODE),array(0,200)) ) {
        log_message('error', "Webht Async Curl Call Request html Status Code: ".curl_getinfo($ch, CURLINFO_HTTP_CODE)."; curl url: ".$url);
    }
    curl_close($ch);
    return $data;
}

/*
 * 把数组元素组合为字符串
 * $container:用来包含元素的符号
 * $se:分隔符
 * $arr：需要重新组合的数组
 * 例如：$arr=['aaaa','bbbb'];myimplode("'",",",$arr);得到
 * 'aaaa','bbbb'
 */
function my_implode($container,$se,$arr)
{
    $str = "";
    if ($arr != '') {
        $str = "";
        $tcount = count($arr);
        $tcountInt = 0;
        foreach ($arr as $i) {
            $tcountInt++;
            if ($tcount == $tcountInt) {
                $str .= $container . $i . $container;
            } else {
                $str .= $container . $i . $container . $se;
            }
        }
    }
    return $str;
}
/*!
 * 解析订单号
 * @author LYT <lyt@hainatravel.com>
 * @date   2017-09-18
 * @param  [type]     $note_invoice_string [description]
 */
function analysis_orderid($note_invoice_string) {
    $data = array();

    //空字符串或者小于8位都属于不正确的订单号
    if (empty($note_invoice_string) || strlen($note_invoice_string) < 8) {
        return false;
    }

    //APP订单处理，如标题China Train Booking-160617462
    if ((strpos($note_invoice_string, 'China Train Booking') !== false) || (strpos($note_invoice_string, 'ChinaTrainBooking') !== false)) {
        $note_invoice_string = explode('-', $note_invoice_string);
        if (isset($note_invoice_string[1]) && $note_invoice_string[1] !== "ChinaTrainBooking") {
            $note_invoice_string = trim($note_invoice_string[1]);
        } elseif (isset($note_invoice_string[0]) && $note_invoice_string[0] !== "China Train Booking") {
            $note_invoice_string = trim($note_invoice_string[0]);
        }
        return json_encode(array('orderid' => $note_invoice_string, 'ordertype' => 'A', 'table' => 'biz')); //APP订单，不需要处理交易记录和通知
    }

    //订单号例子 160420021_B--9608
    //Tracking code:2016-05-06-JJ160319027 /Travel advisor:Fiona Jiang /Content:Shanghai, Beijing, Pingyao, Xian, Guilin, Yangshuo, S

    if (strpos($note_invoice_string, 'Tracking Code:') !== false) {
        $note_invoice_string = explode('Tracking Code:', $note_invoice_string);
        $note_invoice_string = explode('Travel Advisor', $note_invoice_string[1]);
        $note_invoice_string = trim($note_invoice_string[0]);
    }

    //订单号过滤
    $note_invoice_string = explode('--', $note_invoice_string);
    $note_invoice_string = $note_invoice_string[0];
    $note_invoice_string = explode('_', $note_invoice_string);

    //订单类型识别
    $ordertype = 'N';
    $table = null;
    if (isset($note_invoice_string[1])) {
        $ordertype_temp = trim($note_invoice_string[1]);
        if (substr($ordertype_temp, 0, 2) == 'TP') {
            $ordertype = 'TP';
            $table = 'biz';
        } elseif (substr($ordertype_temp, 0, 1) == 'T') {
            $ordertype = 'T';
            $table = 'tour';
        } elseif (substr($ordertype_temp, 0, 1) == 'B') {
            $ordertype = 'B';
            $table = 'biz';
        } elseif (substr($ordertype_temp, 0, 1) == 'A') {
            $ordertype = 'A';
            $table = 'biz';
        }
    }
    // 2018.05.28 for Trippest, tourMaster的订单号是01开头
    if (substr($note_invoice_string[0], 0, 2) == '01') {
        $ordertype = 'TP';
        $table = 'biz';
    }

    //手机订单、机票订单都没有加标示，在这里帮加上，暂时的，今后还是要在网前设置好
    if ($ordertype == 'N' && isset($note_invoice_string[0])) {
        $orderid_temp = $note_invoice_string[0];
        if (strlen($orderid_temp) == 9 && substr($orderid_temp, 0, 2) == '16') {
            $ordertype = 'B';
            $table = 'biz';
        }
    }

    //前台预付款订单，以45开头，如45117640类型的订单号，这个类型的订单会分配到某个新订单去，需要查找COLI_AddCode来找新订单号，然后再发送通知

    if ($ordertype == 'N' && isset($note_invoice_string[0])) {
        $orderid_temp = $note_invoice_string[0];
        if (strlen($orderid_temp) == 8 && substr($orderid_temp, 0, 2) == '45') {
            $ordertype = 'M';
            $table = null;
        }
    }
    //新的订单号14733661876255
    if ($ordertype == 'N' && isset($note_invoice_string[0])) {
        $orderid_temp = $note_invoice_string[0];
        if (strlen($orderid_temp) == 14 && substr($orderid_temp, 0, 2) == '14') {
            $ordertype = 'M';
            $table = null;
        }
    }

    if ($ordertype == 'N') {
        return false; //没有编号的订单直接显示错误，由人工分配
    }

    $note_invoice_string = $note_invoice_string[0];
    $note_invoice_string = explode(',', $note_invoice_string);
    $orderid = trim($note_invoice_string[0]);
    $temp_orderid = explode('-', $orderid);
    if (isset($temp_orderid[1])) {
        $orderid = trim($temp_orderid[1]);
    }
    $tempid = explode(' ', $orderid);
    $pm_orderid = $tempid[0]; //订单号

    if (empty($pm_orderid) || strlen($pm_orderid) < 8) {
        return false;
    }
    return json_encode(array('orderid' => $pm_orderid, 'ordertype' => $ordertype, 'table' => $table));
}
/**
 * 输出xml字符
 * @throws WxPayException
**/
function to_xml($arr)
{
    if(!is_array($arr) || count($arr) <= 0)
    {
        return false;
    }

    $xml = "<xml>";
    foreach ($arr as $key=>$val)
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    return $xml;
}

/**
 * 将xml转为array
 * @param string $xml
 * @throws WxPayException
 */
function from_xml($xml)
{
    if(!$xml){
        return false;
    }
    //将XML转为array
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}

/*!
 * 转换字符集编码
 * @param $data
 * @param $targetCharset
 * @return string
 */
function characet($data, $targetCharset) {
    if (!empty($data)) {
        $fileType = "UTF-8";
        if (strcasecmp($fileType, $targetCharset) != 0) {
            $data = mb_convert_encoding($data, $targetCharset, $fileType);
            // $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
        }
    }
    return $data;
}

function set_url_param($param_arr=array())
{
    parse_str(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY), $current_param);
    $param_arr = $current_param===null ? $param_arr : array_merge($current_param, $param_arr);
    return strstr($_SERVER['REQUEST_URI'],'?', true) . "?" . http_build_query($param_arr);
}

function calc_day_cnt($from, $to)
{
    $now = new DateTime($to);
    $start = new DateTime(($from));
    $date_d = $now->diff($start);
    $d_t = ($date_d->format("%a"));
    return $d_t;
}

function zero_to_one($value)
{
    return $value==0 ? 1 : $value;
}
