<?php
/**
 * JYmusic音乐管理系统
 * @version    2.0
 * @author     战神~~巴蒂 <jyuucn@163.com>
 * @license    http://jyuu.cn/license
 * @copyright  2014 - 2017 JYmusic
 */
namespace addons\Upload\controller;

use think\Db;
use think\Cache;
use Gregwar\Image\Image;

/**
 * 用户头像上传控制
 */
class AvatarController extends BaseController
{
    protected $conf;

    protected $layer;

    protected $file;

    protected $uid;

    public function index()
    {
        //判断头像上传次数
        $this->conf = get_addon_config('Upload');
        //$this->file = $this->request->file('avatar_file');
        $this->uid  = $this->request->param('uid', is_login());

        if (!allow_send_set($this->uid)) {
            $res = ['code' => 40013, 'error' => '本月头像上传次已达上限'];
            return json($res, 200);
        }

        if (!is_numeric($this->uid)) {
            $res = ['code' => 40401, 'error' => 'Please login'];
            return json($res, 200);
        }
        
        // 上传文件验证
        $maxSize = $this->conf['local_avatar_max_size'];
        $maxSize = $maxSize ? $maxSize  : 10; //单位M
    
        $this->validation = $this->getValid('image');
    
        $config['maxSize'] = $maxSize * 1024 * 1024;
        $config['saveDir'] = 'uploads/avatar/' . $this->uid . '/';
        $config['saveName'] = 256;
        $config['onUpload'] = null;
    
        //处理裁剪图像
        $avatarData = $this->request->param('avatar_data');
        $avatarData = json_decode($avatarData, true);
        
        $config['onSuccess'] = function ($file) use ($avatarData)
        {
            $imageFile = $file['save_root'] . $file['save_path'];
            $layer = Image::open($imageFile);
            //设置缓存
            $layer->setCacheDir(ROOT_PATH . 'storage/image');
            $error = false;
            
            if (!empty($avatarData)) {
                //如果有旋转，先旋转图片
                if (!empty($avatarData['rotate'])) {
                    $layer->rotate($avatarData['rotate']);
                }
             
                $newWidth  = $avatarData['width']; // px
                $newHeight = $avatarData['height']; // px
                $posX      = $avatarData['x']; // left translation of 30px
                $posY      = $avatarData['y']; // top translation of 20px
    
                $newWidth = $newWidth < 256? 256 : $newWidth;
                $newHeight = $newHeight < 256? 256 : $newHeight;
                
                try {
                    $layer->crop($posX, $posY, $newWidth, $newHeight);
                } catch (\Exception $e) {
                    $error = $e->getMessage();
                }
            }
            
            $conserve = true;
            try {
                //保存256
                $layer->resize(256, null, $conserve);
                $layer->save($imageFile);
                
                //保存128
                /*
                $layer = Image::open($imageFile);
                $layer->resize(128, null, $conserve);
                $imageFile = str_replace('256', 128, $imageFile);
                $layer->save($imageFile);
                
                //保存64
                $layer = Image::open($imageFile);
                $layer->resize(64, null, $conserve);
                $imageFile = str_replace('128', 64, $imageFile);
                $layer->save($imageFile);
                */
                
            } catch (\Exception $e) {
                $error = $e->getMessage();
            }
            
            if (false !== $error) {
                return [
                    'errorCode' => 40500,
                    'error' => $error
                ];
            }
        };
        
        $this->uploader($config, 'avatar_file');
        
        if ($this->response['code'] > 0) {
            return json($this->response, 200);
        }
        
        $file = $this->response['files'][0];
        
        if (isset($file['errorCode'])) {
            return json(['code' => $file['errorCode'], 'error' => $file['error']], 200);
        }
        
        $this->saveData($file['save_path']);
        $res = [
            'code' => 0,
            'filepath' => $file['save_path'],
            'msg' => lang('avatar_upload_success')
        ];
        
        return json($res, 200);
    }
    
    protected function saveData($filePath)
    {
        Db::name('member')->where('uid', $this->uid)
            ->setField('avatar', $filePath);
        $filePath = get_cover_url($filePath);
    
        //需要修改缓存中的头像数据
        $list = Cache::get('sys_user_info_list');
        /* 查找用户信息 */
        $key = "u{$this->uid}";
        if (isset($list[$key])) {
            //已缓存，更新缓存
            $list[$key]['avatar'] = $filePath . '?v=' . uniqid();
            Cache::set('sys_user_info_list', $list);
        }
        //记录用户上传
        set_user_send($this->uid);
    }
}

