<?php

$cs = Yii::app()->getClientScript();

$cs->registerCssFile(FaHtml::getJsUrl('handsontable/dist/pikaday/pikaday.css'));
$cs->registerCssFile(FaHtml::getJsUrl('handsontable/handsontable.full.min.css'));
$cs->registerCssFile(FaHtml::getJsUrl('ruleJS/src/handsontable.formula.css'));
$cs->registerCssFile(FaHtml::getJsUrl('handsontable//plugins/removeRow/handsontable.removeRow.css'));

$cs->registerScriptFile(FaHtml::getJsUrl('handsontable/handsontable.full.js'));
$cs->registerScriptFile(FaHtml::getJsUrl('handsontable/dist/moment/moment.js'));
$cs->registerScriptFile(FaHtml::getJsUrl('handsontable/dist/pikaday/pikaday.js'));
$cs->registerScriptFile(FaHtml::getJsUrl('ruleJS/bower_components/ruleJS/dist/full/ruleJS.all.full.js'));
$cs->registerScriptFile(FaHtml::getJsUrl('ruleJS/src/handsontable.formula.js'));
$cs->registerScriptFile(FaHtml::getJsUrl('handsontable/plugins/removeRow/handsontable.removeRow.js'));
$cs->registerScriptFile(FaHtml::getJsUrl('estimativas.js'));

$this->renderPartial('_estimativas_planejamento_estilos', array('model' => $model));
?>	
<!-- tabela estimativas -->
	<div class="div-atividades">
	    <h1 class="novo-layout">Estimativas</h1>
	    <?php if($model->podeEditarEstimativas()) { ?>
		<span class="options">
			<button name="save" id="salvar-estimativas">Salvar</button>
			<button name="load" id="carregar-estimativas">Carregar</button>
		</span>
	    <?php } ?>
		<div id="planilha-estimativas"></div>
		<div id="resumo-estimativas">
			<b>Total de horas</b>
			<span class="desenvolvimento" id="estimativa-desenvolvimento">00:00</span>
			<span class="testes" id="estimativa-testes">00:00</span>
		</div>
	</div>
