<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\admin\controller\bbfxshop;

use app\admin\controller\bbfxshop\Base;
use think\Db;
use app\common\library\Upload as Uploads;
use think\Config;


class Upload extends Base
{

    public function _initialize(){
        parent::_initialize();
    }
    
    public function upload()
    {
        Config::set('default_return_type', 'json');

        //必须还原upload配置,否则分片及cdnurl函数计算错误
        Config::load(APP_PATH . 'extra/upload.php', 'upload');

        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Uploads();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    __error($e->getMessage());
                }
                __success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Uploads();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                __success(__('Uploaded successful'));
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Uploads($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    __error($e->getMessage());
                }
                __success(__('Uploaded successful'));
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Uploads($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                __error($e->getMessage());
            }

            __success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url)]);
        }
    }
    
    
    
    public function getCategory(){
        $params = $this->param();
        
        // $info = Db::name("config")->where(['group'=>'dictionary','name'=>'attachmentcategory'])->value("value");
        // $info = json_decode($info,true);
        
        // $list = [];
        
        // foreach ($info as $key => $val){
        //     $list[] = ['id'=>$key,'name'=>$val];
        // }
        
        $list = Db::name("bbfx_attachment_category")->where(['uniacid'=>UNIACID])->select();
        
        $total = count($list);
        __success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function saveCategory(){
        $params = $this->param(['id/d','name/s']);
        
        $category = Db::name("bbfx_attachment_category")->where(['uniacid'=>UNIACID,'id'=>$params['id']])->find();
        
        $data = ['uniacid'=>UNIACID,'name'=>$params['name']];
        if(empty($category)){
            $res = Db::name("bbfx_attachment_category")->insert($data);
        }
        else{
            $res = Db::name("bbfx_attachment_category")->where(['id'=>$category['id']])->update($data);
        }
        
        if($res){
            __success("操作成功");
        }
        else{
            __success("操作成功");
        }
    }
    
    public function getPicture(){
        $params = $this->param();
        
        
        
        $page = intval($params['page']);
        $page = $page<1?1:$page;
        $psize = 15;
        $keywords = trim($params['keywords']);
        $category = intval($params['category']);
        $type = intval($params['type']);
        
        $where = ["uniacid"=>UNIACID,'is_user'=>0,'check_status'=>1];
        
        if($keywords){
            $where['filename'] = ['like',"%".$keywords."%"];
        }
        
        if(!empty($category)){
            $where['category_id'] = $category;
        }
        
        if(empty($type)){
            $type = 1;
        }
        
        if($type == 1){
            $where['mimetype'] = ['like','%image%'];
        }
        else{
            $where['mimetype'] = ['like','%video%'];
        }
        
        $list = Db::name("attachment")->where($where)->field(["id","url","mimetype","filename","createtime"])->order("id desc")->limit(($page-1)*$psize,$psize)->select();
        
        foreach ($list as $key => &$val){
            $val['fileType'] = 2;
            if(strstr($val['mimetype'], "image")){
                $val['fileType'] = 1;
            }
            $val['attachment'] = $val['url'];
            $val['url'] = cdnurl($val['attachment']);
        }
        unset($val);
        
        $total = Db::name("attachment")->where($where)->count();;
        
        __success("操作成功",['total'=>$total,'list'=>$list,'dd'=>$where]);
    }
    
    public function setImgCategory(){
        $params = $this->param(['id/a','category_id/d']);
        
        if(!is_array($params['id']) || empty($params['id'])){
            __error("请选择需要归类的图片");
        }
        
        $res = Db::name("attachment")->where(["uniacid"=>UNIACID,"id"=>['in',$params['id']]])->update(['category_id'=>$params['category_id']]);
        
        if($res){
            __success("操作成功");
        }
        else{
            __success("操作成功",$params);
        }
    }
    
    public function delPicture(){
        $id = $this->param('id/a');
        
        if(!is_array($id) || empty($id)){
            __error("请选择需要删除的图片");
        }
        
        $attachment = Db::name("attachment")->where(["uniacid"=>UNIACID,"id"=>['in',$id]])->select();
        
        if(empty($attachment)){
            __success("删除成功");
        }
        
        $res = Db::name("attachment")->where(["uniacid"=>UNIACID,"id"=>['in',$id]])->delete();
        
        if($res){
            
            
            $urls = [];
            foreach ($attachment as $key => $val){
                $urls[] = $val['url'];
                $file = ROOT_PATH."public".$val['url'];
                if(file_exists($file)) {
                    unlink($file);
                }
            }
            
            \app\admin\model\AdminLog::record("删除图片",implode(",",$urls),$attachment);
            
            __success("删除成功");
        }
        else{
            __error("删除失败");
        }
        
    }
    
    public function delCategory(){
        $id = $this->param('id/d');
        
        if(empty($id)){
            __error("请选择需要删除的图片分类");
        }
        
        $res = Db::name("bbfx_attachment_category")->where(["uniacid"=>UNIACID,"id"=>$id])->delete();
        
        if($res){
            Db::name("attachment")->where(["category_id"=>$id])->update(['category_id'=>0]);
            __success("删除成功");
        }
        else{
            __error("删除失败");
        }
    }
}