<?php
// 應用公共文件
use think\facade\Db;

function getUrl(){
    // $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $protocol = $_SERVER['REQUEST_SCHEME'].'://';
    
    $http = $_SERVER['HTTP_HOST'];
    
    return $protocol.$http;
}

/**
 * 載入配置信息
 *
 * @access  public
 * @return  array
 */
function load_config()
{
    $arr = [];

    // $data = read_static_cache('shop_config');
    // if ($data === false)
    // {

        $res = Db::name('shop_config')
        ->field('code, value')
        ->where('parent_id','>',0)
        ->select();


        foreach ($res as $row)
        {
            $arr[$row['code']] = $row['value'];
        }

        /* 對數值型設置處理 */
        $arr['watermark_alpha']      = intval($arr['watermark_alpha']);
        $arr['market_price_rate']    = floatval($arr['market_price_rate']);
        $arr['integral_scale']       = floatval($arr['integral_scale']);
        //$arr['integral_percent']     = floatval($arr['integral_percent']);
        $arr['cache_time']           = intval($arr['cache_time']);
        $arr['thumb_width']          = intval($arr['thumb_width']);
        $arr['thumb_height']         = intval($arr['thumb_height']);
        $arr['image_width']          = intval($arr['image_width']);
        $arr['image_height']         = intval($arr['image_height']);
        $arr['best_number']          = !empty($arr['best_number']) && intval($arr['best_number']) > 0 ? intval($arr['best_number'])     : 3;
        $arr['new_number']           = !empty($arr['new_number']) && intval($arr['new_number']) > 0 ? intval($arr['new_number'])      : 3;
        $arr['hot_number']           = !empty($arr['hot_number']) && intval($arr['hot_number']) > 0 ? intval($arr['hot_number'])      : 3;
        $arr['promote_number']       = !empty($arr['promote_number']) && intval($arr['promote_number']) > 0 ? intval($arr['promote_number'])  : 3;
        $arr['top_number']           = intval($arr['top_number'])      > 0 ? intval($arr['top_number'])      : 10;
        $arr['history_number']       = intval($arr['history_number'])  > 0 ? intval($arr['history_number'])  : 5;
        $arr['comments_number']      = intval($arr['comments_number']) > 0 ? intval($arr['comments_number']) : 5;
        $arr['article_number']       = intval($arr['article_number'])  > 0 ? intval($arr['article_number'])  : 5;
        $arr['page_size']            = intval($arr['page_size'])       > 0 ? intval($arr['page_size'])       : 10;
        $arr['bought_goods']         = intval($arr['bought_goods']);
        $arr['goods_name_length']    = intval($arr['goods_name_length']);
        $arr['top10_time']           = intval($arr['top10_time']);
        $arr['goods_gallery_number'] = intval($arr['goods_gallery_number']) ? intval($arr['goods_gallery_number']) : 5;
        $arr['no_picture']           = !empty($arr['no_picture']) ? str_replace('../', './', $arr['no_picture']) : 'images/no_picture.gif'; // 修改默認產品圖片的路徑
        $arr['qq']                   = !empty($arr['qq']) ? $arr['qq'] : '';
        $arr['ww']                   = !empty($arr['ww']) ? $arr['ww'] : '';
        $arr['default_storage']      = isset($arr['default_storage']) ? intval($arr['default_storage']) : 1;
        $arr['min_goods_amount']     = isset($arr['min_goods_amount']) ? floatval($arr['min_goods_amount']) : 0;
        $arr['one_step_buy']         = empty($arr['one_step_buy']) ? 0 : 1;
        $arr['invoice_type']         = empty($arr['invoice_type']) ? array('type' => array(), 'rate' => array()) : unserialize($arr['invoice_type']);
        $arr['show_order_type']      = isset($arr['show_order_type']) ? $arr['show_order_type'] : 0;    // 顯示方式默認為列表方式
        $arr['help_open']            = isset($arr['help_open']) ? $arr['help_open'] : 1;    // 顯示方式默認為列表方式

        //限定語言項
        $lang_array = array('zh_cn', 'zh_tw', 'en_us');
        if (empty($arr['lang']) || !in_array($arr['lang'], $lang_array))
        {
            $arr['lang'] = 'zh_tw'; // 默認語言為簡體中文
        }

        if (empty($arr['integrate_code']))
        {
            $arr['integrate_code'] = 'shop'; // 默認的客戶整合插件為 shop
        }
        // write_static_cache('shop_config', $arr);
    // }
    // else
    // {
    //     $arr = $data;
    // }

    return $arr;
}

function getConfigValue($key){
    return Db::name('shop_config')
    ->where('code',$key)
    ->value('value');
}

function getIdBySsoId($id){
    $id =Db::name('users')
    ->where('sso_user_id',$id)
    ->value('user_id');
    if(!$id){
        return false;
    }
    return $id;
}

function getIdByLid($lid){
    $id =Db::name('user')
    ->where('line_id',$lid)
    ->value('id');
    if(!$id){
        return false;
    }
    return $id;
}

function getUseridByCuid($cuid){
    $id =Db::name('user')
    ->where('uniqid',$cuid)
    ->value('user_id');
    
    if(!$id){
        return false;
    }
    return $id;
}

