<?php
namespace app\admin\logic;

use app\BaseController;
use app\admin\model\Attachment;
use app\admin\model\AttachmentCategory;
use think\facade\Image;
use think\facade\File;
use think\facade\Filesystem;
use app\shared\model\Option;
use OSS\OssClient;
use OSS\Core\OssUtil;
use OSS\Core\OssException;
use think\facade\Env;
require root_path().'extend/AliyunOss/SDK/autoload.php';


class AttachmentForm extends Base
{
    
    public function __construct()
    {
        parent::__construct();
    }
    private $size_limit=40;
    private $ext_limit='jpg,png';
    private $file_input_name='file';
    //上传图片
    public function upload(){
       
        
        $uid = input('uid','');
        $dir = 'images';
        $size_limit = $this->size_limit * 1024*1024;
        // 附件类型限制
        $ext_limit = $this->ext_limit;
         // 缩略图参数
        $thumb = request()->post('thumb', '');
        // 水印参数
        $watermark = request()->post('watermark', '');
        $file_input_name = 'file';
        $file = request()->file('file');
        // 判断附件大小是否超过限制
        if ($size_limit > 0 && (filesize($file) > $size_limit)) {
           return fetchJson([],'文件太大',1);  
        }
        // 判断附件格式是否符合
        $file_name = $_FILES['file']['name'];
        $file_ext  = strtolower(substr($file_name, strrpos($file_name, '.')+1));

        $error_msg = '';
        if ($ext_limit == '') {
            $error_msg = '获取文件信息失败！';
        }
        if ($file->getMime() == 'text/x-php' || $file->getMime() == 'text/html') {
            $error_msg = '禁止上传非法文件！';
        }
        if($file){
            // 缩略图路径
            $thumb_path_name = '';
            // 图片宽度
            $img_width = '';
            // 图片高度
            $img_height = '';
            // 获取附件信息
            $file_add=Attachment::where(['md5'=>$file->hash('md5'),'sha1'=>$file->hash('sha1')])->find();
            $root_url=request()->domain().str_replace('index.php', '',request()->baseFile());
            if($file_add){

                if($this->store_id>0){
                    if($this->store_id!=$file_add->store_id){
                        $file_info = [
                            'uid'    => $uid,
                            'acid'   =>$this->acid,
                            'store_id' =>$this->store_id,
                            'category_id'=>input('category_id'),
                            'name'   => $file_name,
                            'mime'   => $file_name,
                            'path'   => $file_add->path,
                            'ext'    => $file_add->ext,
                            'size'   => $file_add->size,
                            'md5'    => $file_add->md5,
                            'sha1'   => $file_add->sha1,
                            'thumb'  => $file_add->thumb,
                            'module' => $file_add->module,
                            'width'  => $file_add->width,
                            'height' => $file_add->height,
                        ];
                         // 写入数据库
                        if ($file_add1 = Attachment::create($file_info)) {
                            $data=[
                                'id'    =>$file_add1->id,
                                'url'   =>$root_url.$file_add1->path
                            ];
                           return fetchJson($data);
                        }
                    }
                }
                if($file_add->is_delete==1){
                    $file_add->is_delete=0;
                }
                if(input('category_id')){
                     $file_add->category_id=input('category_id');
                }
                $file_add->save();
                $data=[
                    'id'     => $file_add->id,
                    'url'   => $root_url.$file_add->path
                ];
               return fetchJson($data);
            }else{
                $savename = \think\facade\Filesystem::disk('uploads')->putFile( 'images', $file);
                $file_info = [
                    'uid'    => $uid,
                    'acid'   =>$this->acid,
                    'store_id' =>$this->store_id,
                    'category_id'=>input('category_id'),
                    'name'   => $file_name,
                    'mime'   => $file_name,
                    'path'   => 'uploads/'. str_replace('\\', '/', $savename),
                    'ext'    => $file_ext,
                    'size'   => filesize($file),
                    'md5'    => $file->hash('md5'),
                    'sha1'   => $file->hash('sha1'),
                    'thumb'  => $thumb_path_name,
                    'module' => "hotel",
                    'width'  => $img_width,
                    'height' => $img_height,
                ];
                $option=Option::get_data(-1,'admin','system_upload_config');
                $config=json_decode($option,1);
                if(isset($config['upload'])){
                    if($config['upload']=='aloss'){
                        if(isset($config['al']['ak'])&&isset($config['al']['sk'])&&isset($config['al']['bucket'])&&isset($config['al']['endpoint'])){
                            $isCName=false;
                            //阿里OSS
                            $ossClient = new OssClient($config['al']['ak'], $config['al']['sk'], $config['al']['endpoint'], $isCName);
                            $res=$ossClient->multiuploadFile($config['al']['bucket'],$config['al']['cname'].$file_info['sha1'].'.'.$file_info['ext'],$file_info['path']);
                            if(isset($res['info']['url'])){
                                $file_info['url']=$res['info']['url'];
                                $file_info['driver']='aloss';
                            }
                        }
                    }
                }
                // 写入数据库
                if ($file_add = Attachment::create($file_info)) {
                    $data=[
                        'id'    =>$file_add->id,
                        'url'   =>$root_url.$file_add->path
                    ];
                   return fetchJson($data);
                }else{
                    return fetchJson([],'数据保存失败',1);  
                }  
            }
             
        }else{
             return fetchJson([],'暂无目录',1);  
        } 
    }
    //分类
    public function category(){
        $all=[
            ['id'=>-1,'is_edit'=>0,'is_show'=>0,'name'=>'全部'],
            ['id'=>0,'is_edit'=>0,'is_show'=>0,'name'=>'未分类'],
        ];
        $query=AttachmentCategory::where(['is_delete'=>0]);
         //平台账号
        if($this->role==2){
            $query=$query->where(['acid'=>$this->acid]);
        }
        //商户
        if($this->role==3){
            $query=$query->where(['acid'=>$this->acid,'store_id'=>$this->store_id]);
        }
        $list=$query->column('id,name');
        foreach ($list as $key => &$value) {
            $value['is_edit']=0;
            $value['is_show']=0;
        }
        if($list){
            $all=array_merge($all,$list);
        }
        return fetchJson($all);  
    }
     //图片列表
    public function file_list(){
        $page=input('page')?input('page'):1;
        $category_id=input('category_id');
        if($category_id==-1){
            $query=Attachment::where(['is_delete'=>0]);
        }else{
            $query=Attachment::where(['is_delete'=>0,'category_id'=>$category_id]);
        }
        //平台账号
        if($this->role==2){
            $query=$query->where(['acid'=>$this->acid]);
        }
        //商户
        if($this->role==3){
            $query=$query->where(['acid'=>$this->acid,'store_id'=>$this->store_id]);
        }
        $list=$query->page($page)->limit(20)->column('id,path,driver,url');
        $root_url=request()->domain().str_replace('index.php', '',request()->baseFile());
        foreach ($list as $key => &$value) {
            if($value['driver']=='local'){
                 $value['url']=$root_url.$value['path'];
             }
            $value['status']=0;
        }
        return fetchJson($list);  
    }
    //分类编辑
    public function category_edit(){
        $id=input('id');
        $form=AttachmentCategory::where(['acid'=>$this->acid,'id'=> $id])->find();
        if(!$form){
            $form=new AttachmentCategory();
            $form->acid=$this->acid;
            $form->store_id=$this->store_id;
        }
        $form->name=input('name')?input('name'):'未命名';
        $form->save();
        return fetchJson([],'编辑成功');  
    }
    //删除分类
    public function category_delete(){
        $id=input('id');
        AttachmentCategory::where(['acid'=>$this->acid,'id'=> $id])->update(['is_delete'=>1]);
        return fetchJson([],'删除成功');
    }
    //删除文件
    public function file_delete(){
        $ids=input('ids');
        Attachment::where(['acid'=>$this->acid])->where('id','in',$ids)->update(['is_delete'=>1]);
        return fetchJson([],'删除成功');
    }
    public function file_move(){
        $ids=input('ids');
        $category_id=input('category_id');
        Attachment::where(['acid'=>$this->acid])->where('id','in',$ids)->update(['category_id'=>$category_id]);
        return fetchJson([],'移动成功');
    }
   /**
     * 创建缩略图
     * @param string $file 目标文件，可以是文件对象或文件路径
     * @param string $dir 保存目录，即目标文件所在的目录名
     * @param string $save_name 缩略图名
     * @param string $thumb_size 尺寸
     * @param string $thumb_type 裁剪类型
     * @author 芊雅软件技术
     * @return string 缩略图路径
     */
    private function create_thumb($file = '', $dir = '', $save_name = '', $thumb_size = '', $thumb_type = '')
    {
        // 获取要生成的缩略图最大宽度和高度
        $thumb_size = $thumb_size == '' ? config('upload_image_thumb') : $thumb_size;
        list($thumb_max_width, $thumb_max_height) = explode(',', $thumb_size);
        // 读取图片
        $image = Image::open($file);
        // 生成缩略图
        $thumb_type = $thumb_type == '' ? config('upload_image_thumb_type') : $thumb_type;
        $image->thumb($thumb_max_width, $thumb_max_height, $thumb_type);
        // 保存缩略图
        $thumb_path = config('upload_path') . DIRECTORY_SEPARATOR . 'images/' . $dir . '/thumb/';
        if (!is_dir($thumb_path)) {
            mkdir($thumb_path, 0766, true);
        }
        $thumb_path_name = $thumb_path. $save_name;
        $image->save($thumb_path_name);
        $thumb_path_name = 'uploads/images/' . $dir . '/thumb/' . $save_name;
        return $thumb_path_name;
    }

    /**
     * 添加水印
     * @param string $file 要添加水印的文件路径
     * @param string $watermark_img 水印图片id
     * @param string $watermark_pos 水印位置
     * @param string $watermark_alpha 水印透明度
     * @author 芊雅软件技术
     */
    private function create_water($file = '', $watermark_img = '', $watermark_pos = '', $watermark_alpha = '')
    {
        $path = model('admin/attachment')->getFilePath($watermark_img, 1);
        $thumb_water_pic = realpath(Env::get('root_path') . 'public/' . $path);
        if (is_file($thumb_water_pic)) {
            // 读取图片
            $image = Image::open($file);
            // 添加水印
            $watermark_pos   = $watermark_pos   == '' ? config('upload_thumb_water_position') : $watermark_pos;
            $watermark_alpha = $watermark_alpha == '' ? config('upload_thumb_water_alpha') : $watermark_alpha;
            $image->water($thumb_water_pic, $watermark_pos, $watermark_alpha);
            // 保存水印图片，覆盖原图
            $image->save($file);
        }
    }
}   