<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/25
 * Time: 16:41
 */

namespace Addons\Upload\Controller\Admin;


use Addons\Upload\Helper;
use Addons\Upload\Model\ImgLib;
use Lib\Request;

class UploadImage extends \BaseController
{
    /**
     *
     * @param array $data
     * @param array $config
     * @return false|string
     * @throws \Exception
     */
    public function index(array $config, array $data)
    {
        $style = !empty($config['style']) ? $config['style'] : 'library';
        $style = in_array($style, ['simple', 'library']) ? $style : 'library';
        $method = "upload_{$style}";
        return $this->$method( $config,$data);
    }

    /**
     * 简单上传组件
     * @param array $data
     * @param array $config
     * @return false|string
     * @throws \Exception
     */
    public function upload_simple(array $config, array $data)
    {

        $this->assign('data', $data);
        $config = array_merge(['name' => '', 'id' => md5(time()), 'title' => '图片上传', 'type' => 'img'], $config);
        $config['type'] = Helper::getInstance()->upTypeFilter($config['type']);
        $this->assign('temp_id', Helper::getInstance()->randomCode());
        $this->assign('config', $config);
        return $this->show('', true);
    }

    public function upload_library(array $config, array $data)
    {
        $this->assign('data', $data);
        $config = array_merge(['callback' => '','multiple'=>false,'data' => ['target' => 'sharepic'], 'class' => 'btn btn-default', 'name' => '', 'id' => md5(time()), 'title' => '图片上传', 'type' => 'img'], $config);
        $data_str = '';
        foreach ($config['data'] as $k => $v) {
            $data_str .= " data-{$k}='{$v}' ";
        }
        $config['config_str']=http_build_query(["config"=>$config]);
        $config['data_str'] = $data_str;
        $this->assign('temp_id', Helper::getInstance()->randomCode());
        $this->assign('config', $config);
        return $this->show('', true);
    }

    /**
     * 文件本地上传
     * @param Request $request
     * @return array
     */
    public function upload(Request $request)
    {
        if ($request->file('img')) {
            $upload = Helper::getInstance()->upload_file('img', pub_path('img'));
        } elseif ($request->file('file')) {
            $upload = Helper::getInstance()->upload_file('file', pub_path('file'));
        }

        if ($upload) {
            return success('上传成功', \Conf::$http_path_api . $upload);
        } else {
            return error('上传失败');
        }
    }

    /**
     * 图片上传页面
     * @return false|string
     * @throws \Exception
     */
    public function img_library(){
        $wid=\Session::get('wid');
        $request=Request::instance();
        $config=is_array($_GET['config']) ? $_GET['config'] : [];
        $config['multiple']=empty($config['multiple']) ? 'false':'true';
        $this->assign('config',$config);
        $where=['wid' => $wid];
        if($_GET['type']){
            $where['type']=$_GET['type'];
        }
        $imgList = (new \Model('imglib'))->where(['type'=>'vsho_img'])->order('ctime desc')->list_all_array($where);
        $this->assign('temp_id', Helper::getInstance()->randomCode());
        $this->assign('imgList',$imgList);
        return $this->show('',true);
    }

