<?php

namespace app\controller\admin\system;

use app\BaseController;
use app\entity\SysFileRecord;
use app\service\CurdService;
use think\db\exception\DbException;
use think\exception\FileException;
use think\exception\ValidateException;
use think\facade\Filesystem;
use think\response\Json;

class FileController extends BaseController
{
    public function download()
    {
        $fileId = \request()->route('fileId');
        $fileExt = hashids(12)->decode($fileId)[0] ?? '';
        $data = \app\entity\SysFileRecord::find($fileExt);

        $fileUrl = filesystem()->getFileUrl($data['rule_id'], $data['id'], $data['path'].'/'.$data['name'], true);
        if(empty($fileUrl)){
            return json(['message'=>'文件不存在']);
        }
        $mime = "image/jpeg";
//        header('Content-Type: ' . $mime);
//        header('Content-Disposition: attachment; filename="b7b9f5caae81dc32ba2a062e00247270.jpg"');
//        header('Content-Length: 928318');
//        echo file_get_contents($fileUrl);
        return \response()->content(file_get_contents($fileUrl))->header([
            'Content-Type'=> $mime,
            'Content-Disposition'=> 'attachment; filename="b7b9f5caae81dc32ba2a062e00247270.jpg"',
            'Content-Length' => 928318
        ]);
    }
    /**
     * 分页查询账号登录记录
     * @return Json
     * @throws DbException
     */
    public function page(): Json
    {
        $model = SysFileRecord::with(['createUser'])->withSearch(['name', 'path', 'createNickname'], [
            'name' => $this->request->param('name/s', ''),
            'path' => $this->request->param('path/s', ''),
            'createNickname' => $this->request->param('createNickname/s', ''),
            'createTime' => [
                $this->request->get('createTimeStart/s', ''),
                $this->request->get('createTimeEnd/s', '')
            ],
        ]);

        $paginate = CurdService::getPaginate($this->request, $model->append(['previewUrl','downloadUrl']));

        return $this->writeSuccess('ok', $paginate);
    }

    public function batchRemove()
    {
        return $this->writeError('禁止删除');
        $data = $this->request->delete();
        SysFileRecord::destroy($data);
        return $this->writeSuccess('删除成功');
    }

    public function upload()
    {
        $file = $this->request->file('file');
        if (empty($file)) {
            return $this->writeError('文件不存在');
        }
        try {
            $result = filesystem()->upload($file, 0, $this->auth->userId);
        } catch (ValidateException|FileException $e) {
            return $this->writeError($e->getMessage());
        }

        return $this->writeSuccess('ok', $result);
    }
}