<?php

namespace app\api\controller;

use think\facade\Filesystem;
use think\facade\Event;
use think\facade\Db;
use think\Request;

class Upload
{
    /**
     * 附件入库
     */
    public function attachment($list, $post, $cun_type)
    {
        if ($list['errno'] == 0) {
            foreach ($list['data'] as $key=>$item) {
                try {
                    $md5 = explode('/', $item);
                    Db::name('im_attachment')->insert([
                        'title'    => $_FILES[$post['field']]['name']??'无',
                        'path'     => $item,
                        'cun_type' => $cun_type,
                        'user_id'  => $post['user_id'],
                        'user_type'=> $post['user_type'],
                        'ip_info'  => request()->ip(),
                        'md5'      => end($md5),
                        'add_time' => time()
                    ]);
                } catch (\Exception $e) {}
            }
        }
    }
    /**
     * 上传文件公共方法
     * @param $r
     * @param $valie   规则
     * @param $putFath 路径
     */
    public function upload_file($r, $valie, $putFath)
    {
        if ($r->isPost()) {
            if (!empty($_FILES)) {
                $files = request()->file();
                try {
                    $validate = validate(['file' => $valie])->check(['file' => $files]);
                    if (!$validate) {
                        return json([
                            'errno' => 1,
                            'data'  => [],
                            'msg'   => $validate->getMessage()
                        ]);
                    }
                    $info = Event::trigger('upload_storage_location', [
                        'files'   => $files,
                        'putFath' => $putFath
                    ]);
                    
                    if (!empty($info[0])) {
                        $this->attachment($info[0], $r->post(), 2);
                        return json($info[0]);
                    }

                    $img_lists = [];
                    foreach ($files as $file) {
                        $savename = Filesystem::disk('public')->putFile($putFath, $file);
                        $img_lists[] = '/uploads/' . str_replace('\\', '/', $savename);
                    }
                    $imgs = [
                        'errno' => 0,
                        'data'  => $img_lists
                    ];
                    $this->attachment($imgs, $r->post(), 1);
                    return json($imgs);

                } catch (\think\exception\ValidateException $e) {
                    return json([
                        'errno' => 1,
                        'data'  => [],
                        'msg'   => $e->getMessage()
                    ]);
                }
            }
        }
    }

    /**
     * 编辑器内图片
     */
    public function img(Request $r)
    {
        $format = Db::name('im_options')
            ->where('option_ename', 'set_attachment_tpgs')
            ->value('option_value');
        if (empty($format)) {
            $format = 'jpg,jpeg,png,gif';
        }
        return $this->upload_file($r, [
            'fileSize:41943040',
            'fileExt:'.$format
        ], 'reply');
    }

    /**
     * ajax上传图片
     */
    public function ajaxupimg(Request $r)
    {
        $format = Db::name('im_options')
            ->where('option_ename', 'set_attachment_tpgs')
            ->value('option_value');
        if (empty($format)) {
            $format = 'jpg,jpeg,png,gif';
        }
        return $this->upload_file($r, [
            'fileSize:41943040',
            'fileExt:'.$format
        ], 'chats');
    }

    /**
     * 上传文件
     */
    public function ajaxupfile(Request $r)
    {
        $format = Db::name('im_options')
            ->where('option_ename', 'set_attachment_wjgs')
            ->value('option_value');
        if (empty($format)) {
            $format = 'jpg,jpeg,png,gif,doc,ppt,txt';
        }
        return $this->upload_file($r, [
            'fileSize:167772160',
            'fileExt:'.$format
        ], 'file');
    }

    /**
     * 上传mp3音频文件
     */
    public function ajaxmp3upfile(Request $r)
    {
        return $this->upload_file($r, [
            'fileSize:8388608',
            'fileExt:mp3,ogg'
        ], 'file');
    }

    /**
     * 上传mp3音频文件
     */
    public function ajaxupaudio(Request $r)
    {
        return $this->upload_file($r, [
            'fileSize:167772160',
            'fileExt:mp3,ogg'
        ], 'audio');
    }
}