<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\controllers;

use Yii;
use common\components\UploadFile;
use home\models\Attachment;
use yii\data\ActiveDataProvider;

/**
 * 附件控制器
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class AttachmentController extends Controller
{
    /**
     * 不知为何swfupload上传无法通过csrf验证，所以这里暂时先把csrf验证关闭
     */
    public function beforeAction($action)
    {
        $session = Yii::$app->session;
        $session->open();

        $this->enableCsrfValidation = false;
        
        if (parent::beforeAction($action)) {
            return true;
        }
        else {
            return false;
        }

    }

	public function actions() 
	{
		return [];
	}

    /**
	 * 显示上传页面
	 */
    public function actionIndex() 
    {
        $cache = Yii::$app->cache;
        //$cache->set('attach',null);
        //\common\components\Tool::dump($cache->get('attach'));
        $system_config = $cache->get('system_config');

		$upload = new UploadFile();
		$upload->savePath = Attachment::getSavePath();
		$config = array(
			'sys_upload_type' => $system_config['sys_upload_type'],
			'sys_upload_size' => $system_config['sys_upload_size'],
		);
		$request = Yii::$app->request;

		$type = $request->get('type');
		$uploadType = array('image', 'images', 'file', 'files');
		if (!in_array($type, $uploadType)) {
			$this->flash('上传类型错误', 'error');
        }
		$route = $request->get('route');

		$upload_num = ($type == 'image' || $type == 'file') ? 1 : (int) $request->get('upload_num');
		$allow_ext = (!empty($_GET['allow_ext'])) ? $request->get('allow_ext') : $config['sys_upload_type'];
		$allow_ext = explode('|', $allow_ext);
		foreach ($allow_ext as &$ext) {
			$ext = '*.' . $ext;
		}

		return $this->renderPartial('index', [
			'upload_num' => $upload_num,
			'route' => $route,
			'allow_ext' => implode(';', $allow_ext),
			'sys_upload_size' => $config['sys_upload_size'],
		]);
	}

	/**
	 * 执行上传
	 */
    public function actionUpload() 
    {
        //$cache = Yii::$app->cache;
        //$cache->set('post', $_POST);

		$upload = new UploadFile();
		$upload->savePath = Attachment::getSavePath();

		if (!$upload->upload()) {
			$data = ['status' => 0, 'info' => $upload->getErrorMsg()];
		} else {
			$fileInfo = $upload->getUploadFileInfo();
			$firstFile = $fileInfo[0];
			$firstFile['savepath'] = Yii::getAlias('@web') . trim($firstFile['savepath'], '.'); //去除保存路径前面的点号

			$request = Yii::$app->request;

			//插入附件表
			$attach = new Attachment();
			$attach->route = $request->post('route');
			$attach->file_name = $firstFile['name'];
			$attach->file_path =  $firstFile['savepath'] . $firstFile['savename'];
			$attach->file_ext = $firstFile['extension'];
			$attach->file_md5 = $firstFile['hash'];
			$attach->is_image = (in_array($firstFile['extension'], ['jpg', 'jpeg', 'gif', 'png'])) ? 1 : 0;
			$attach->is_thumb = 0;
			$attach->user_id =  Yii::$app->user->identity->user_id;
			$attach->create_time = time();
			$attach->ip = Yii::$app->getRequest()->getUserIP();
			$attach->status = 1;
			$attach->save();


			$data['aid'] = $attach->attach_id; 
			$data['file'] = $firstFile['savepath'] . $firstFile['savename'];
			$data['ext'] = $firstFile['extension'];
			$data['name'] = $firstFile['name'];
			$data['status'] = 1;
		}
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $data['upload'] = $upload;
        return $data;
	}

	/**
	 * 加载图库 
	 */
    public function actionList() 
    {
		$request = Yii::$app->request;

		$query = Attachment::find()
				->where(['user_id' => Yii::$app->user->identity->user_id])
				->orderBy(['create_time' => SORT_DESC]);

		$filename = trim($request->get('filename'));
		$time = trim($request->get('time'));

		if (!empty($filename) ) {
			$query->andWhere(['like', 'file_name', $filename]);
		}
        if (!empty($time)) {
            $time = strtotime($time);
            $startTime = mktime(0, 0, 0, date('m', $time), date('d', $time), date('Y', $time));
            $endTime = mktime(23, 59, 59, date('m', $time), date('d', $time), date('Y', $time));
            $query->andWhere(['between', 'create_time', $startTime, $endTime]);
        }

		$provider = new ActiveDataProvider([
			'query' => $query,
			'pagination' => [
				'pageSize' => 12,
			],
		]);

		return $this->renderPartial('list', [
			'models' => $provider->models,
			'pages' => $provider->pagination,
			'upload_num'=> (int) $request->getQueryParam('upload_num'),
			'get' => $request->get(),
		]);
	}

	/**
	 * 下载文件
	 */
	public function actionDownload()
	{
		$id = (int) Yii::$app->request->get('id');
		$attach = Attachment::find()
				->where(['attach_id' => $id])// 'user_id' => Yii::$app->user->identity->user_id])
				->one();
		$uploadPath = '.'.Yii::getAlias('@web').$attach->file_path;
		if (!$attach || !file_exists($uploadPath)) {
			return $this->flash('下载的文件不存在', 'error');
		}
        //增加下载量
        $attach->downloads = $attach->downloads + 1;
        $attach->save();

        //解决window平台上下载文件中文编码错误问题
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $attach['file_name'] = iconv('utf-8', 'gbk', $attach['file_name']);
        }

		return Yii::$app->response->sendFile($uploadPath, $attach['file_name']);
	}

}
