<?php

use yii\helpers\Html;
use yii\helpers\Url;
//use yii\grid\ActionColumn;
//use yii\widgets\ListView;
//use yii\grid\GridView;
use yii\widgets\Pjax;
/** @var yii\web\View $this */
/** @var yii\data\ActiveDataProvider $dataProvider */
use dosamigos\fileupload\FileUpload;
use yii\web\View;

$this->title = 'Документы';
$this->params['breadcrumbs'][] = ['label' => 'Документы', 'url' => ['index'] ];

$ucat = Yii::$app->request->get('cat', '');
if( $ucat ){
	$this->params['breadcrumbs'][] = ['label' => $ucat, 'url' => ['index', 'cat'=>$ucat]];
}

$croute = '/manager/docs';

$rootcat = $model->GetRootCat();
$curcat = $model->GetCat();

$cat = yii\helpers\FileHelper::findDirectories($curcat);
$files = yii\helpers\FileHelper::findFiles($curcat,['recursive'=>false]);
$ckey = 'dosc_cat_'.md5($ucat);
Yii::$app->cache->delete($ckey);
$docs = Yii::$app->cache->getOrSet( $ckey, function () use ($model, $ucat) {
		return $model->find()->where(['cat'=>$ucat?$ucat:null])->all();
	},2 );
//var_dump($docs);
$docsf = [];
foreach($docs as $key => $item){
	$docsf[$item->uid] = $key;
}
//$docsf = array_flip( yii\helpers\ArrayHelper::getColumn($docs, "uid") );
?>
<style>
.docs-index {
	font-size:1rem;
}
</style>
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h5><i class="icon fas fa-check"></i> info!</h5>
<?=Yii::$app->session->getFlash('success');?>
</div>

<?php endif; ?>


<div class="docs-index">

    <p>
        <?= Html::a('Создать Docs', ['create', 'cat' => $ucat], ['class' => 'btn btn-success']) ?>
        <?= Html::a('Создать Папку', ['catcreate'], ['class' => 'btn btn-success']) ?>
        <?= Html::a('Массовая загрузка', ['uploads', 'cat'=>$ucat ], ['class' => 'btn btn-success']) ?><br>
    </p>


<div class="card" id="conteiner">
  <div class="card-header">
    <h3 class="card-title"><a href="/<?=Yii::$app->controller->route?>"><i class="icon fas fa-home mx-2"></i></a> <a href="/<?=Yii::$app->controller->route?>?cat=<?=$ucat?>"><i class="fas fa-1x fa-sync-alt mx-2"></i></a> Папка <?=$ucat?></h3><i class="fas fa-upload mx-3"></i>
    <div class="card-tools">
      <button type="button" class="btn btn-tool" data-card-widget="collapse">
        <i class="fas fa-minus"></i>
      </button>
    </div>
  </div>
  <div class="card-body p-0">
    <ul class="nav nav-pills flex-column" id="filesbox">

<?
foreach($cat as $item ){
	$file = str_replace( $rootcat.'/', '', $item );
?>
<li class="nav-item">
        <a href="?cat=<?=$file?>" class="nav-link">
          <i class="fas fa-inbox"></i> <?=$file?>
        </a>
</li>
<?
}

foreach($files as $item ){
	$ext = pathinfo($item, PATHINFO_EXTENSION);
//	$bsaename = str_replace( '.'.$ext, '', pathinfo($item, PATHINFO_BASENAME));
	$bsaename = str_replace( '.', '_', pathinfo($item, PATHINFO_BASENAME));

	if( $ext == 'webp' ) continue;
	$file = str_replace( $rootcat.'/', '', $item );
	$ext = pathinfo($item, PATHINFO_EXTENSION);
	$webp = str_replace( '.'.$ext, '.webp', $item );
	if( !file_exists($webp) && $ext != 'webp' && ( $ext == 'pdf' || $ext == 'jpg' || $ext == 'png' || $ext == 'jpeg'  || $ext == 'svg' )){
		exec('convert -thumbnail x200 -background white -alpha remove '.$item.'[0] '.$webp);
	}
	$url = $model::$story_dir. DIRECTORY_SEPARATOR .$file;
?>
<li class="nav-item">
        <a href="<?=$url?>" class="nav-link" target="_blank" style="display: inline-block;">
<?
if( file_exists($webp)  ){
?>
		  <img src="<?=$model::$story_dir. DIRECTORY_SEPARATOR .str_replace( '.'.$ext, '.webp', $file );?>" style="max-height:60px;max-width: 90px;">
<?
}else{
?>
          <i class="far fa-file-alt"></i>
<?
}
	$key = pathinfo($item, PATHINFO_BASENAME);
//	$p = $model->find()->where(['uid'=>$key])->one();

	$p = isset($docsf[$key])?$docs[$docsf[$key]]:false;
	if( $p ){
		$title = $p->title;
		$id = $p->id;
		unset($docsf[$key]);
	}else{
		$title = $file;
		$id = $key."&cat=$ucat";
	}
?>
 <span id="<?=$bsaename?>"><?=$title?></span>
        </a><button type="button" class="btn btn-default btn-sm"><i class="fas fa-edit" onclick="edit('<?=$bsaename?>')"></i></button> <a href="<?=$croute?>/delete?id=<?=$id?>&cat=<?=$ucat?>"><button type="button" class="btn btn-default btn-sm"><i class="fas fa-trash"></i></button></a>
</li>
<?
}

