<?php

namespace app\modules\performance\models;

use Yii;
use app\components\Utils;

/**
 * This is the model class for table "sanepar_analise_risco".
 *
 * @property int $id
 * @property int $contexto_id
 * @property int $coleta_id
 * @property string $data_cadastro
 * @property string $email
 * @property string $nome_unidade
 * @property string $area_localizacao
 * @property string $protecao_perimetral
 * @property string $acesso_pessoa
 * @property string $acesso_veiculo
 * @property string $edificacao
 * @property string $controle_acesso_edificacao
 * @property string $monitoramento_imagem
 * @property string $monitoramento_alarme
 * @property string $acesso_nao_autorizado
 * @property string $ativo
 * @property string $consequencia
 * @property string $historico_problema
 *
 * @property Coleta $coleta
 * @property Contexto $contexto  144   75/74/74  41/41/41  27/29/29
 * 
 * f 9 12 9 10 10 12 11 1
 * a 9 6 7 6 6 1 6
 * d 2 2 4 4 4 7 3 3
 * 
 */
class SaneparAnaliseRisco extends \app\models\BaseModel {

    public $pai;
    public $avo;
    public $pvf1;
    public $pvf2;
    public $pvf3;
    public $pvf4;
    public $pontuacao;
    public $servico;
    public $parecerSearch;
    public $atributosVirtuais;