<!-- tabela planejamento -->
	<div class="clearfix"></div>

	<div class="div-atividades">
	    <h1 class="novo-layout">Planejamento</h1>
	    <span class="options">
	    	<?php if($model->podeEditarPlanejamento()) { ?>
		    	<?php $url = $model->getPlanejamento() ? $model->getPlanejamento()->getUrl() : "#"; ?>
		    	<a href="<?php echo $url ?>" id="download-xml" class="button <?php if($url == '#') {echo 'sr-only';}?>">Download XML</a>
		    	<button name="save" id="atualizar-planejamento" data-toggle="modal" data-target="#captchaModal" >Atualizar planejamento</button>
		    <?php } ?>
	    	<label id="ck-button" class="checked">
				<input type="checkbox" name="milestone-only" id="milestone-only" checked="checked" /><i class="fa fa-check"></i><span class="milestone-label-text">Mostrar somente marcos</span>
			</label>
		</span>
		<div id="planilha-planejamento"></div>
	</div>
	<div class="clearfix"></div>
	<script type="text/javascript">
		function milestoneRenderer(instance, td, row, col, prop, value, cellProperties) {
		    Handsontable.renderers.TextRenderer.apply(this, arguments);
		    if(instance.getDataAtRowProp(row, 'milestone') == 1) {
		    	td.style.fontWeight = 'bold';
			    td.style.color = 'green';
			    td.style.background = '#CEC';
			    $(td).parent('tr').addClass('planejamento-milestone');
		    } else {
			    $(td).parent('tr').addClass('planejamento-task');
				if($('#milestone-only').is(':checked')) {
					$(td).parent('tr').addClass('sr-only');
				} else {
					$(td).parent('tr').removeClass('sr-only');
				}
		    }
		    if(prop == 'descricao') {
				$(td).addClass('planejamento-nivel-'+instance.getDataAtRowProp(row, 'nivel'));
				td.innerHTML = instance.getDataAtRowProp(row, 'codigo') + ' ' + value;
		    }
		    if(instance.getDataAtRowProp(row, 'summary') == 1) {
			    $(td).parent('tr').addClass('planejamento-summary');
		    }
		    return td;
		}
		var dataPlanejamento = <?php echo CJSON::encode($model->loadPlanejamento()); ?>;
		var containerPlanejamento,	hotPlanejamento;
		containerPlanejamento = document.getElementById('planilha-planejamento');

		hotPlanejamento = new Handsontable(containerPlanejamento, {
			data: dataPlanejamento,
			rowHeights: 30,
	    	stretchH: 'all',
			colWidths: [300, 100, 100, 100, 120, 120, 180],
			colHeaders: ['Descrição', 'Antecessores','Duração', 'Trabalho', 'Início', 'Fim', 'Envolvidos'],
			columns: [
				{data: 'descricao', renderer: milestoneRenderer},
				{data: 'predecessor', renderer: milestoneRenderer},
				{data: 'duracao', renderer: milestoneRenderer},
				{data: 'trabalho', renderer: milestoneRenderer},
				{data: 'inicio', renderer: milestoneRenderer},
				{data: 'fim', renderer: milestoneRenderer},
				{data: 'envolvidos', renderer: milestoneRenderer},
			],
	    	readOnly: true,
		});
		function checkMilestone() {
			if($('#milestone-only').is(':checked')) {
				$('.planejamento-task').addClass('sr-only');
				$('#ck-button').addClass('checked');
			} else {
				$('.planejamento-task').removeClass('sr-only');
				$('#ck-button').removeClass('checked');
			}
		}
		checkMilestone();
		$('#milestone-only').change(checkMilestone);
	
		var	dataEstimativas = <?php echo CJSON::encode($model->loadEstimativas()); ?>;

		var containerEstimativas, hotEstimativas;
		containerEstimativas = document.getElementById('planilha-estimativas');
		hotEstimativas = new Handsontable(containerEstimativas, {
			data: dataEstimativas,
	    	<?php if($model->podeEditarEstimativas()) { ?>
				outsideClickDeselects: false,
	    		removeRowPlugin: true,
	    		beforeRemoveRow: function(){return confirm("Tem certeza que deseja excluir esta atividade?")},
	    	<?php } else { ?>
	    		readOnly: true,
	    	<?php } ?>
			rowHeights: 35,
			minSpareRows: 1,
	    	stretchH: 'all',
			colWidths: [260, 82, 82, 82,82,82,82,82,82,82,82,75,75],
			colHeaders: ['Descrição', 'Dev', 'Testes', 'Dev', 'Testes', 'Dev', 'Testes', 'Dev', 'Testes', 'Dev', 'Testes', 'Dev', 'Testes'],
			columns: [
				{data: 'EST_DESCRICAO'},
				{data: 'EST_INTERFACE_DEV', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_INTERFACE_TESTES', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_DADOS_DEV', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_DADOS_TESTES', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_RELATORIO_DEV', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_RELATORIO_TESTES', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_REGRAS_DEV', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_REGRAS_TESTES', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_TABELAS_DEV', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_TABELAS_TESTES', editor: 'select', selectOptions: ['Simples', 'Media', 'Complexa']},
				{data: 'EST_TEMPO_DEV', renderer: EstimativasDesenvolvimentoRenderer},
				{data: 'EST_TEMPO_TESTES', renderer: EstimativasTestesRenderer},
			],
		    afterRender: function () {
	            $(containerEstimativas).find('thead').find('tr').before('<tr id="header-grouping"><?php echo ($model->podeEditarEstimativas() ? '<th></th>' : ''); ?><th>Tarefa</th><th colspan="2">Tipo da Interface</th><th colspan="2">Manipulação de Dados</th><th colspan="2">Relatório</th><th colspan="2">Regras de Negócio</th><th colspan="2">Nro. Tabelas/Datamodule</th><th colspan="2">Horas</th></tr>');
			},
	        beforeRender: function() {
	        	while ($('#header-grouping').size() > 0) {
	                $('#header-grouping').remove();
	        	}
	        },
		});
		<?php if($model->podeEditarEstimativas()) { ?>
		$('#carregar-estimativas').click(function () {
		  $.ajax({
		    url: createUrl('estimativas/load'),
		    data: {id: <?php echo $model->SOL_IDPENDENCIA; ?>},
		    dataType: 'json',
		    type: 'GET',
		    success: function (response) {
		      hotEstimativas.loadData(response.data);
		      alert(response.message);
		    },
		    error: function (response) {
		      alert(response.responseText);
		    }
		  });
		});

		$('#salvar-estimativas').click(function () {
		  $.ajax({
		    url: createUrl('estimativas/save'),
		    data: {Estimativas: hotEstimativas.getSourceData(), id: <?php echo $model->SOL_IDPENDENCIA; ?>},
		    dataType: 'json',
		    type: 'POST',
		    success: function (response) {
		      if(response.errors != undefined) {
		      	errors = JSON.stringify(response.errors);
		      	errors = errors.replace('"', '');
		      	errors = errors.replace('{', '');
		      	errors = errors.replace('}', '');
		      	var message = response.message + "\n" + errors;
		      	alert(message);
		      } else {
		      	alert(response.message);
		      }
		    },
		    error: function (response) {
		      alert(response.message);
		    }
		  });
		});
		<?php } ?>
	</script>
<?php if($model->podeEditarPlanejamento()) { ?>
<!-- modal upload arquivo-->
	<div class="modal fade" id="captchaModal" tabindex="-1" role="dialog" aria-hidden="true">
	    <div class="modal-dialog">
	        <div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only hide">Fechar</span></button>
	                <h1 class="modal-title" id="myModalLabel">Atualizar planejamento</h1>
	            </div>
				<form id="formulario-planejamento" enctype="multipart/form-data" method="post" action="<?php echo Yii::app()->createUrl('planejamentoSolicitacoes/save');?>">
	            	<div class="modal-body">
		                <input type="hidden" id="ARQ_FOREIGNKEY" name="ARQ_FOREIGNKEY" value="<?php echo $model->SOL_IDPENDENCIA;?>">
			            <div class="input-group">
			                <label for="ARQ_ARQUIVO" class="input-group-btn">
			                    <span class="btn btn-primary">
			                        Selecione o XML do projeto<input type="file" class="form-control" id="ARQ_ARQUIVO" name="ARQ_ARQUIVO" style="display: none;" accept=".xml"/>
			                    </span>
			                </label>
			                <input type="text" id="file-name" class="form-control" readonly="">
			            </div>
			            <div id="error-upload-planejamento" class="color-red col-xs-12"></div>
			            <div id="success-upload-planejamento" class="color-green col-xs-12"></div>
		        	</div>
		            <div class="modal-footer">
		                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
		                <button type="submit" class="btn btn-success" id="upload">Atualizar</button>
		            </div>
	            </form>
	        </div>
	    </div>
	</div>
	<!-- scripts modal upload de arquivos -->
	<script>
	$(function() {
	    $('#atualizar-planejamento').on('click', function (e) {
			placeError('');
	        placeSuccess('');
	        return true;
		});
		$(document).on('change', ':file', function() {
		    var input = $(this),
		        numFiles = input.get(0).files ? input.get(0).files.length : 1,
		        label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
		    input.trigger('fileselect', [numFiles, label]);
		});
		$(document).ready( function() {
		    $(':file').on('fileselect', function(event, numFiles, label) {
		    	$("#file-name").val(label);
		    });
		});
		function refreshButton(btn) {
			$(btn).html("Atualizar");
			btn.removeAttr('disabled');
		}
		function placeError(message) {
			$('#error-upload-planejamento').html(message);
		}
		function placeSuccess(message) {
			$('#success-upload-planejamento').html(message);
		}
	    $('#formulario-planejamento').submit(function (e) {
	    	e.preventDefault();
	        var btn = $("#upload");
	        placeError('');
	        placeSuccess('');
			var formData = new FormData($('#formulario-planejamento'));
			formData.append('ARQ_ARQUIVO', $('#ARQ_ARQUIVO')[0].files[0]);
			formData.append('ARQ_FOREIGNKEY', $('#ARQ_FOREIGNKEY').val());
		    $.ajax({
		        url: createUrl('planejamentoSolicitacoes/save'),
		        type: 'POST',
		        data: formData,
		        success: function (response) {
		        	var resp = jQuery.parseJSON(response);
		            if(resp.xmlLink != undefined) {
		            	$('#download-xml').prop('href', resp.xmlLink);
		            }
		            if(resp.data!= undefined) {
		            	hotPlanejamento.loadData(resp.data);
		            }
		            refreshButton(btn);
		            $('#formulario-planejamento').trigger("reset");
		            placeSuccess(resp.message);
		        },
		        error: function(response) {
		        	placeError(response.responseText);
		            refreshButton(btn);
		        },
		        cache: false,
		        contentType: false,
		        processData: false,
		    });
		    refreshButton(btn);
		});
	});
</script>
<?php } ?>