<?php

namespace app\adminapi\controller;

use app\common\controller\AdminApi;
use app\common\model\Attachment as AttachmentModel;

/**
 * 附件管理
 *
 * @icon   fa fa-circle-o
 * @remark 主要用于管理上传到服务器或第三方存储的数据
 */
class Attachment extends AdminApi
{
    /**
     * @var \app\common\model\Attachment
     */
    protected $model = null;

//    protected $noNeedRight = ['classify'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new AttachmentModel;
//        $this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
//        $this->view->assign("categoryList", \app\common\model\Attachment::getCategoryList());
    }


    /**
     * 查看附件分类和类型
     */
    public function config()
    {
        $mimetypeList = \app\common\model\Attachment::getMimetypeList();
        $categoryList = \app\common\model\Attachment::getCategoryList();
        $this->success('查看数据', [
            'mimetypeList' => $mimetypeList,
            'categoryList' => $categoryList,
        ]);
    }



    /**
     * 查看附件列表
     *
     * @ApiMethod (GET)
     * @ApiParams (name="limit", type="int", required=true, description="每页条数")
     * @ApiParams (name="page", type="int", required=true, description="页数")
     * @ApiParams (name="category", type="string", required=true, description="图片分类")
     * @ApiParams (name="mimetype", type="string", required=true, description="图片类型")
     * @ApiParams (name="admin_id", type="int", required=true, description="管理员ID")
     * @ApiParams (name="user_id", type="int", required=true, description="会员ID")
     * @ApiParams (name="filename", type="int", required=true, description="文件名称")
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

            $mimetypeQuery = [];
            $where = [];

            $category = $this->request->request('category',null);
            $mimetype = $this->request->request('mimetype',null);
            $limit = $this->request->request('limit/d', 10);


            if (isset($category) && $category == 'unclassed') {
                $category = '';
            }



        if($category !==null){
            $where['category'] = ['=',"{$category}"];
        }

        $admin_id =  $this->request->get("admin_id/s","");
        if($admin_id){
            $where['admin_id'] = ['=',"{$admin_id}"];
        }
        $user_id =  $this->request->get("user_id/s","");
        if($user_id){
            $where['user_id'] = ['=',"{$user_id}"];
        }



        $filename =  $this->request->get("filename/s","");
        if($filename){
            $where['filename'] = ['like',"%{$filename}%"];
        }



            if (isset($mimetype) && preg_match("/(\/|\,|\*)/", $mimetype)) {

                $mimetypeQuery = function ($query) use ($mimetype) {
                    $mimetypeArr = array_filter(explode(',', $mimetype));
                    foreach ($mimetypeArr as $index => $item) {
                        $query->whereOr('mimetype', 'like', '%' . str_replace("/*", "/", $item) . '%');
                    }
                };
            }


            $list = $this->model->with(["user"])
                ->where($mimetypeQuery)
                ->where($where)
                ->whereRaw("`filename`  NOT REGEXP  '^[0-9A-Fa-f]{32}'")
                ->order("id desc")
                ->paginate($limit);
//            var_dump($this->model->getLastSql());

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname', 'realname', 'mobile', 'avatar']);

            }
            $rows = $list->items();


            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            //得到当前域名
            $doman = $this->request->domain();
            foreach ($rows as $k => &$v) {
//                $v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : config('upload.cdnurl')). $v['url'];
//                $v['fullurl'] = cdnurl($v['url'],true);
                $v['fullurl'] = ($v['storage'] == 'local' ? $doman.$v['url'] : config('upload.cdnurl').$v['url']);

            }
            unset($v);
            $result = array("total" => $list->total(), "rows" => $rows);

        $this->success("查询成功！",$result);

    }




    /**
     * 删除附件
     *
     * @ApiMethod (POST)
     * @ApiRoute    (/adminapi/attachment/del/ids/{ids})
     * @ApiParams (name="ids", type="string", required=true, description="需要删除的附件ids")
     *
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            \think\Hook::add('upload_delete', function ($params) {
                if ($params['storage'] == 'local') {
                    $attachmentFile = ROOT_PATH . '/public' . $params['url'];
                    if (is_file($attachmentFile)) {
                        @unlink($attachmentFile);
                    }
                }
            });
            $attachmentlist = $this->model->where('id', 'in', $ids)->select();
            foreach ($attachmentlist as $attachment) {
                \think\Hook::listen("upload_delete", $attachment);
                $attachment->delete();
            }
            $this->success("删除成功！");
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }




    /**
     * 附件归类
     * @ApiMethod (POST)
     * @ApiParams (name="category", type="string", required=true, description="分类标识")
     * @ApiParams (name="ids", type="string", required=true, description="要归类的附件ids")
 */
    public function classify()
    {

        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $category = $this->request->post('category', '');
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $categoryList = \app\common\model\Attachment::getCategoryList();
        if ($category && !isset($categoryList[$category])) {
            $this->error(__('Category not found'));
        }
        $category = $category == 'unclassed' ? '' : $category;
        \app\common\model\Attachment::where('id', 'in', $ids)->update(['category' => $category]);
        $this->success("归档成功！");
    }




}