<?php

namespace app\worker\controller;

use think\facade\Session;
use think\facade\Request;

use think\facade\Filesystem;

use app\common\model\Attachment as AttachmentModel;

class Attachment
{


    // 文件上传
    public function tplFieldFile()
    {
        $file     = request()->file("file");
        $savename = \think\facade\Filesystem::disk('public')->putFile('files', $file);
        if ($file) {
            $filename   = str_replace(strrchr($_FILES['file']['name'], "."), "", $_FILES['file']['name']);
            $attachment = AttachmentModel::create([
                'filename'   => $filename,
                'atype'      => 4,
                'attachment' => request()->domain() . "/attachment/" . str_replace("\\", "/", $savename),
                'createtime' => time(),
            ]);
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
                'data' => [
                    'src'   => request()->domain() . "/attachment/" . str_replace("\\", "/", $savename),
                    'path'  => "./attachment/" . str_replace("\\", "/", $savename),
                    'title' => $filename,
                ],
            ]));
        } else {
            exit(json_encode([
                'code' => 1,
                'msg'  => "上传失败，请稍后重试",
            ]));
        }
    }

    // 图片上传
    public function tplFieldImage()
    {
        $this->validateExt(['jpg', 'png', 'jpeg']);
        $file     = request()->file("file");
        $savename = \think\facade\Filesystem::disk('public')->putFile('images', $file);
        if ($file) {
            $filename   = str_replace(strrchr($_FILES['file']['name'], "."), "", $_FILES['file']['name']);
            $attachment = AttachmentModel::create([
                'filename'   => $filename,
                'atype'      => 1,
                'attachment' => request()->domain() . "/attachment/" . str_replace("\\", "/", $savename),
                'createtime' => time(),
            ]);
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
                'data' => [
                    'src'   => request()->domain() . "/attachment/" . str_replace("\\", "/", $savename),
                    'title' => $filename,
                ],
            ]));
        } else {
            exit(json_encode([
                'code' => 1,
                'msg'  => "上传失败，请稍后重试",
            ]));
        }
    }

    public function validateExt($ext_arr)
    {
        $ext = pathinfo($_FILES['file']['name'])['extension'];
        if (!in_array($ext, $ext_arr)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "文件格式不正确",
            ]));
        }
    }

}