<?php


namespace App\User\Services;



use App\Services\CommonUserBaseService;
use App\User\Facades\UserFacade;
use App\User\Models\AttachmentModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Exceptions\ApiException;
use App\Common\Facades\UploadFileFacade;
use App\Common\Facades\PinYinFacade;

class AttachmentService extends CommonUserBaseService
{

    /**
     * 文件上传
     * @param Request $request
     */
    public function upload(Request $request)
    {
        //验证上传文件类型
        try {
            $isReName= $request->input('is_re_name', false);
            $upload = UploadFileFacade::upload($request, $request->input('field', 'file'),[],false,$isReName);
            $mimeType = empty($upload['mimeType']) ? '' : $upload['mimeType'];
            $data = [
                'user_id' => $this->getAuthUserId(),
                'file' => $upload['url'],//文件地址
                'name' => $upload['filename'] ?? '',//文件名
                'old_name' => $upload['original_filename'] ?? '',//文件名
                'alt' => $upload['original_filename'] ?? '',//文件名
                'size' => $upload['size'],
                'ext' => $upload['ext'],
                'pic'=>empty($upload['pic'])?'':$upload['pic'],
                'resolution' => empty($upload['resolution']) ? '' : $upload['resolution'],
                'type' => $this->getFileType($mimeType)
            ];
            $data['name'] = str_replace('.' . strtolower($data['ext']), '', $data['name']);
            if (empty($data['name'])) {
                die;
            } else {
                $data['first_letter'] = PinYinFacade::getOnePY($data['old_name']);
            }
            $saveModel = $this->save($data);
            return $saveModel;
        } catch (\Exception $ex) {
            Log::info('method:upload:' . $ex->getMessage());
            Log::info('method:upload:' . $ex->getTraceAsString());
            throw new ApiException(1004,['msg'=> $ex->getMessage()]);
        }
    }
    /**
     * 获取文件类型
     * */
    private function getFileType($mimeType)
    {
        $type = 0;
        if (strpos($mimeType, 'image') !== false) {
            $type = 1;
        } else if (strpos($mimeType, 'video') !== false) {
            $type = 2;
        } else if (strpos($mimeType, 'audio') !== false) {
            $type = 3;
        }
        return $type;
    }

    /**
     * 文件上传
     * @param Request $request
     */
    public function uploadImg($data, $fileExt, $selectFileName = '',$host='',$userId = null)
    {
        $userId = $userId ?? $this->getAuthUserId();
        $upload = UploadFileFacade::uploadImgBase64($data, $fileExt,$host,$selectFileName,false);
        //如果该url已存在于该公司
        $data = [
            'user_id' => $userId,
            'file' => $upload['url'],//文件地址
            'name' => $upload['filename'] ?? '',//文件名
            'old_name' => $selectFileName ?? '',//文件名
            'alt' => $selectFileName ?? '',//文件名
            'size' => $upload['size'],
            'ext' => $upload['ext'],
            'resolution' => empty($upload['resolution']) ? '' : $upload['resolution'],
            'type' => 1
        ];
        $data['name'] = str_replace('.' . strtolower($data['ext']), '', $data['name']);
        if (empty($data['name'])) {
            die;
        } else {
            $data['first_letter'] = PinYinFacade::getOnePY($data['old_name']);
        }
        $saveModel = $this->save($data);
        return $saveModel;
    }
    /**
     * 附件列表详情
     * */
    public function getAttachmentList($requestParams)
    {
        $pageSize = $requestParams['page_size'] ? $requestParams['page_size'] : 10; //页面大小，不传默认一页10条记录
        $pageNo = $requestParams['page'] ? $requestParams['page'] : 1; //页码，不传默认第1页
        $skip = ($pageNo - 1) * $pageSize; //页面记录的开始位置，即偏移量
        $where = [];
        $where['a.status'] = 0;
        if (isset($requestParams['type']) && $requestParams['type'] !== '' && $requestParams['type'] != -1) {
            $where['a.type'] = $requestParams['type'];
        }
        //查询的月份处理
        if (!empty($requestParams['month'])) {
            $begin = $requestParams['month'].'-01 00:00:00';
            $end = date('Y-m-d 23:59:59',strtotime('+1 month', strtotime($begin)) - 1);
            $requestParams['begin_end_time'] = [$begin, $end];
        }

        $resultData = [];
        $model = new AttachmentModel();
        $totalCount = $model->alias('a')->where($where)->count();
        $query = $model->alias('a')
            ->leftJoin('sys_admin_user as b', 'a.user_id', '=', 'b.id')
            ->where($where);
        if (!empty($requestParams['begin_end_time'])) {
            $begin = empty($requestParams['begin_end_time'][0]) ? '' : $requestParams['begin_end_time'][0];
            $end = empty($requestParams['begin_end_time'][1]) ? '' : $requestParams['begin_end_time'][1];
            if (!empty($begin) && !empty($end)) {
                $query->whereBetween('a.create_time', [$begin, $end]);
            }
        }
        if (!empty($requestParams['keyword'])) {
            $keyword = $requestParams['keyword'];
            $query->where(function ($queryStr) use ($keyword) {
                $queryStr->where('a.des', 'like', "%" . $keyword . "%")
                    ->orWhere('a.alt', 'like', "%" . $keyword . "%")
                    ->orWhere('a.old_name', 'like', "%" . $keyword . "%")
                    ->orWhere('a.title', 'like', "%{$keyword}%");
            });
        }
        $data = $query
            ->selectRaw('a.*,b.real_name as nick_name,b.user_name,b.real_name')
            ->skip($skip)
            ->limit($pageSize)
            ->orderByDesc('a.create_time')
            ->get();
        if (!empty($data)) {
            $resultData = $data->toArray();
        }

        $result = buildPage($resultData, $skip, $pageNo, $pageSize, $totalCount);

        return $result;
    }

    public function saveAttachment($params)
    {
        $model = new AttachmentModel();
        $data = $model->where(['id' => $params['id']])->first();
        $data->update_time = nowTime();
        if ($data->type == 1) {
            $data->alt = empty($params['alt']) ? '' : $params['alt'];
            $data->title = empty($params['title']) ? '' : $params['title'];
            $data->remark = empty($params['remark']) ? '' : $params['remark'];
            $data->des = empty($params['des']) ? '' : $params['des'];
        }
        $data->save();
        return $data;
    }
    public function delAttachment($id)
    {
        $model = new AttachmentModel();
        if (!is_array($id)) {
            $ids = [$id];
        } else {
            $ids = $id;
        }
        $where = [];
        $where['id'] = [['in', $ids]];
        $ret = $model->buildQuery($where)->update(['update_time' => nowTime(), 'status' => 2]);
        return $ret;
    }

    public function uploadCustomImage(Request $request)
    {
        //验证上传文件类型
        try {
            $allowedRequests = 10;
            // 时间窗口，单位为秒
            $timeWindow = 60;
            $ip = getClientIp();
            if ($ip) {
                $key = 'upload_custom_image_' . $ip;
                $times = Cache::get($key);
                if (!$times) {
                    Cache::put($key, 1, $timeWindow);
                } else if ($times >= $allowedRequests) {
                    throw new ApiException(40002);
                } else {
                    Cache::increment($key);
                }
            }
            $upload = UploadFileFacade::uploadCustomImage($request, 'file', [], false, true);
            return $upload['url'] ?? '';
        } catch (\Exception $ex) {
            Log::info('method:upload:' . $ex->getMessage());
            Log::info('method:upload:' . $ex->getTraceAsString());
            throw new ApiException(40002);
        }
    }
}