?>
      </li>
<?
foreach($docsf as $item ){
	$p = $docs[$item];
	$id = $p->id;
?>
	<li class="nav-item">
        <a href="<?=$croute?>/view?id=<?=$p->id?>" class="nav-link" style="display: inline-block;">
          <i class="fas fa-file"></i> <?=$p->title?>
        </a> <a href="<?=$croute?>/update?id=<?=$id?>"><button type="button" class="btn btn-default btn-sm"><i class="fas fa-edit"></i></button></a> <a href="<?=$croute?>/delete?id=<?=$id?>&cat=<?=$ucat?>"><button type="button" class="btn btn-default btn-sm"><i class="fas fa-trash"></i></button></a>
     </li>
<?
}
?>
    </ul>
  </div>
</div>

</div>

<div class="modal" tabindex="-1" id="modal-lg" aria-modal="true" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Заголовок файла</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <input type="text" id="titlev" value="" class="form-control form-control-lg">
        <input type="hidden" id="uid" value="">
      </div>
      <div class="modal-footer justify-content-between">
        <button type="button" class="btn btn-default" data-dismiss="modal">Отменить</button>
        <button type="button" class="btn btn-primary" onclick="save()">Сохранить</button>
      </div>
    </div>

  </div>

</div>

<div class="info-box bg-info" style="width: 300px; position: fixed; bottom: 0px; right: 0px;display:none" id="templ1">
<span class="info-box-icon bg-info"><i class="far fa-copy"></i></span>
<div class="info-box-content">
<span class="info-box-text">Uploads</span>
<div class="progress">
<div class="progress-bar" style="width: 0%"></div>
</div>
</div>
</div>

<script>
function edit(id){
	val = $('#'+id).html();
	$('#titlev').val(val);
	$('#uid').val(id);
	$('#modal-lg').modal('show');
}
function save(){
	uidl = $('#uid').val();
	val = $('#titlev').val();
	$('#'+uidl).html(val);
	$('#modal-lg').modal('hide');
	$.post( "updatetitle", {'uid':uidl,'title':val, 'text':'', 'cat':'<?=$ucat?>','_csrf':'<?=Yii::$app->request->csrfToken?>'}, function( data, status, xhr ) {
		if( data.status == 'ok' ){

		}
		if( data.status == 'err' ){
			console.log( data.text );
			alert(data.text);
		}
    }, "json");
}
	var poper = new Map();
</script>
<?
\Yii::$app->assetManager->bundles['yii\\bootstrap\\BootstrapAsset'] = [
        'css' => [],
        'js' => []
    ];
?>
<?= FileUpload::widget([
    'model' => $model,
    'attribute' => 'file',
    'url' => ['docsupload', 'id' => 0, 'cat'=>$ucat],
	'options' => ['accept' => '*'],
    'clientOptions' => [
	'limitConcurrentUploads' => 3,
	'disableImageMetaDataLoad' => true,
	'autoUpload' => true,
    ],
    // ...
    'clientEvents' => [
        'fileuploaddone' => 'function(e, data) {
								res = JSON.parse(data.result);
								$("#filesbox").append("<a href="+res.files[0].name+" class=\"nav-link\" target=\"_blank\" style=\"display: inline-block;\"><i class=\"far fa-file-alt\"></i> <span>"+res.files[0].name+"</span></a>");
								var obj = poper.get(res.files[0].oname);
								setTimeout(() => {
									obj.css("display", "none");
								}, 2000);
								e.preventDefault();
                            }',
        'fileuploadfail' => 'function(e, data) {
//                                console.log(e);
                                console.log(data);
								e.preventDefault();
                            }',
		'fileuploadchange' => 'function(e, data) {
								starting(e, data);
                          }',
		'fileuploaddrop' => 'function(e, data) {
								starting(e, data);
							}',
		'fileuploadprogress' =>'function(e,data) {
								e.preventDefault();
								progress = parseInt(data.loaded / data.total * 100, 10);
								var obj = poper.get(data.files[0].name);
								obj.find(".progress-bar").css("width", progress+"%");
							}',
		'fileuploadstop' => 'function(e) {
                                console.log("fin");
								setTimeout(() => {
									window.location.reload();
								}, 3000);
							}'
    ],
]); ?>
<script>
function starting(e, data){
								data.files.forEach( function(value,key){
									res = value.name;
									console.log(res);
									var i = $("#templ1").find(".info-box-text");
									i.text("Upload "+res);
									var templ = $("#templ1").clone();
									templ.css("display", "block");
									var index = poper.size;
									if( index > 0 ){
										poper.forEach( function(value,key) {
											y = parseInt(value.css("bottom"), 10);
											y = y +90;
											if( y > 800 ) y = y - 800;
										});
									}else{
										y = 0;
									}
									templ.css("bottom", y+"px");
									templ.attr( "id", "poper_"+index );
									poper.set(res, templ);
									$("body").append(templ);
								});
								console.log("start");
}
</script>
<?
$this->registerJs(<<<JS
    var	dzone=$('#conteiner');
	$('#docs-file').fileupload({'dropZone':dzone});
JS, View::POS_READY
);