    /**
     * 图片进行上传处理
     * @return array
     * @throws \Exception
     */
    public function upload_library_img(Request $request)
    {

        $wid = \Session::get('wid');
        $admin = get_user_agency();
        $path = 'tmpImg';
        $field = 'img';
        $bucketName = $admin->bucket_name;
        $allowExt = ['jpg', 'jpeg', 'gif', 'ico', 'png', 'bmp'];
        // 上传到本地，拿到本地的path
        if (!$_FILES[$field]) return error('文件不存在');
        $ext = explode('.', $_FILES['img']["name"]);
        $ext = $ext[count($ext) - 1];
        if (strtolower($ext) == 'php') {
            return error('禁止的文件后缀');
        }
        if (!in_array(strtolower($ext), $allowExt)) return error('文件后缀不允许');
        // 创建文件夹
        try {
            mkdir($path);
        } catch (\Exception $e) {
            // 防止文件夹已存在
        }
        $file=$request->file('img');
        if(!$file||!$file->check()){
            return error('文件格式错误');
        }

        $tmp_name=$file->getInfo('tmp_name');
        $md5 = md5_file($tmp_name);
        $fileName = $md5 . '.' . $ext;
        $imgPath = $path . '/' . $fileName; // 文件的相对路径
        if (!file_exists($imgPath)) {
            $upload = move_uploaded_file($_FILES['img']['tmp_name'], pub_path($imgPath));
            if (!$upload) return error('上传失败，请稍后重试');
        } else {
            diy_log('文件已存在');
        }
        $imgTruePath = str_replace('\\', '/', DOXCX_FRAME_PATH . '/pub/' . $imgPath);  // 文件在本地硬盘的路径
        // 判断是否需要对接阿里OSS

        if (!$admin->oss_status && !$admin->qiniu_status) {
            $is_oss = 0;
            $is_qiniu = 0;
            $realUrl = get_host(strstr($imgPath,'tmpImg'));
        } else if ($admin->oss_status) {
            $is_oss = 1;
            $is_qiniu = 0;
            // 对接阿里OSS，本地文件上传到OSS，得到云地址
            require_once DOXCX_FRAME_PATH . "/fun/aliyun-oss/autoload.php";
            try {
                $ossClient = new \OSS\OssClient($admin->oss_id, $admin->oss_secret, $admin->oss_endpoint);
                // 判断存储空间是否存在
                if (!$ossClient->doesBucketExist($bucketName)) {
                    $ossClient->createBucket($bucketName, \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ);
                } else {
                    $ossClient->putBucketAcl($bucketName, \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ);
                }
                $uploadOssRes = $ossClient->uploadFile($bucketName, $fileName, $imgTruePath);
                $realUrl = $uploadOssRes['info']['url'];
                if (!$realUrl) {
                    // 没获取到Url
                    return error('上传失败，请重试');
                }
            } catch (\OSS\Core\OssException $e) {
                return error('上传到阿里云OSS失败，请联系代理商检查配置：' . $e->getMessage());
            }
        } else if ($admin->qiniu_status) {
            $is_qiniu = 1;
            $is_oss = 0;
            require_once DOXCX_FRAME_PATH . "/fun/qiniu-oss/autoload.php";
            $accessKey = $admin->qiniu_key;
            $secretKey = $admin->qiniu_secret;
            $auth = new \Qiniu\Auth($accessKey, $secretKey);
            $bucket = $admin->qiniu_bucket_name;
            $token = $auth->uploadToken($bucket);
            $filePath = $imgTruePath;
            $key = $fileName;
            $uploadMgr = new \Qiniu\Storage\UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return error('上传到七牛失败，请联系代理商检查配置');
            }
            $realUrl = 'http://' . $admin->qiniu_domain . '/' . $ret['key'];
        }

        // 存入数据库，把path返回到前端
        $save = (new \Model('imglib'))->find(['wid' => $wid, 'type' => 'vshop_img', 'url' => $realUrl]);
        if (!$save->id) {
            $save->wid = $wid;
            $save->is_oss = $is_oss;
            $save->is_qiniu = $is_qiniu;
            $save->type = 'vshop_img';  // 商品图片
            $save->url = $realUrl;
            $save->md5 = $md5;
            $save->ctime = time();
            $save->save();
        }
        return success('上传成功', $realUrl);


    }
    public function del_image(Request $request){
        $wid=\Session::get('wid');
        $id=$request->post('id');
        $info=ImgLib::where(['id'=>$id,'wid'=>$wid])->first();

        $file_url=$info->url;
        if(strpos($file_url,$_SERVER['HTTP_HOST'])){
            $path=pub_path(parse_url($file_url)['path']);
            if(is_file($path))unlink($path);

        }
        $re=$info->delete();
        if($re){
            return success('删除成功');
        }else{
            return error('删除失败');
        }
    }


}