<?php
    $this->layout = 'telao';
    Yii::import('ext.qTip2.qTip2');
    qTip2::apply('.tool_tip');
    $script = '';
?>
    <a class="search-button" href="#"><?= FaHtml::iconSetaClose(); ?></a>
    <a onclick="reloadFrame();" class="refresh-button" href="javascript:void(0);"><?= FaHtml::iconRefresh(); ?></a>

    <div class="search-form" style="display: none;" >
        <?php $this->renderPartial('_search_visao_geral', array('model' => $model)); ?>
    </div><!-- search-form -->

<?php if (in_array(User::getPrivilegio(), [1, 12, 20])) { ?>
    <?php
        $nomes = $model->getFuncionariosOciosos();
        $nomes = array_unique($nomes);
        if (count($nomes) > 1) {
            $msg = implode(", ", $nomes) . " não estão trabalhando em nenhuma pendência!";
        } else {
            $msg = implode(", ", $nomes) . " não está trabalhando em nenhuma pendência!";
        }
        echo FaHtml::alert($msg, 'important', false, false);
    ?>
<?php } elseif ($model->temPrivilegioLancarFases()) { ?>
    <?php if (!$model->estaTrabalhandoEmPendencia()) { ?>
        <div id="alertAviso" class="alert alert-important" role="alert">
            <div class="alert-message">
                VOCÊ NÃO ESTÁ TRABALHANDO EM NENHUMA PENDÊNCIA!
            </div>
        </div>
    <?php } ?>
<?php } ?>

<table width="100%">

	<thead>
		<tr>
			<?php foreach($solicitacoes as $local) { ?>
			<th class="<?= getClassContador($local['count'],$local['max']);?>">
				<span><?= str_replace('Pendência', '', $local['title']); ?> <?= getSituacao($local); ?></span>
			</th>
			<?php $script .= notify($local); ?>
			<?php } ?>
		</tr>
	</thead>
	<tbody>
		<tr>
			<?php foreach($solicitacoes as $local) { ?>
                <td class="<?= getClassContador($local['count'],$local['max']);?>">
                    <ul>
                        <?php foreach($local['pendencias'] as $key => $pendencia) { ?>
                            <?php
                                $class = "";
                                if ($pendencia->pendenciaEmProducao) {
                                    $class = " pendenciaEmProducao";
                                }
                            ?>
                            <li class="pendencia<?= $class; ?>">
                                <?= CHtml::link($pendencia->SOL_IDPENDENCIA,
                                                ['solicitacoes/view', 'id' => $pendencia->SOL_IDPENDENCIA],
                                                ['target' => '_blank']); ?>
                                <?= FaHtml::spanMovimentacaoPendenciasTooltip($pendencia->getNumeroVezesLocal()); ?>
                                <?= Util::formatTxtSolicitacaoTooltip($pendencia, '<i class="icon-file-alt"></i>', true); ?>
                                <?php
                                    if ($pendencia->SOL_PENDENCIA_PRIORITARIA) {
                                        echo CHtml::link(
                                            '<i class="fa fa-flag" aria-hidden="true"></i>',
                                            '#',
                                            array(
                                                'id'             => 'pendenciaPrioritaria',
                                                'data-toggle'    => 'tooltip',
                                                'data-placement' => 'bottom',
                                                'title'          => 'Esta pendência é prioritária'
                                            )
                                        );
                                    }
                                ?>
                                <span class="data">
                                    <?= Util::formatDatasSolicitacaoTooltip($pendencia, '<i class="icon-time"></i>', true); ?>
                                    <?= getTempoParada($pendencia); ?>
                                </span>
                                <hr />
                                    <?= FaHtml::spanMotivoPendencia($pendencia->SOL_IDMOTIVO, $pendencia->Motivo); ?>
                                <?php
                                    $responsavel = getResponsavel($pendencia);
                                    if(empty($responsavel)){
                                        $responsavel = '-';
                                    }
                                ?>
                                <span class="data">
                                    <?= Util::formatEnvolvidosSolicitacaoTooltip($pendencia, '<i class="icon-user"></i>') ?>
                                    <?= Util::shortenName($responsavel); ?>
                                </span>
                            </li>
                        <?php } ?>
                    </ul>
                </td>

            <?php } ?>
        </tr>
    </tbody>
