<?php


use App\Service\Util\Support\Trace\CustomizeLogger;
use Illuminate\Http\UploadedFile;
use Modules\Common\Support\Upload\Uploader;
use PHPMailer\PHPMailer\PHPMailer;

if(!function_exists("str_decode")){
    /**
     * 字符解密
     * name: str_decode
     * @param $str
     * @return int
     * date 2022/09/27 11:38
     */
    function str_decode($str){

        $decode = Hashids::decode($str);
        $decode = is_array($decode) ? array_shift($decode) : $decode;
        if(empty($decodeBid)){
            myLog("StrDecodeError")->info("str : {$str}, decode : ".var_export($decode,true));
        }
        return intval($decode);
    }
}

if (!function_exists('str_encode')){
    /***
     *  字符加密
     * name: str_decode
     * @param mixed $str
     * @return mixed
     * date 2022/09/27 11:38
     */
    function str_encode($str)
    {
        return Hashids::encode($str);
    }
}




if (!function_exists('is_empty')){
    /**
     * 判断数据是否为空
     * name: is_empty
     * @param $data
     * @return bool 空返回true 非空返回false
     * date 2022/11/18 11:39
     */
    function is_empty($data): bool
    {
        if (is_object($data)){
            if (method_exists($data,'isEmpty')){
                return  $data->isEmpty();
            }

            return empty(get_object_vars($data));
        }

        return  empty($data);
    }
}

if (!function_exists('column_str')) {
    /**
     * 列转化
     * @param $key
     * @return string
     */
    function column_str($key)
    {
        $array = array(
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
            'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ',
            'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ',
            'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DH', 'DI', 'DJ', 'DK', 'DL', 'DM', 'DN', 'DO', 'DP', 'DQ', 'DR', 'DS', 'DT', 'DU', 'DV', 'DW', 'DX', 'DY', 'DZ',
            'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'EG', 'EH', 'EI', 'EJ', 'EK', 'EL', 'EM', 'EN', 'EO', 'EP', 'EQ', 'ER', 'ES', 'ET', 'EU', 'EV', 'EW', 'EX', 'EY', 'EZ'
        );
        return $array[$key];
    }
}

if (!function_exists('column')) {
    /**
     * Excel 列转化
     * @param $key
     * @param mixed $columns
     * @return string
     */
    function column($key, $columns = 1)
    {
        return column_str($key) . $columns;
    }
}

if (!function_exists('export')) {
    /***
     * @param mixed $list 导出的数据
     * @param mixed $params 标题设置
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    function export($list, $params = array())
    {

        if (PHP_SAPI == 'cli') {
            die('This example should only be run from a Web Browser');
        }

        $excel = new \PHPExcel();
        $excel->getProperties()->setCreator("植宇")->setLastModifiedBy("植宇")->setTitle("Office 2007 XLSX Test Document")->setSubject("Office 2007 XLSX Test Document")->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")->setKeywords("office 2007 openxml php")->setCategory("report file");
        $sheet = $excel->setActiveSheetIndex(0);
        $rowNum = 1;
        foreach ($params['columns'] as $key => $column) {
            $sheet->setCellValue(column($key, $rowNum), $column['title']);
            if (!empty($column['width'])) {
                $sheet->getColumnDimension(column_str($key))->setWidth($column['width']);
            }
        }
        $rowNum++;
        $len = count($params['columns']);;
        foreach ($list as $row) {

            for ($i = 0; $i < $len; $i++) {
                $value = $row[$params['columns'][$i]['field']] ?? '';
                $sheet->setCellValue(column($i, $rowNum), $value);
            }
            $rowNum++;
        }
        $excel->getActiveSheet()->setTitle($params['title']);
        $filename = urlencode($params['title'] . '-' . date('Y-m-d H:i', time()));
        ob_end_clean();
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $writer->save("php://output");
    }
}





/**
 * 发送邮件
 * @param $to_email 收件人
 * <pre>
 *  [
 *  ['address' => 'aa@bb.com', 'name' => 'aa'],
 *  ......,
 *  ['address' => 'aa@bb.com', 'name' => 'aa'],
 * ]
 * </pre>
 * @param $param
 * <pre>
 *  [
 *      'subject' => "xxxxxx" , // 标题
 *      'body' => 'xxxx', // 邮件内容,如果内容需要换行,使用 <br>
 * ]
 * </pre>
 * @param string $accessory
 */
function sendEmail($to_email, $param, $accessory = '')
{
    $mail = new PHPMailer(true);// Passing `true` enables exceptions
    $mail->CharSet = 'UTF-8';//'UTF-8';
    try {
        $mail->SMTPDebug = 0;                                 // Enable verbose debug output
        $mail->isSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'smtp.exmail.qq.com';     //$mail->Host = 'smtp.126.com'; Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = 'sendemail01@zkanshu.com'; //$mail->Username = 'tushengxiang@126.com';                // SMTP username
        $mail->Password = '5jBekvU2jJ2Ketue';                           // SMTP password
        $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
        $mail->Port = 465;                                    // TCP port to connect to

        //Recipients
        $mail->setFrom('sendemail01@zkanshu.com', 'System');
        $mail->addAddress($to_email[0]['address'], $to_email[0]['name']);
        array_shift($to_email);
        foreach ($to_email as $item) {
            $mail->addCC($item['address'], $item['name']);     // Add a recipient
        }

        //Attachments
        if ($accessory) $mail->addAttachment($accessory);// Add attachments

        $mail->isHTML(true);
        $mail->Subject = $param['subject'];
        $mail->Body = $param['body'];
        $mail->send();
    } catch (\Exception $e) {
        \Log::warning('发送邮件失败:' . $mail->ErrorInfo, $e->getTrace());
    }
}

/**
 * 获取日志对象
 * @param $fileName 保存日志的名称
 * @param string $logLevel 日志等级
 * @param int $logDays 日志保留的天数
 * @return \Psr\Log\LoggerInterface
 */
function myLog($fileName, $logLevel='info', $logDays = 7) :\Psr\Log\LoggerInterface{
    return CustomizeLogger::getLogger($fileName, $logLevel, $logDays);
}


if (!function_exists('get_date')) {
    /**
     * 获取时间
     * @param mixed $time
     * @param mixed $format
     * @return false|string
     */
    function get_date($time = 0, $format = "Y-m-d H:i:s")
    {
        $time = intval($time);
        if ($time <= 0) {
            $time = time();
        }
        return date($format, $time);
    }
}

/**
 * 华为obs文件上传
 * @param UploadedFile $file
 * @return array
 */
function huaweiObsUpload(UploadedFile $file) {
    $uploader = new Uploader();
    $uploader->setDriver('HuaweiOBS');
    return  $uploader->upload($file);
}


if (!function_exists("random")) {

    /**
     * [random 生成随机字符串]
     * @wzq
     * @DtuateTime 2020-09-08
     * @param      [type]     $length  [长度]
     * @param mixed $numeric [是否仅是数字]
     * @return string [type]              [string]
     * @version    v1
     */
    function random($length, $numeric = false): string
    {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed[mt_rand(0, $max)] ?? "";
        }
        return $hash;
    }
}