<?php
/**
 * JYmusic音乐管理系统
 *
 * @version     2.0
 * @author      战神~~巴蒂 <jyuucn@163.com>
 * @license     http://jyuu.cn [未经授权严禁私自出售，否者承担法律责任]
 * @copyright   2014 - 2017 JYmusic
 */

namespace addons\Upload\controller;

use app\services\Uploader;
use app\common\controller\AddonsController;

class BaseController extends AddonsController
{
    /**
     * @var
     */
    protected $fileModel;
    
    protected $validation;
    
    protected $response = ['code' => 0, 'msg' => 'complete'];
    
    protected function uploader($config = [], $field = 'files')
    {
        $model = $this->fileModel;
        $options = [
            'maxSize' =>  20*1024*1024,
            'rootPath' => ROOT_PATH,
            'saveDir' => 'uploads/',
            'extensions' => $this->validation['extensions'],
            'mimeTypes' => $this->validation['mimeTypes'],
            'onUpload' => function($file) use ($model) {
                $fileData = $model->isHave($file['md5']);
                if (false !== $fileData) {
                    $file['is_have'] = true;
                    $file['id'] = $fileData['id'];
                    $file['filepath'] = $fileData['filepath'];
                    $file['save_path'] = $fileData['filepath'];
                    return $file;
                }
            },
            'onSuccess'  => function($file) use ($model) {
                $data     = [
                    'filepath'    => '/' . ltrim($file['save_path'], '/'),
                    'name'        => $file['name'],
                    'size'        => $file['size'],
                    'mime'        => $file['mime_type'],
                    'ext'         => $file['extension'],
                    'md5'         => $file['md5'],
                    'sha1'        => $file['sha1'],
                    'location'    => 0,
                    'create_time' => time(),
                ];
                //入库当前文件
                if ($model->data($data)->save()) {
                    return [
                        'filepath' => $data['filepath'],
                        'id' => $model->id
                    ];
                } else {
                    return false;
                }
            },
        ];
        
        $options = is_array($config) && !empty($config) ? array_merge($options, $config) : $options;
        
        $uploader = new Uploader($field, $options);
        $result = $uploader->upload();
        
        $files = $result['files'];
        if(count($files) > 0) {
            foreach ($files as &$val) {
                if (isset($val['errorCode'])) {
                    if ($val['errorCode'] == 400216) {
                        $val['code'] = 0;
                        unset($val['error'], $val['errorCode']);
                    } else {
                        unset($val['save_root']);
                        $val['error'] = lang($val['errorCode']);
                    }
                } else {
                    $val['code'] = 0;
                    unset($val['error'], $val['save_root']);
                }
                $this->response['files'] = $files;
            }
        } else {
            $this->response['error'] = lang($result['errorCode']);
            $this->response['code'] = $result['errorCode'];
        }
    }
    
    /**
     * 获取上传类型
     * @param $type
     * @return bool|mixed
     */
    public function getValid($type)
    {
        $allowTypes = [
            'audio' => [
                'mimeTypes' => ['audio/mp3','audio/mpeg','video/mp4','audio/mp4','audio/ogg','audio/x-wav','audio/webm','audio/x-flac','audio/mp4a-latm'],
                'extensions' => ['mp3','mp4','m4a','oga','ogg','wav','weba','flac'],
                'is_img' => false
            ],
            'image' => [
                'mimeTypes' => ['image/jpeg','image/png','image/gif','image/bmp','image/x-icon'],
                'extensions' => ['jpg','jpeg','png','gif','bmp','ico'],
                'is_img' => true
            ],
            'video' => [
                'mimeType' => ['video/3gpp','video/x-msvideo','video/x-f4v','video/x-flv','video/h264','video/ogg','video/mpeg','video/mp4','application/vnd.apple.mpegurl'],
                'extensions' => ['3gp','avi','f4v','flv','h264','mp4','mpeg','m4v','ogv','m3u8'],
                'is_img' => false
            ],
            'attach' => [
                'mimeTypes' => ['text/plain','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-excel','application/pdf','application/zip','application/x-rar-compressed','application/x-7z-compressed'],
                'extensions' => ['txt','doc','docx','xlm','xlsx','xls','pdf','zip','rar','7z'],
                'is_img' => false
            ]
        ];
        
        return isset($allowTypes[$type]) ? $allowTypes[$type] : false;
    }

    /**
     * 针对WangEditor 单独设置返回
     * @param int $version
     * @return void
     */
    protected function retWangEdit2()
    {
        if ($this->response['code'] == 0) {
            $file = $this->response['files'][0];
            if ($file['error']) {
                die('error|' . $file['error']);
            } elseif($file['local'] === 0) {
                $path = $this->request->domain() . $file['filepath'];
            } else {
                $path = $file['filepath'];
            }
            die($path);
        } else {
            die('error|' . $this->response['error']);
        }
    }

    /**
     * 针对WangEditor3 单独设置返回
     * @return array
     */
    protected function retWangEdit3()
    {
        if ($this->response['code'] == 0) {
            $file = $this->response['files'][0];
            if ($file['error']) {
                $res['errno'] = $file['error'];
            } elseif ($file['local'] === 0) {
                $res['errno']  = 0;
                $res['data'][] = $this->request->domain() . $file['filepath'];
            } else {
                $res['data'][] = $file['filepath'];
            }
        } else {
            $res['errno'] = $this->response['error'];
        }
        die(json_encode($res));
    }
}