</table>
<?php
$cs = Yii::app()->getClientScript();
$percent = 100/count($model->SOL_IDLOCAL);
$css = <<<CSS
    .pendenciaEmProducao {
        background-color: #f0f994 !important;
    }
    #pendenciaPrioritaria {
        color: #d9534f;
        animation-name: blinker;
        animation-duration: 1.2s;
        animation-timing-function: cubic-bezier(.5, 0, 1, 1);
        animation-iteration-count: infinite;
    }

    .search-form .ui-multiselect {
        width: 464px!important;
    }
    form .row.tiny {
        height: 165px!important;
    }
    .tool_tip {
        display: inline;
    }
    @-moz-keyframes blinker {
        0% { opacity: 1.0; }
        50% { opacity: 0.3; }
        100% { opacity: 1.0; }
    }

    @-webkit-keyframes blinker {
        0% { opacity: 1.0; }
        50% { opacity: 0.3; }
        100% { opacity: 1.0; }
    }

    @keyframes blinker {
        0% { opacity: 1.0; }
        50% { opacity: 0.3; }
        100% { opacity: 1.0; }
    }
    * {
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        font-size: 11px;
    }
    body {
        padding: 5px;
        background-color: #F0F0F0;
    }
    table {
        border-collapse: collapse;
    }
    table, th, td {
        border: 1px solid #C0C0C0;
    }
    th span {
        font-size: 14px;
    }
    th {
        font-size: 14px;
        width: {$percent}%;
        padding: 10px 0;
    }
    th.green,
    th.green *{
        color: green;
    }
    th.yellow,
    th.yellow *{
        color: #abab3f;
    }
    th.red,
    th.red * {
        color: red;
    }
    th.animate_text span {
        -webkit-animation-name: blinker;
        -webkit-animation-duration: 1.2s;
        -webkit-animation-timing-function: cubic-bezier(.5, 0, 1, 1);
        -webkit-animation-iteration-count: infinite;
        -moz-animation-name: blinker;
        -moz-animation-duration: 1.2s;
        -moz-animation-timing-function: cubic-bezier(.5, 0, 1, 1);
        -moz-animation-iteration-count: infinite;
        animation-name: blinker;
        animation-duration: 1.2s;
        animation-timing-function: cubic-bezier(.5, 0, 1, 1);
        animation-iteration-count: infinite;
    }
    .green {
        background: #f4fff4;
    }
    .yellow {
        background: #f7f7ec;
    }
    .red {
        background: #f7f1f1;
    }
    td {
        height: 600px;
        padding: 10px;
        vertical-align: top;
    }
    ul {
        display: block;
        float: left;
        width: 100%;
        padding: 0;
        margin: 0;
    }
    li.pendencia {
        display: block;
        float: left;
        width: 100%;
        padding:  5px;
        background: #FFFFE0;
        border:  1px solid #FED22F;
        margin-bottom: 10px;
        -webkit-border-radius: 4px;
        -moz-border-radius: 4px;
        border-radius: 4px;
    }
    li.pendencia a {
        color: #0088cc;
    }
    li hr {
        border-top: 1px dotted #FED22F;
        border-bottom: none;
        margin: 5px 0;
        clear: both;
    }
    .label {
        font-size: 10px;
    }
    .data {
        float: right;
        clear: both;
    }
    .search-button {
        margin-bottom: 5px;
    }
    .search-form {
        margin-top: 0px;
    }
    .search-form .ui-multiselect-menu {
        left: 125px!important;
    }
    .ui-multiselect-checkboxes label {
        padding: 0 10px 10px 3px;
    }
    .search-form .select2-container .select2-choice div b, .search-form .chzn-container-multi .chzn-choices .search-choice {
        height: 16px;
    }
    .ui-multiselect .available, .ui-multiselect .selected {
        width: 225px!important;
    }
    .row.tiny div.ui-multiselect .selected, .row.tiny div.ui-multiselect .available {
        height: 130px !important;
    }
    .row.tiny div.ui-multiselect {
        height: 170px!important;
    }
    .row.tiny {
        height: 190px!important;
        margin-bottom: 3px;
    }
    #divLeftFrameSwitcher {
        display: none;
    }
    .qtip {
        max-width: 700px;
    }
    .ui-widget-header {
        height: 25px!important;
    }
