<?php


use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Modules\Common\Support\Trace\TraceContext;
use Modules\Common\Support\Upload\Uploader;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Modules\Common\Support\Trace\CustomizeLogger;
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");
    }
}

/**
 * 输出到浏览器(需要设置header头)
 * @param string $fileName 文件名
 * @param string $fileType 文件类型
 */
function excelBrowserExport($fileName, $fileType) {

    //文件名称校验
    if(!$fileName) {
        trigger_error('文件名不能为空', E_USER_ERROR);
    }

    //Excel文件类型校验
    $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
    if(!in_array($fileType, $type)) {
        trigger_error('未知文件类型', E_USER_ERROR);
    }

    if($fileType == 'Excel2007' || $fileType == 'Xlsx') {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
        header('Cache-Control: max-age=0');
    } else { //Excel5
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$fileName.'.xls"');
        header('Cache-Control: max-age=0');
    }
}

/**
 * 导出excel
 * @param $header 第一行,表头
 * <pre>
 *  ['书名', 'bid', '版权方']
 * </pre>
 * @param $datas 表内容,和表头一一对应
 * <pre>
 * [
 *  ['aa', 1, 'bb'],
 *  ['aa', 1, 'bb'],
 *  ....
 *  ['aa', 1, 'bb'],
 *  ['aa', 1, 'bb'],
 * ]
 * </pre>
 * @param $fileName 导出文件名
 * @param string $fileType
 * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
 */
function exportExcelXslx($header, $datas, $fileName, $fileType = 'Xlsx') {
    $spreadsheet = new Spreadsheet();
    $worksheet = $spreadsheet->getActiveSheet();

//    $worksheet->setTitle('数据中心');

    foreach ($header as $key => $value) {
        $worksheet->setCellValue([$key+1, 1], $value);
    }

    $row = 2; //从第二行开始
    foreach ($datas as $item) {
        $column = 1;

        foreach ($item as $value) {
            $worksheet->setCellValue([$column, $row], $value);
            $column++;
        }
        $row++;
    }



    $writer = IOFactory::createWriter($spreadsheet, $fileType); //按照指定格式生成Excel文件
    excelBrowserExport($fileName, $fileType);
    $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;
    }
}

if(!function_exists('getMiniProgramTableName')){
    /**
     *  获取小程序表名  表名前添加前缀：wechat_miniprogram_ 或者 douyin_miniprogram_
     * name: getMiniProgramTableName
     * @param int $from 来源 1 微信小程序
     * @param string $name 表名
     * @return string
     * date 2023/05/19 09:18
     */
    function getMiniProgramTableName(int $from, string $name): string
    {
        return sprintf('%s_%s', [
            '1' => 'wechat_miniprogram',
            '2' => 'douyin_miniprogram'
        ][$from],$name);
    }
}

if (!function_exists('getProp')){
    /**
     * 获取对象或数组的属性值
     * @param        $param
     * @param        $key
     * @param string $default
     * @return mixed|string
     */
    function getProp($param, $key, $default = '')
    {
        $result = $default;
        if (is_object($param) && isset($param->$key)) {
            $result = $param->$key;
        }

        if (is_array($param) && isset($param[$key])) {
            $result = $param[$key];
        }

        return $result;
    }
}

/**
 * 打印sql
 */
if (!function_exists('print_sql')) {
    function print_sql ()
    {
        DB::listen(function ($sql) {
            $singleSql = $sql->sql;
            if ($sql->bindings) {
                foreach ($sql->bindings as $replace) {
                    $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
                    $singleSql = preg_replace('/\?/', $value, $singleSql, 1);
                }
            }
            myLog('sql-query')->info($singleSql);
        });
    }
}

if(!function_exists('getTraceContext')) {

    /**
     * @return TraceContext
     */
    function getTraceContext() {
        return app(TraceContext::class);
    }
}