    const FAVORAVEL = 1;
    const ANALISE = 2;
    const DESFAVORAVEL = 3;
    const PONTUACAO_FAVORAVEL = 45;
    const PONTUACAO_DESFAVORAVEL = 30;
    const COR_FAVORAVEL = '#089f50';
    const COR_ANALISE = '#e8dd11';
    const COR_DESFAVORAVEL = '#DF5353';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return 'sanepar_analise_risco';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['contexto_id', 'coleta_id', 'parecer'], 'integer'],
            [['data_cadastro'], 'safe'],
            [['email', 'nome_unidade', 'area_localizacao', 'protecao_perimetral'], 'required'],
            [['email', 'nome_unidade', 'area_localizacao', 'protecao_perimetral', 'consequencia', 'municipio', 'regional'], 'string', 'max' => 255],
            [['acesso_pessoa', 'acesso_veiculo', 'edificacao', 'controle_acesso_edificacao', 'monitoramento_imagem', 'monitoramento_alarme', 'acesso_nao_autorizado', 'ativo', 'historico_problema'], 'string', 'max' => 255],
            [['coleta_id'], 'exist', 'skipOnError' => true, 'targetClass' => Coleta::className(), 'targetAttribute' => ['coleta_id' => 'id']],
            [['contexto_id'], 'exist', 'skipOnError' => true, 'targetClass' => Contexto::className(), 'targetAttribute' => ['contexto_id' => 'id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'contexto_id' => 'Contexto',
            'coleta_id' => 'Coleta',
            'data_cadastro' => 'Data de Cadastro',
            'email' => 'Email',
            'nome_unidade' => 'Nome da Unidade',
            'area_localizacao' => 'Ambiente em que a unidade auditada está inserida',
            'protecao_perimetral' => 'Barreiras perimetrais',
            'acesso_pessoa' => 'Qtde de acessos de pessoas a pé',
            'acesso_veiculo' => 'Qtde de acesso de veículos',
            'edificacao' => 'Qtde de edificações existentes na unidade auditada',
            'controle_acesso_edificacao' => 'Tipo de controle de acesso as edificações',
            'monitoramento_imagem' => 'Monitoramento de imagens',
            'monitoramento_alarme' => 'Monitoramento de alarmes',
            'acesso_nao_autorizado' => 'Há o risco de acidentes com lesões corporais ou morte na unidade?',
            'ativo' => 'Há ativos passíveis de serem furtados e comercializados por criminosos?',
            'consequencia' => 'Prospecção de período de interrupção dos serviços em caso de atos criminosos',
            'historico_problema' => 'Unidade auditada possui histórico de eventos críticos?',
            'parecer' => 'Parecer',
            'pai' => 'Regional',
            'avo' => 'Município',
            'pvf1' => 'PVF 1',
            'pvf2' => 'PVF 2',
            'pvf3' => 'PVF 3',
            'pvf4' => 'PVF 4',
            'pontuacao' => 'Valor Global',
            'servico' => 'Posto de Serviço',
            'parecerSearch' => 'Parecer',
            'municipio' => 'Município',
            'regional' => 'Regional',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getColeta() {
        return $this->hasOne(Coleta::className(), ['id' => 'coleta_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getContexto() {
        return $this->hasOne(Contexto::className(), ['id' => 'contexto_id']);
    }

    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    public static function getClient() {
        $client = new \Google_Client();
        $client->setApplicationName('SANEPAR');
        $client->setScopes([\Google_Service_Sheets::SPREADSHEETS_READONLY, \Google_Service_Drive::DRIVE_READONLY]);
        $client->setAuthConfig(Yii::getAlias('@diretoriobase') . '/credentials-google-api.json');
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');
        //\app\component\Utils::debug($client);
        // Load previously authorized token from a file, if it exists.
        // The file token.json stores the user's access and refresh tokens, and is
        // created automatically when the authorization flow completes for the first
        // time.
        $tokenPath = Yii::getAlias('@diretoriobase') . '/token-sanepar.json';
        if (file_exists($tokenPath)) {
            $accessToken = json_decode(file_get_contents($tokenPath), true);
            $client->setAccessToken($accessToken);
        }

        // If there is no previous token or it's expired.
        if ($client->isAccessTokenExpired()) {
            // Refresh the token if possible, else fetch a new one.
            if ($client->getRefreshToken()) {
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            } else {
                // Request authorization from the user.
                $authUrl = $client->createAuthUrl();

                $authCode = '4/rQHd4qd-WzfWgMVr0-guX5pQ8jOkCEFAp9OJqNNSDrxe0fbkthe8KXk';
                //$authCode = trim(fgets(STDIN));
                // Exchange authorization code for an access token.
                $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
                //Utils::debug($authUrl);
                $client->setAccessToken($accessToken);

                // Check to see if there was an error.
                if (array_key_exists('error', $accessToken)) {
                    throw new Exception(join(', ', $accessToken));
                }
            }
            // Save the token to a file.
            if (!file_exists(dirname($tokenPath))) {
                mkdir(dirname($tokenPath), 0700, true);
            }
            file_put_contents($tokenPath, json_encode($client->getAccessToken()));
        }
        //\app\component\Utils::debug($client);
        return $client;
    }

    public static function atualiza() {

        $client = self::getClient();
        $service = new \Google_Service_Sheets($client);
        //\app\component\Utils::debug($service);
        $spreadsheetId = '1019I99pqKCPYcoLkllxePBMiYQgSaOfnwU7HATJfWow';
        $range = 'Respostas ao formulário 1!A2:O';
        $response = $service->spreadsheets_values->get($spreadsheetId, $range);
        //
        $values = $response->getValues();

        $dados = self::find()->all();
        $existe = [];

        foreach ($dados as $dado0) {
            $dado = htmlentities($dado0->nome_unidade, ENT_COMPAT | ENT_SUBSTITUTE, 'utf-8');
            $dado = str_replace("&nbsp;", "", $dado);
            $dado = str_replace(" ", "", $dado);
            $dado = str_replace("\n", "", $dado);
            $dado = str_replace("\r", "", $dado);
            $dado = preg_replace('/\s/', '', $dado);

            $existe[$dado0->id] = $dado;
        }

        if (!empty($values)) {

            foreach ($values as $key => $value) {

                $dado1 = htmlentities($value[2], ENT_COMPAT | ENT_SUBSTITUTE, 'utf-8');
                $dado1 = str_replace("&nbsp;", "", $dado1);
                $dado1 = str_replace(" ", "", $dado1);
                $dado1 = str_replace("\n", "", $dado1);
                $dado1 = str_replace("\r", "", $dado1);
                $dado1 = preg_replace('/\s/', '', $dado1);

                //Utils::debug([$existe, $dado1]);
                if (!in_array($dado1, $existe)) {

                    $resposta = new self;
                } else {
                    $resposta = self::findOne(array_search($dado1, $existe));
                }

                if (!$resposta) {
                    throw new \yii\web\HttpException(500, $value[2] . ' não encontrado');
                }
                $resposta->nome_unidade = $value[2];
                $resposta->email = $value[1];
                $resposta->area_localizacao = $value[3];
                $resposta->protecao_perimetral = $value[4];
                $resposta->acesso_pessoa = $value[5];
                $resposta->acesso_veiculo = $value[6];
                $resposta->edificacao = $value[7];
                $resposta->controle_acesso_edificacao = $value[8];
                $resposta->monitoramento_imagem = $value[9] == 'Sim' ? 'Possui sistema de monitoramento de imagens' : 'Não possui sistema de monitoramento de imagens';
                $resposta->monitoramento_alarme = $value[10] == 'Sim' ? 'Possui sistema de monitoramento de alarmes' : 'Não possui sistema de monitoramento de alarmes';
                $resposta->acesso_nao_autorizado = $value[11];
                $resposta->ativo = $value[12];
                $resposta->consequencia = $value[13];
                $resposta->historico_problema = $value[14];
                $resposta->data_cadastro = date('Y-m-d H:i:s', strtotime($value[0]));

                if ($resposta->isNewRecord) {
                    \app\component\Comunica::mailgun('gledson@krinom.com.br', 'Nova resposta pra SANEPAR', 'Nova resposta para o projeto SANEPAR, por favor acesse o sistema e corriga o contexto dessa resposta', 'Nova resposta para o projeto SANEPAR, por favor acesse o sistema e corriga o contexto dessa resposta');
                }

                if (!$resposta->save()) {
                    throw new \yii\web\HttpException(500, "Erro ao salvar a resposta de " . $value[2] . ", motivo: " . json_encode($resposta->getErrors()));
                }
            }
        }

        return true;
    }

    public function getPaiNome() {

        if (!$this->contexto_id) {
            return 'N/D';
        }

        $contexto = Contexto::findOne($this->contexto_id);
        if (!$contexto) {
            return 'N/D';
        }

        $pai = $contexto->parents(1)->one();

        if (!$pai) {
            return 'N/D';
        }

        return $pai->name;
    }

    public function getAvoNome() {

        if (!$this->contexto_id) {
            return 'N/D';
        }

        $contexto = Contexto::findOne($this->contexto_id);
        if (!$contexto) {
            return 'N/D';
        }

        $pai = $contexto->parents(2)->one();

        if (!$pai) {
            return 'N/D';
        }

        return $pai->name;
    }

    public function getPvf1Valor() {

        if (!$this->coleta_id) {
            return 'N/D';
        }

        $pvf = ColetaEstrutura::find()
                ->where([
                    'coleta_id' => $this->coleta_id,
                    'nome' => '1. Localização da unidade auditada',
                    'status' => ColetaEstrutura::ATIVO
                ])
                ->orderBy('id DESC')
                ->one();

        if (!$pvf) {
            return 'N/D';
        }

        return $pvf->pontuacao;
    }

    public function getPvf2Valor() {

        if (!$this->coleta_id) {
            return 'N/D';
        }

        $pvf = ColetaEstrutura::find()
                ->where([
                    'coleta_id' => $this->coleta_id,
                    'nome' => '2. Características de segurança da unidade auditada',
                    'status' => ColetaEstrutura::ATIVO
                ])
                ->orderBy('id DESC')
                ->one();

        if (!$pvf) {
            return 'N/D';
        }

        return $pvf->pontuacao;
    }

    public function getPvf3Valor() {

        if (!$this->coleta_id) {
            return 'N/D';
        }

        $pvf = ColetaEstrutura::find()
                ->where([
                    'coleta_id' => $this->coleta_id,
                    'nome' => '3. Vulnerabilidades a eventos críticos',
                    'status' => ColetaEstrutura::ATIVO
                ])
                ->orderBy('id DESC')
                ->one();

        if (!$pvf) {
            return 'N/D';
        }

        return $pvf->pontuacao;
    }

    public function getPvf4Valor() {

        if (!$this->coleta_id) {
            return 'N/D';
        }

        $pvf = ColetaEstrutura::find()
                ->where([
                    'coleta_id' => $this->coleta_id,
                    'nome' => '4. Histórico de eventos críticos',
                    'status' => ColetaEstrutura::ATIVO
                ])
                ->orderBy('id DESC')
                ->one();

        if (!$pvf) {
            return 'N/D';
        }

        return $pvf->pontuacao;
    }

    public function getVgValor() {

        if (!$this->coleta_id) {
            return 'N/D';
        }

        return $this->coleta->valorGlobal;
    }

    public function getServicoNome() {

        if (!$this->contexto_id) {
            return 'N/D';
        }

        $contextoTemParametro = ContextoTemParametro::find()
                ->where([
                    'contexto_id' => $this->contexto_id,
                    'parametro' => 'Posto de vigilância'
                ])
                ->one();

        if (!$contextoTemParametro) {
            return 'N/D';
        }

        return $contextoTemParametro->informacao;
    }

    public function getParecerNome() {

        if ($this->parecer) {

            $texto = 'N/D';
            $cor = '';

            if ($this->parecer == self::FAVORAVEL) {
                $texto = 'Favorável';
                $cor = self::COR_FAVORAVEL;
            }

            if ($this->parecer == self::DESFAVORAVEL) {
                $texto = 'Desfavorável';
                $cor = self::COR_DESFAVORAVEL;
            }

            if ($this->parecer == self::ANALISE) {
                $texto = 'Análise';
                $cor = self::COR_ANALISE;
            }
        } elseif ($this->coleta_id) {

            $vg = $this->coleta->valorGlobal;

            $texto = 'Desfavorável';
            $cor = self::COR_DESFAVORAVEL;

            if ($vg > self::PONTUACAO_DESFAVORAVEL) {

                $texto = 'Análise';
                $cor = self::COR_ANALISE;
            }

            if ($vg > self::PONTUACAO_FAVORAVEL) {

                $texto = 'Favorável';
                $cor = self::COR_FAVORAVEL;
            }
        } else {

            $texto = 'N/D';
            $cor = '';
        }

        return [0 => $texto, 1 => $cor];
    }

    /*
     * CEON
     */

    public static function retornaDesempenhoGr($modelId) {

        $model = self::findOne($modelId);

        $parecerNome = $model->parecerNome;

        return '<div style="line-height:40px;vertical-align: inherit;text-align:center;color:white; font-weight: bold; font-size: 13px;background-color:' . $parecerNome[1] . '">' . $parecerNome[0] . '</div>';
    }

    public function getName() {
        if (!$this->contexto_id) {
            return 'N/D';
        }

        return $this->contexto->name;
    }

    public static function filtroContexto() {

        $contextosSanepar = \app\modules\performance\models\SaneparAnaliseRisco::find()
                ->select('contexto_id')
                ->column();

        $contextos = \yii\helpers\ArrayHelper::map(\app\modules\performance\models\Contexto::find()
                                ->where('rgt-lft=1')
                                ->andwhere(['in', 'id', $contextosSanepar])
                                ->all(), 'id', 'name');

        return $contextos;
    }

    public static function filtroServico() {

        $contextosSanepar = \app\modules\performance\models\SaneparAnaliseRisco::find()
                ->select('contexto_id')
                ->column();

        $servicos = \yii\helpers\ArrayHelper::map(\app\modules\performance\models\ContextoTemParametro::find()
                                ->where([
                                    'status' => \app\modules\performance\models\ContextoTemParametro::ATIVO,
                                    'parametro' => 'Posto de vigilância'
                                ])
                                ->andwhere([
                                    'in', 'contexto_id', $contextosSanepar,
                                ])
                                ->orderBy('informacao ASC')
                                ->groupBy('informacao')
                                ->all(), 'informacao', 'informacao');

        return $servicos;
    }

}
