<?php

namespace app\manystoreapi\controller;
use app\common\controller\ManystoreApiBase;
use app\common\model\ManystoreAttachment;
use think\exception\PDOException;

/**
 * 机构API后台：附件管理接口
 */
class Attachment extends ManystoreApiBase
{
    protected $noNeedLogin = [];
//    protected $noNeedRight = '*';

    /**
     * @var \app\common\model\ManystoreAttachment
     */
    protected $model = null;

    public function _initialize()
    {
        $this->model = new \app\common\model\ManystoreAttachment;
        parent::_initialize();


    }


    /**
     * 附件列表查看
     * @ApiMethod (GET)
     * @ApiParams (name="category", type="string", required=true, description="附件分类分类标识：category1=非机密类1,category2=非机密类2,cert=证件机密类,code=二维码类,user=用户普通上传")
     * @ApiParams (name="mimetype", type="string", required=true, description="消息类型image/*=图片,audio/*=音频,video/*=视频,text/*=文档,application/*=应用程序,zip,rar,7z,tar=压缩文件")
     * @ApiParams (name="page", type="number", required=true, description="页数")
     * @ApiParams (name="limit", type="number", required=true, description="条数")
     * @ApiParams (name="keyword", type="number", required=true, description="关键词")
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

            $mimetypeQuery = [];
            $filter = $this->request->request('filter');

            $filterArr = $this->request->param();
        $page = $this->request->param("page/d",1);
        $limit = $this->request->param("limit/d",10);
        $category = $this->request->param("category/s","");
        $keyword = $this->request->param("keyword/s","");
        $where = [];
        $wherekeyword  =[[]];
        if($category)$where["category"] = $category;
        if($keyword){
            $wherekeyword = [
                'filename', 'like', "%{$keyword}%",
            ];
        }
            if (isset($filterArr['category']) && $filterArr['category'] == 'unclassed') {
                $filterArr['category'] = ',unclassed';
                $this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['category' => '']))]);
            }

            if (isset($filterArr['mimetype']) && preg_match("/[]\,|\*]/", $filterArr['mimetype'])) {
                $this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['mimetype' => '']))]);
                $mimetypeQuery = function ($query) use ($filterArr) {
                    $mimetypeArr = explode(',', $filterArr['mimetype']);
                    foreach ($mimetypeArr as $index => $item) {
                        if (stripos($item, "/*") !== false) {
                            $query->whereOr('mimetype', 'like', str_replace("/*", "/", $item) . '%');
                        } else {
                            $query->whereOr('mimetype', 'like', '%' . $item . '%');
                        }
                    }
                };
            }

//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        try {
            $as = $this->model->getWithAlisaName();

            $list = $this->model->with(["user"])
                ->where($mimetypeQuery)
                ->whereRaw("`filename`  NOT REGEXP  '^[0-9A-Fa-f]{32}'")
                ->where($where)
//                ->where("{$as}.shop_id", $this->auth->shop_id)
                ->where(...$wherekeyword)
                ->order("{$as}.id desc")
                ->paginate($limit);
//        var_dump(111);die;
        }catch (PDOException $e){
            var_dump($e->getData());die;
        }
            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname', 'realname', 'mobile', 'avatar']);

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

            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            foreach ($rows as $k => &$v) {
                $v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : $this->view->config['upload']['cdnurl']) . $v['url'];
            }
            unset($v);
            $result = array("total" => $list->total(), "rows" => $rows);
            $this->apisuccess(__('发送成功'),$result);
            //return json($result);

    }




    /**
     * 删除附件
     * @ApiMethod (POST)
     * @ApiParams (name="ids", type="string", required=true, description="附件id")
     * @param array $ids
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->apierror(__("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->apisuccess();
        }
        $this->apierror(__('Parameter %s can not be empty', 'ids'));
    }



    /**
     * 归类
     * @ApiMethod (POST)
     * @ApiParams (name="category", type="string", required=true, description="附件分类分类标识：category1=非机密类1,category2=非机密类2,cert=证件机密类,code=二维码类,user=用户普通上传")
     * @ApiParams (name="ids", type="string", required=true, description="附件id")
     */
    public function classify()
    {
//        if (!$this->auth->check('general/attachment/edit')) {
//            \think\Hook::listen('admin_nopermission', $this);
//            $this->apierror(__('You have no permission'), '');
//        }
        if (!$this->request->isPost()) {
            $this->apierror(__("Invalid parameters"));
        }
        $category = $this->request->post('category', '');
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->apierror(__('Parameter %s can not be empty', 'ids'));
        }
        $categoryList = \app\common\model\Attachment::getCategoryList();
        if ($category && !isset($categoryList[$category])) {
            $this->apierror(__('Category not found'));
        }

//        if(!defined('SHOP_ID')){
//            define('SHOP_ID', $this->auth->shop_id);
//        }

        $category = $category == 'unclassed' ? '' : $category;
        ManystoreAttachment::where('id', 'in', $ids)->update(['category' => $category]);
        $this->apisuccess();
    }



}