function genUniqid($prefix='mc'){
    $is_get = false;
    while(!$is_get){
        $uniqid = $prefix.uniqid();

        $result1 = Db::name('user')
        ->where('user_id',$uniqid)
        ->count();

        $result2 = Db::name('precard')
        ->where('user_id',$uniqid)
        ->count();

        if(!$result1 && !$result2){
            $is_get=true;
        }
    }
    return $uniqid;    
}

/**
 * 取得開通序號
 *
 * @author Ｗayne <wwayne.hsu@gmail.com>
 *
 * @param integer $num  數量
 *
 * @return array
 */
function genSerialNo(){
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m')))
        .date('d').substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('%02d',rand(0,99));

    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord( $a[ $f ] ),
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    return  $d;    
}


function encodeRefer($userId)
{
    $sourceString = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    $code = '';
    while ($userId > 0) {
        $mod = $userId % 35;
        $userId = ($userId - $mod) / 35;
        $code = $sourceString[$mod] . $code;
    }
    if (strlen($code) < 8)
        $code = str_pad($code, 8, '0', STR_PAD_LEFT);
    return $code;
}

function decodeRefer($code)
{
    $sourceString = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    //移除左側的 0
    if (strrpos($code, '0') !== false)
        $code = substr($code, strrpos($code, '0') + 1);
    $len = strlen($code);
    $code = strrev($code);
    $num = 0;
    for ($i = 0; $i < $len; $i++) {
        $num += strpos($sourceString, $code[$i]) * pow(35, $i);
    }
    return $num;
}

/**
 * 功能：生成二維碼
 * @param string $qrData 手機掃描後要跳轉的網址
 * @param string $qrLevel 預設糾錯比例 分為L、M、Q、H四個等級，H代表最高糾錯能力
 * @param string $qrSize 二維碼圖大小，1－10可選，數字越大圖片尺寸越大
 * @param string $savePath 圖片儲存路徑
 * @param string $savePrefix 圖片名稱字首
 */
function createQRcode($savePath, $qrData = 'QR Code :)', $qrLevel = 'L', $qrSize = 4, $savePrefix = 'qrcode')
{
    if (!isset($savePath)) return '';

    //設定生成png圖片的路徑
    $PNG_TEMP_DIR = $savePath;
    //檢測並建立生成資料夾
    if (!file_exists($PNG_TEMP_DIR)) {
        mkdir($PNG_TEMP_DIR);
    }

    $filename = $PNG_TEMP_DIR . '/qrcode_temp.png';
    $errorCorrectionLevel = 'L';
    if (isset($qrLevel) && in_array($qrLevel, ['L', 'M', 'Q', 'H'])) {
        $errorCorrectionLevel = $qrLevel;
    }
    $matrixPointSize = 4;
    if (isset($qrSize)) {
        $matrixPointSize = min(max((int)$qrSize, 1), 10);
    }
    if (isset($qrData)) {
        if (trim($qrData) == '') {
            die('data cannot be empty!');
        }
        //生成檔名 檔案路徑+圖片名字字首+md5(名稱)+.png
        $filename = $PNG_TEMP_DIR . $savePrefix . '_qrcode.png';

        //開始生成
        \PHPQRCode\QRcode::png($qrData, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    } else {
        //預設生成
        \PHPQRCode\QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    }
    if (file_exists($PNG_TEMP_DIR . basename($filename)))
        return basename($filename);
    else
        return FALSE;
}

function genQrCode($url,$user_id,$prefix)
{
       //$savePath 圖片儲存路徑
       $savePath = $_SERVER['DOCUMENT_ROOT'].'/storage/'.$user_id.'/';
       //路徑
       $webPath = str_replace($_SERVER['DOCUMENT_ROOT'], '', $savePath);

       //$qrData 手機掃描後要跳轉的網址
       $qrData = $url;

       // $qrLevel 預設糾錯比例 分為L、M、Q、H四個等級，H代表最高糾錯能力
       $qrLevel = 'H';
       //$qrSize 二維碼圖大小，1－10可選，數字越大圖片尺寸越大
       $qrSize = '4';
       // $savePrefix 圖片名稱字首
       $savePrefix = $user_id.'_'.$prefix;
       $pic = '';
       $filename = createQRcode($savePath, $qrData, $qrLevel, $qrSize, $savePrefix);
       if($filename = createQRcode($savePath, $qrData, $qrLevel, $qrSize, $savePrefix)){
           $pic = $webPath . $filename;
           return $pic;    
       }
       return false;
}

function asc_trim($val){
    if(!is_array($val)){
        return trim($val);
    }else{
        return $val;
    }
}

/**
* 得到新訂單號
*
* @return string
*/
function get_order_sn()
{
    /* 選擇一個隨機的方案 */
    mt_srand((double) microtime() * 1000000);
    $sn = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

    /* 檢查訂單號是否重複 */
    $is_existed = Db::name('order_info')
        ->where('order_sn',$sn)
        ->count();
    if ($is_existed != '0') get_order_sn();

    return $sn;
}


function getUserIdByUid($uid){
    return Db::name('users')->where('sso_user_id',$uid)->value('user_id');
}

function price_format($price){
    return $price;
}