CSS;

$cs->registerCss(Util::uid(), $css);

function getResponsavel($pendencia) {
    switch($pendencia->SOL_IDLOCAL) {
        case 13://aguardando analise
        return;
        break;
        case 14://pré analise
        return $pendencia->Atendente;
        break;
        case 2://analise
        return $pendencia->Analista;
        break;
        case 1://desenvolvimento
        return $pendencia->Desenvolvedor;
        break;
        case 16://pre testes
        return $pendencia->Testador;
        break;
        default:
        return;
        break;
    }
}
function getTempoParada($pendencia) {
    $atividade = SolicitacoesAtividades::model()->find('SAT_IDSOLICITACAO='.$pendencia->SOL_IDPENDENCIA.' AND SAT_IDLOCAL='.$pendencia->SOL_IDLOCAL.' ORDER BY SAT_DATACADASTRO DESC');
    if ($atividade) {
        return Util::getTempoDecorrido($atividade->SAT_DATACADASTRO);
    }
}

function notify($local) {
    if(!isset($local['max']) || $local['max'] == false) {
        return;
    }
    $text_notificacao = false;
    $percent = $local['count']/$local['max'];
    if($percent >= 0.7) {
        $text_notificacao = 'O mesmo possui '.$local['count'].' pendências de '.$local['max'].' suportadas.';
    }

    $notificado = false;
    $local_name = str_replace('Pendência', '', $local['title']);

    $uid = User::getid() . 'Notificado' . md5($local_name);

    if (Yii::app()->cache->get($uid)) {
        $notificado = Yii::app()->cache->get($uid);
    }

    $codigos = '';
    foreach($local['pendencias'] as $pendencia) {
        $codigos .= $pendencia->SOL_IDPENDENCIA;
    }
    Yii::app()->cache->set($uid, md5($codigos));

    if($notificado != Yii::app()->cache->get($uid) && $text_notificacao != false) {
        return 'notificacoes("Há alterações nas pendências no local '.$local_name.'!", {
            body: "'.$text_notificacao.'",
            icon: "'.FaHtml::getImgUrl('alerta.png').'"
        });';
    }
}
function getClassContador($counter, $max) {
    if(!$max) {
        return;
    }
    $percent = $counter/$max;
    if($percent <= 0.7) {
        return "green";
    } else if($percent <= 0.9) {
        return "yellow";
    } else {
        return "red animate_text";
    }
}

function getSituacao($local) {
    $return = $local['count'];
    if(isset($local['max']) && $local['max'] != false) {
        $return .="/" . $local['max'];
    }
    return '<small>('.$return.')</small>';
}

$script = <<<JAVASCRIPT
    $(document).ready(function() {
        setTimeout(function() {
            var url = window.location.href;
            if (url.indexOf('&automatico=1') == -1){
               url += '&automatico=1'
            }
            window.location.href = url;
        }, 60*1000);
    });
JAVASCRIPT;

$cs->registerScript(Util::uid(), $script);
?>
<script type="text/javascript">
    window.onload = (function(){
        notificacoes_request_permission();
    });
    notificacoes_check = function() {
        if (window.Notification) {
            return true;
        } else {
            console.log("Hum... navegador sem suporte a notificações!.");
            return false;
        }

    }
    notificacoes = function(title, opt) {
        if (notificacoes_check()) {
            if (window.Notification.permission != 'granted') {
                window.Notification.requestPermission(function(){
                    new Notification(title, opt);
                });
            } else {
                new Notification(title, opt);
            }
        }

    }

    notificacoes_request_permission = function(callback) {
        if (notificacoes_check()) {
            if (window.Notification.permission != 'granted') {
                window.Notification.requestPermission();
            }
        }
    }
    <?= $script; ?>
</script>