<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */


namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\common\behavior\AdminLogBehavior;
use app\common\model\Attachment as model;
use file\FileHelper;
use file\PathHelper;
use think\Db;
use think\Log;
use think\Session;
use time\Timestamp;

class Attachment extends Permissions
{
    public function index()
    {
        $model = new model();
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $where = [];
            if (isset($post['filename']) and !empty($post['filename'])) {
                $where['filename'] = ['like', '%' . $post['filename'] . '%'];
            }
            if (isset($post['filepath']) and !empty($post['filepath'])) {
                $where['filepath'] = ['like', '%' . $post['filepath'] . '%'];
            }
            if (isset($post['status']) and ($post['status'] == 1 or $post['status'] === '0' or $post['status'] == -1)) {
                $where['status'] = $post['status'];
            }
            if (isset($post['type'])) {
                if ($post['type'] == 1) {
                    $where['filepath'] = ['like', '%http%'];
                }
                if ($post['type'] == -1) {
                    $where['filepath'] = ['not like', '%http%'];
                }
            }
            if (isset($post['create_time']) and !empty($post['create_time'])) {
                $min_time = strtotime($post['create_time']);
                $max_time = $min_time + 24 * 60 * 60;
                $where['create_time'] = [['>=', $min_time], ['<=', $max_time]];
            }

            $count = $model->where($where)->count();
            $data = $model->where($where)->page($post['page']??0, $post['limit']??15)->order('create_time desc')->select();

            foreach ($data as $k => $v) {
                $v['thumb_url'] = $v['filepath'];
                $v['status_text'] = $v->status_text;
                $data[$k] = $v;
            }

            return array('code' => 0, 'count' => $count, 'data' => $data);
        } else {
            return $this->fetch();
        }
    }

    /**
     * 选择图片
     * @return mixed
     */
    public function selectImage()
    {
        $model = new model();
        $where = [
            'fileext' => ['in', ['jpg', 'png', 'gif', 'jpeg', 'bmp', 'webp']],
            'status' => model::STATUS_OPEN
        ];
        $attachment = $model->where($where)->order('create_time desc')->paginate(24);
        $this->assign('attachment', $attachment);
        $this->assign('showUpload', in_array(43, $this->getPermission()));
        return $this->fetch();
    }

    /**
     * 审核
     */
    public function status()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $admin_id = \think\Session::get(self::ADMIN_ID);
            if (false == Db::name('attachment')->where('id', $post['id'])->update(['status' => $post['status'], 'admin_id' => $admin_id, 'audit_time' => time()])) {
                $this->error('设置失败');
            } else {
                $this->success('设置成功', 'index');
            }
        }
    }

    /**
     * 删除本地文件
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', 0, 'intval');
            $attachment = Db::name('attachment')->where('id', $id)->value('filepath');
            if (!isUrl($attachment) && file_exists(ROOT_PATH . 'public' . $attachment)) {
                //删除本地文件
                if (unlink(ROOT_PATH . 'public' . $attachment)) {
                    if (false == Db::name('attachment')->where('id', $id)->delete()) {
                        $this->error('删除失败');
                    } else {
                        $this->success('删除成功', 'admin/attachment/index');
                    }
                } else {
                    $this->error('删除失败');
                }
            } else {
                if (false == Db::name('attachment')->where('id', $id)->delete()) {
                    $this->error('删除失败');
                } else {
                    $this->success('删除成功', 'admin/attachment/index');
                }
            }
        }
    }

    /**
     * 批量删除本地文件
     */
    public function deletes()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ids = $post['ids'];
            $attachments = (new model())->where('id', 'in', $ids)->select();
            foreach ($attachments as $attachment) {
                if (!isUrl($attachment->filepath) && file_exists(ROOT_PATH . 'public' . $attachment->filepath)) {
                    //删除本地文件
                    if (unlink(ROOT_PATH . 'public' . $attachment->filepath)) {
                        if (false == Db::name('attachment')->where('id', $attachment->id)->delete()) {
                            $this->error('删除失败');
                        }
                    } else {
                        $this->error('删除失败');
                    }
                } else {
                    if (false == Db::name('attachment')->where('id', $attachment->id)->delete()) {
                        $this->error('删除失败');
                    }
                }
            }
            Log::log("批量删除附件：" . implode(',', $ids));
            $this->success('删除成功');
        }
    }


    /**
     * 下载
     * @return \think\response\Json
     */
    public function download()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', 0, 'intval');
            if ($id > 0) {
                //获取下载链接
                $data = Db::name('attachment')->where('id', $id)->find();
                $res['data'] = $data['filepath'];
                $res['name'] = $data['filename'];
                //增加下载量
                Db::name('attachment')->where('id', $id)->setInc('download', 1);
                $res['code'] = 1;
                return json($res);
            } else {
                $this->error('错误请求');
            }
        }
    }

    /**
     * 网络文件本地化
     */
    public function imgPersistence()
    {
        $attachments = (new model())->where(['filepath' => ['like', '%http%']])->order('id desc')->select();
        if (count($attachments) > 50) {
            $this->error('网络文件过多,请使用命令行操作');
        }
        $savePath = DS . 'uploads' . DS . 'admin' . DS . 'attachment' . DS . Timestamp::dayStart(time()) . DS;
        foreach ($attachments as $attachment) {
            $saveName = PathHelper::getFilename($attachment->filepath);
            FileHelper::fetchDownFile($attachment->filepath, ROOT_PATH . 'public' . $savePath, $saveName);
            $attachment->save(['filepath' => $savePath . $saveName]);
        }
        $msg = '执行完成，本地化' . count($attachments) . '个文件';
        if ($this->request->isCli()) {
            echo $msg . PHP_EOL;
        } else {
            $this->success($msg);
        }
    }

    /**
     * 添加网络图片
     */
    public function create()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $validate = new \think\Validate([
                ['filepath', 'require|max:200'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
            $module = $this->request->param('module', 'admin');
            $use = $this->request->param('use', 'attachment');
            if (ifContain($use, '/')) {
                $use = deleteStartDS(replaceDS($use));
            }
            if (ifContain($use, '.')) {
                $use = explode('.', $use)[0];
            }
            $filepath = $post['filepath'];
            $pathinfo = pathinfo($filepath);
            $data = [
                'module' => $module,//模块
                'use' => $use,//来源
                'filename' => $pathinfo['basename'],//文件名
                'filepath' => $filepath,//文件路径
                'fileext' => $pathinfo['extension']??'webp',//文件后缀
                'filesize' => 0,//文件大小
                'create_time' => time(),//时间
                'uploadip' => $this->request->ip(),//IP
                'user_id' => Session::has(self::ADMIN_ID) ? Session::get(self::ADMIN_ID) : 0,
                'status' => model::STATUS_OPEN,
                'admin_id' => 0,
                'audit_time' => 0,
            ];
            $res['id'] = Db::name('attachment')->insertGetId($data);
            $res['src'] = $filepath;
            $this->success('完成', '', $res);
        }
    }

    /**
     * 上传附件
     * @return \think\response\Json
     */
    public function upload()
    {
        $module = $this->request->param('module', 'admin');
        $use = $this->request->param('use', 'attachment');
        if (ifContain($use, '/')) {
            $use = deleteStartDS(replaceDS($use));
        }
        if (ifContain($use, '.')) {
            $use = explode('.', $use)[0];
        }

        if ($this->request->file('file')) {
            $file = $this->request->file('file');
        } else {
            $res['code'] = 1;
            $res['msg'] = '没有上传文件';
            return json($res);
        }
        $web_config = Db::name('webconfig')->where('id', 1)->find();
        $info = $file->validate(['size' => $web_config['file_size'] * 1024, 'ext' => $web_config['file_type']])->rule('date')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $module . DS . $use);
        if ($info) {
            //写入到附件表
            $data = [];
            $data['module'] = $module;//模块
            $data['use'] = $use;//来源
            $data['filename'] = $info->getFilename();
            $data['filepath'] = DS . 'uploads' . DS . $module . DS . $use . DS . $info->getSaveName();
            $data['fileext'] = $info->getExtension();
            $data['filesize'] = $info->getSize();
            $data['create_time'] = time();
            $data['uploadip'] = $this->request->ip();
            $data['user_id'] = Session::has(self::ADMIN_ID) ? Session::get(self::ADMIN_ID) : 0;
            if ($data['module'] = 'admin') {
                //通过后台上传的文件直接审核通过
                $data['status'] = model::STATUS_OPEN;
                $data['admin_id'] = $data['user_id'];
                $data['audit_time'] = time();
            }
            $res['id'] = Db::name('attachment')->insertGetId($data);
            $res['src'] = replaceUrlDS($data['filepath']);
            (new AdminLogBehavior())->updateLastLog('上传附件：' . $data['filepath']);
            $this->success('上传完成', 'admin/attachment/index', $res);
        } else {
            $this->error('上传失败：' . $file->getError());
        }
    }

}
