<?php

namespace app\modules\performance\controllers;

use app\components\Utils;
use Yii;
use app\modules\performance\models\Anexo;
use app\modules\performance\models\AnexoSearch;
use app\modules\performance\models\Contexto;
use app\modules\performance\models\Timeline;
use app\modules\performance\models\TipoPermissao;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\HttpException;
use yii\filters\VerbFilter;
use mdm\admin\components\Helper;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;
use app\controllers\BaseController;
use app\models\GenericSearch;
use app\models\InventarioDados;
use app\models\InventarioResposta;
use app\models\InventarioScope;
use app\models\Scope;
use app\modules\performance\models\AnexoArvore;
use app\modules\performance\models\Coleta;
use app\modules\performance\models\ColetaEstrutura;
use app\modules\performance\models\ColetaIndicador;
use app\modules\performance\models\RecomendacaoSeguranca;
use Browser\Casper;
use yii\helpers\Url;

/**
 * AnexoController implements the CRUD actions for Anexo model.
 */
class AnexoController extends BaseController
{

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Anexo models.
     * @return mixed
     */
    public function actionIndex()
    {

        \app\models\Base::loga("Acessou a lista de Documentos", $_GET, $_POST, 3);

        $searchModel = new AnexoSearch();

        if (!$searchModel->status) {
            $searchModel->status = Anexo::ATIVO;
        }

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Anexo model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {

        return false;

        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Anexo model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {

        $model = new Anexo();

        $model->scenario = 'create';

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->all();

        $contextos = ArrayHelper::map($meusContextos, 'id', 'clienteNomeName');

        if ($model->load(Yii::$app->request->post())) {

            if (!array_key_exists($model->contexto_id, $contextos)) {
                throw new HttpException(500, "Erro: contexto não pertence a seus clientes");
            }

            $valid = true;

            $model->status = Anexo::ATIVO;

            $model->created_by = Yii::$app->user->identity->id;

            $model->created_at = date('Y-m-d H:i:s');

            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file) {
                $nome = md5(date('Ymd') . $model->nome);

                $model->arquivo = $nome . '.' . $model->file->extension;

                $model->tipo = $model->file->type;

                $model->tamanho = $model->file->size;

                if (!$model->upload()) {
                    $valid = false;
                    \Yii::$app->session->setFlash('error', "ECA1 - Erro ao fazer o upload do anexo");
                    //throw new HttpException(500, "ECC1 - Erro ao salvar a logo");
                }

                if ($valid) {
                    if (!$model->save()) {
                        $valid = false;
                        \Yii::$app->session->setFlash('error', "ECA2 - Erro ao cadastrar o anexo, motivo: " . json_encode($model->getErrors()));
                    }
                }

                if ($valid) {
                    //                    $timeLine = new Timeline();
                    //                    $timeLine->tipo = Timeline::TIPO_CONTEXTO;
                    //                    $timeLine->vinculo = $model->contexto_id;
                    //                    $timeLine->data_cadastro = date('Y-m-d H:i:s');
                    //                    $timeLine->icone = Timeline::ICONE_ANEXO_CADASTRADO;
                    //                    $timeLine->cadastrado_por = Yii::$app->user->identity->id;
                    //                    $timeLine->cadastrado_nome = Yii::$app->user->identity->nome;
                    //                    $timeLine->titulo = 'cadastrou um anexo';
                    //                    $timeLine->conteudo = 'Cadastrou o anexo ' . $model->id;
                    //                    $timeLine->status = Timeline::ATIVO;
                    //
                    //                    if (!$timeLine->save()) {
                    //                        $valid = false;
                    //                        throw new ErrorException("Erro ao salvar a timeline, entre em contato com o suporte");
                    //                    }
                }

                if ($valid) {
                    \app\models\Base::loga("Cadastrou Documento", $_GET, $_POST, 4);

                    return $this->redirect(['index']);
                }
            }
        }

        \app\models\Base::loga("Acessou a criação de Documentos", $_GET, $_POST, 4);

        return $this->render('create', [
            'model' => $model,
            'contextos' => $contextos,
            'breadcrumb' => null,
        ]);
    }

    /**
     * Updates an existing Anexo model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {

        $model = $this->findModel($id);

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->all();

        $contextos = ArrayHelper::map($meusContextos, 'id', 'clienteNomeName');

        if (!array_key_exists($model->contexto_id, $contextos)) {
            throw new HttpException(500, "Erro: contexto não pertence a seus clientes");
        }

        if (!$model->contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }


        if ($model->load(Yii::$app->request->post())) {

            if (!array_key_exists($model->contexto_id, $contextos)) {
                throw new HttpException(500, "Erro: contexto não pertence a seus clientes");
            }

            $valid = true;

            $model->created_by = Yii::$app->user->identity->id;

            $model->created_at = date('Y-m-d H:i:s');

            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file) {
                $nome = md5(date('Ymd') . $model->nome);

                $model->arquivo = $nome . '.' . $model->file->extension;

                $model->tipo = $model->file->type;

                $model->tamanho = $model->file->size;


                if (!$model->upload()) {
                    $valid = false;
                    \Yii::$app->session->setFlash('error', "ECA3 - Erro ao fazer o upload do anexo");
                    //throw new HttpException(500, "ECC1 - Erro ao salvar a logo");
                }
            }

            if ($valid) {
                if (!$model->save()) {
                    $valid = false;
                    \Yii::$app->session->setFlash('error', "ECA4 - Erro ao atualizar o anexo, motivo: " . json_encode($model->getErrors()));
                }
            }

            if ($valid) {

                //                $timeLine = new Timeline();
                //                $timeLine->tipo = Timeline::TIPO_CONTEXTO;
                //                $timeLine->vinculo = $model->contexto_id;
                //                $timeLine->data_cadastro = date('Y-m-d H:i:s');
                //                $timeLine->icone = Timeline::ICONE_ANEXO_ALTERADO;
                //                $timeLine->cadastrado_por = Yii::$app->user->identity->id;
                //                $timeLine->cadastrado_nome = Yii::$app->user->identity->nome;
                //                $timeLine->titulo = 'alterou um anexo';
                //                $timeLine->conteudo = 'Alterou o anexo ' . $model->id;
                //                $timeLine->status = Timeline::ATIVO;
                //
                //                if (!$timeLine->save()) {
                //                    $valid = false;
                //                    throw new ErrorException("Erro ao salvar a timeline, entre em contato com o suporte");
                //                }
            }

            if ($valid) {
                \app\models\Base::loga("Atualizou Documento", $_GET, $_POST, 5);

                return $this->redirect(['index']);
            }
        }

        \app\models\Base::loga("Acessou a atualização de Documento", $_GET, $_POST, 5);

        return $this->render('update', [
            'model' => $model,
            'contextos' => $contextos,
            'breadcrumb' => null,
        ]);
    }

    /**
     * Deletes an existing Anexo model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id, $origem = 'index')
    {

        \app\models\Base::loga("Excluiu Documento", $_GET, $_POST, 6);

        $model = $this->findModel($id);

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($model->contexto_id, $meusContextos)) {
            throw new HttpException(500, "Erro! Anexo não pertence a seus contextos");
        }

        if (!$model->contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }

        $model->status = Anexo::INATIVO;

        $valid = true;

        if (!$model->save()) {

            $valid = false;

            $msgErro = '<ul>';
            foreach ($model->getErrors() as $key => $value) {
                $msgErro .= '<li>' . $key . ': ' . $value . '</li>';
            }
            $msgErro .= '</ul>';
            throw new HttpException(500, "Erro ao excluir o Anexo, motivo: " . $msgErro);
        }

        if ($valid) {
            //            $timeLine = new Timeline();
            //            $timeLine->tipo = Timeline::TIPO_CONTEXTO;
            //            $timeLine->vinculo = $model->contexto_id;
            //            $timeLine->data_cadastro = date('Y-m-d H:i:s');
            //            $timeLine->icone = Timeline::ICONE_ANEXO_EXCLUIDO;
            //            $timeLine->cadastrado_por = Yii::$app->user->identity->id;
            //            $timeLine->cadastrado_nome = Yii::$app->user->identity->nome;
            //            $timeLine->titulo = 'excluiu um anexo';
            //            $timeLine->conteudo = 'Excluiu o anexo ' . $model->id;
            //            $timeLine->status = Timeline::ATIVO;
            //
            //            if (!$timeLine->save()) {
            //                $valid = false;
            //                throw new ErrorException("Erro ao salvar a timeline, entre em contato com o suporte");
            //            }
        }

        if ($valid) {

            if ($origem == 'view') {
                return $this->redirect(['index']);
            }

            return true;
        }
    }

    /**
     * Finds the Anexo model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Anexo the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Anexo::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionDownload($id)
    {

        \app\models\Base::loga("Acessou o download de Documento", $_GET, $_POST, 7);

        $anexo = Anexo::find()->where(['id' => $id, 'status' => Anexo::ATIVO])->one();

        if (!$anexo) {
            throw new \yii\web\HttpException(500, "Anexo não encontrado");
        }

        $meusContextos = GenericSearch::filterMyContextosVisualizacao()
            ->query
            ->select('contexto.id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($anexo->contexto_id, $meusContextos)) {
            throw new HttpException(500, "Erro: contexto não pertence a seus clientes");
        }

        if (!$anexo->contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }

        $path = Yii::getAlias('@webroot') . '/anexo';

        $file = $path . '/' . $anexo->arquivo;

        $ex = explode(".", $anexo->arquivo);

        $extensao = end($ex);

        if (file_exists($file)) {

            Yii::$app->response->sendFile($file, $anexo->nome . '.' . $extensao);
        } else {
            throw new \yii\web\HttpException(500, "Arquivo não encontrado");
        }
    }

    public function actionCreateAjax($id, $aplicacao_id, $layout = null)
    {

        $this->layout = '//empty';

        $model = new Anexo();

        $model->scenario = 'create';

        $model->contexto_id = $id;

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->all();

        $contextos = ArrayHelper::map($meusContextos, 'id', 'clienteNomeName');

        if (!array_key_exists($model->contexto_id, $contextos)) {
            throw new HttpException(500, "Erro: contexto não pertence a seus clientes");
        }

        if ($model->contexto->tipoLicenca != 'Licenciado') {
            throw new HttpException(500, "Cliente não Licenciado");
        }

        if (!$model->contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }


        if ($model->load(Yii::$app->request->post())) {

            if (!array_key_exists($model->contexto_id, $contextos)) {
                throw new HttpException(500, "Erro: contexto não pertence a seus clientes");
            }

            $valid = true;

            $model->created_by = Yii::$app->user->identity->id;

            $model->created_at = date('Y-m-d H:i:s');

            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file) {
                $nome = md5(date('Ymd') . $model->nome);

                $model->arquivo = $nome . '.' . $model->file->extension;

                $model->tipo = $model->file->type;

                if ($model->tipo == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                    $model->tipo = 'application/msword';
                }

                if ($model->tipo == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
                    $model->tipo = 'application/vnd.ms-excel';
                }

                $model->tamanho = $model->file->size;

                if (!$model->upload()) {
                    $valid = false;
                    \Yii::$app->session->setFlash('error', "ECA1 - Erro ao fazer o upload do anexo");
                    //throw new HttpException(500, "ECC1 - Erro ao salvar a logo");
                }
            }

            \app\models\Base::loga("Cadastrou Documento", $_GET, $_POST, 8);

            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Documento cadastrado com sucesso!');
                return $this->redirect(['/performance/contexto/view', 'id' => $model->contexto_id, 'aplicacao_id' => $aplicacao_id, "#" => 'contexto-analise-tecnica']);
            } else {
                Yii::$app->session->setFlash('danger', 'Erro ao cadastrar o documento! Motivo: ' . json_encode($model->getErrors()));
                return $this->redirect(['/performance/contexto/view', 'id' => $model->contexto_id, 'aplicacao_id' => $aplicacao_id, "#" => 'contexto-analise-tecnica']);
            }
        }

        if ($layout == 'contexto') {

            //   $this->layout = '//empty';

            $contexto = Contexto::findOne($id);

            if (!$contexto) {
                return '<div class="alert alert-danger">Erro! Cliente não encontrado!</div>';
            }

            $aplicacao = \app\modules\performance\models\Aplicacao::findOne($aplicacao_id);

            if (!$aplicacao) {
                return '<div class="alert alert-danger">Erro! Aplicação não encontrada!</div>';
            }

            $tarefasAtrasadas = \app\modules\performance\models\Tarefa::find()
                ->join('LEFT JOIN', 'pa_acao_proposta', 'pa_acao_proposta.id=pa_tarefa.pa_acao_proposta_id')
                ->join('LEFT JOIN', 'pa_plano_acao', 'pa_plano_acao.id=pa_acao_proposta.pa_plano_acao_id')
                ->where([
                    'pa_plano_acao.contexto_id' => $contexto->id,
                    'pa_acao_proposta.status' => \app\modules\performance\models\PlanoAcao::ATIVO,
                    'pa_plano_acao.status' => \app\modules\performance\models\AcaoProposta::ATIVO,
                ])
                ->andWhere(['<', 'pa_tarefa.termino_previsto', date('Y-m-d')])
                ->andWhere(['!=', 'pa_tarefa.situacao', \app\modules\performance\models\Tarefa::SITUACAO_ENCERRADA])
                ->orderBy('pa_plano_acao_id ASC, pa_tarefa.termino_previsto ASC, pa_tarefa.id ASC')
                ->all();

            $totalNotificacoes = count($tarefasAtrasadas);

            $permiteEditar = true;

            $ultimasAtualizacoes = \app\models\Log::find()
                ->where([
                    'contexto_id' => $contexto->id,
                ])
                ->andWhere(['!=', 'mensagem', 'Acessou a visualização de Contexto'])
                ->orderBy('id DESC')
                ->limit(10)
                ->all();

            \app\models\Base::loga("Acessou o criação de Documento via Contexto", $_GET, $_POST, 8);

            return $this->render('create_contexto', [
                'contexto' => $contexto,
                'aplicacao' => $aplicacao,
                'totalNotificacoes' => $totalNotificacoes,
                'permiteEditar' => $permiteEditar,
                'ultimasAtualizacoes' => $ultimasAtualizacoes,
                'model' => $model,
                'contextos' => $contextos,
                'breadcrumb' => ['label' => $model->contexto->name, 'url' => Url::previous()],
            ]);
        }

        \app\models\Base::loga("Acessou o criação de Documento", $_GET, $_POST, 8);

        return $this->render('create', [
            'model' => $model,
            'contextos' => $contextos,
            'breadcrumb' => ['label' => $model->contexto->name, 'url' => Url::previous()],
        ]);
    }

    public function actionUpdateAjax($id, $aplicacao_id, $layout = null)
    {

        $model = Anexo::find()
            ->where([
                'id' => $id,
                'status' => Anexo::ATIVO
            ])
            ->one();

        if (!$model) {
            throw new HttpException(500, "Erro! Documento não encontrado");
        }

        $meusContextos = GenericSearch::filterMyContextosGestor()
            ->query
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->all();

        $contextos = ArrayHelper::map($meusContextos, 'id', 'clienteNomeName');

        if (!array_key_exists($model->contexto_id, $contextos)) {
            throw new HttpException(500, "Erro: contexto não pertence a seus clientes");
        }

        if ($model->contexto->tipoLicenca != 'Licenciado') {
            throw new HttpException(500, "Cliente não Licenciado");
        }

        if (!$model->contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }


        if ($model->load(Yii::$app->request->post())) {

            if (!array_key_exists($model->contexto_id, $contextos)) {
                throw new HttpException(500, "Erro: contexto não pertence a seus clientes");
            }

            $valid = true;

            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file) {
                $nome = md5(date('Ymd') . $model->nome);

                $model->arquivo = $nome . '.' . $model->file->extension;

                $model->tipo = $model->file->type;

                $model->tamanho = $model->file->size;

                if (!$model->upload()) {
                    $valid = false;
                    \Yii::$app->session->setFlash('error', "ECA1 - Erro ao fazer o upload do anexo");
                    //throw new HttpException(500, "ECC1 - Erro ao salvar a logo");
                }
            }

            \app\models\Base::loga("Atualizou Documento", $_GET, $_POST, 9, $model->contexto_id);

            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Documento atualizado com sucesso!');
                return $this->redirect(['/performance/contexto/view', 'id' => $model->contexto_id, 'aplicacao_id' => $aplicacao_id, "#" => 'contexto-analise-tecnica']);
            } else {
                Yii::$app->session->setFlash('danger', 'Erro ao atualizar o Documento! Motivo: ' . json_encode($model->getErrors()));
                return $this->redirect(['/performance/contexto/view', 'id' => $model->contexto_id, 'aplicacao_id' => $aplicacao_id, "#" => 'contexto-analise-tecnica']);
            }
        }

        if ($layout == 'contexto') {

            $this->layout = '//empty';

            $contexto = Contexto::findOne($model->contexto_id);

            if (!$contexto) {
                return '<div class="alert alert-danger">Erro! Cliente não encontrado!</div>';
            }

            $aplicacao = \app\modules\performance\models\Aplicacao::findOne($aplicacao_id);

            if (!$aplicacao) {
                return '<div class="alert alert-danger">Erro! Aplicação não encontrada!</div>';
            }

            $tarefasAtrasadas = \app\modules\performance\models\Tarefa::find()
                ->join('LEFT JOIN', 'pa_acao_proposta', 'pa_acao_proposta.id=pa_tarefa.pa_acao_proposta_id')
                ->join('LEFT JOIN', 'pa_plano_acao', 'pa_plano_acao.id=pa_acao_proposta.pa_plano_acao_id')
                ->where([
                    'pa_plano_acao.contexto_id' => $contexto->id,
                    'pa_acao_proposta.status' => \app\modules\performance\models\PlanoAcao::ATIVO,
                    'pa_plano_acao.status' => \app\modules\performance\models\AcaoProposta::ATIVO,
                ])
                ->andWhere(['<', 'pa_tarefa.termino_previsto', date('Y-m-d')])
                ->andWhere(['!=', 'pa_tarefa.situacao', \app\modules\performance\models\Tarefa::SITUACAO_ENCERRADA])
                ->orderBy('pa_plano_acao_id ASC, pa_tarefa.termino_previsto ASC, pa_tarefa.id ASC')
                ->all();

            $totalNotificacoes = count($tarefasAtrasadas);

            $permiteEditar = true;

            $ultimasAtualizacoes = \app\models\Log::find()
                ->where([
                    'contexto_id' => $contexto->id,
                ])
                ->andWhere(['!=', 'mensagem', 'Acessou a visualização de Contexto'])
                ->orderBy('id DESC')
                ->limit(10)
                ->all();

            \app\models\Base::loga("Acessou o atualização de Documento via Contexto", $_GET, $_POST, 9, $model->contexto_id);

            return $this->render('update_contexto', [
                'contexto' => $contexto,
                'aplicacao' => $aplicacao,
                'totalNotificacoes' => $totalNotificacoes,
                'permiteEditar' => $permiteEditar,
                'ultimasAtualizacoes' => $ultimasAtualizacoes,
                'model' => $model,
                'contextos' => $contextos,
                'breadcrumb' => ['label' => $model->contexto->name, 'url' => Url::previous()],
            ]);
        }

        \app\models\Base::loga("Acessou o atualização de Documento", $_GET, $_POST, 9, $model->contexto_id);

        return $this->render('update', [
            'model' => $model,
            'contextos' => $contextos,
            'breadcrumb' => ['label' => $model->contexto->name, 'url' => Url::previous()],
        ]);
    }

    public function actionDeleteAjax($id, $aplicacao_id)
    {

        $model = Anexo::findOne($id);

        \app\models\Base::loga("Excluiu Documento", $_GET, $_POST, 10, $model->contexto_id);

        $model->status = Anexo::INATIVO;

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($model->contexto_id, $meusContextos)) {
            throw new HttpException(500, "Erro! Anexo não pertence a seus contextos");
        }

        if ($model->contexto->tipoLicenca != 'Licenciado') {
            throw new HttpException(500, "Cliente não Licenciado");
        }

        if (!$model->contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }


        if ($model->save()) {
            Yii::$app->session->setFlash('success', 'Documento excluído com sucesso! ');
            return $this->redirect(['/performance/contexto/view', 'id' => $model->contexto_id, 'aplicacao_id' => $aplicacao_id, "#" => 'contexto-analise-tecnica']);
        } else {
            Yii::$app->session->setFlash('danger', 'Erro ao excluir o documento! Motivo: ' . json_encode($model->getErrors()));
            return $this->redirect(['/performance/contexto/view', 'id' => $model->contexto_id, 'aplicacao_id' => $aplicacao_id, "#" => 'contexto-analise-tecnica']);
        }
    }

    public function actionDados($id)
    {

        return json_encode([
            ["id" => "ajson1", "parent" => "#", "text" => "Simple root node"],
            ["id" => "ajson2", "parent" => "#", "text" => "Root node 2"],
            ["id" => "ajson3", "parent" => "ajson2", "text" => "Child 1"],
            ["id" => "ajson4", "parent" => "ajson2", "text" => "Child 2"],
        ]);
    }

    public function actionArvoreAnexoAdiciona($id, $contexto_id, $aplicacao_id)
    {

        \app\models\Base::loga("Adicionou uma pasta", $_GET, $_POST);

        $pai = substr($id, 1);

        $modelPai = \app\modules\performance\models\AnexoArvore::findOne($pai);

        if (!$modelPai) {
            throw new HttpException(500, "Pasta não encontrada");
        }

        $model = new \app\modules\performance\models\AnexoArvore();

        $model->parent_id = $pai;

        $model->contexto_id = $modelPai->contexto_id;

        $meusContextos = GenericSearch::filterMyContextosGestor()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($modelPai->contexto_id, $meusContextos)) {
            throw new HttpException(500, "Erro! Pasta não pertence a seus contextos");
        }

        if ($model->contexto->tipoLicenca != 'Licenciado') {
            throw new HttpException(500, "Cliente não Licenciado");
        }

        if (!$model->contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                return $this->redirect(['/performance/contexto/view', 'id' => $modelPai->contexto_id, 'aplicacao_id' => $aplicacao_id, '#' => 'contexto-analise-tecnica']);
            }
        }

        return $this->renderAjax('_form_arvore_anexo', ['model' => $model]);
    }

    public function actionArvoreAnexoEdita($id, $contexto_id, $aplicacao_id)
    {

        \app\models\Base::loga("Editou uma pasta", $_GET, $_POST);

        $id = substr($id, 1);

        $model = \app\modules\performance\models\AnexoArvore::findOne($id);

        if (!$model) {
            throw new HttpException(500, "Pasta não encontrada");
        }

        $meusContextos = GenericSearch::filterMyContextosGestor()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($model->contexto_id, $meusContextos)) {
            throw new HttpException(500, "Erro! Pasta não pertence a seus contextos");
        }

        if ($model->contexto->tipoLicenca != 'Licenciado') {
            throw new HttpException(500, "Cliente não Licenciado");
        }

        if (!$model->contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                return $this->redirect(['/performance/contexto/view', 'id' => $model->contexto_id, 'aplicacao_id' => $aplicacao_id, '#' => 'contexto-analise-tecnica']);
            }
        }

        return $this->renderAjax('_form_arvore_anexo', ['model' => $model]);
    }

    public function actionArvoreAnexoMove($origem, $destino, $posicao)
    {

        \app\models\Base::loga("Moveu uma pasta", $_GET, $_POST);

        $this->layout = '//empty';

        $itemDestino = substr($destino, 1);

        $tipoDestino = substr($destino, 0, 1);

        if ($tipoDestino == 'A') {
            return 'Destino não é uma pasta';
        }

        $modelDestino = \app\modules\performance\models\AnexoArvore::findOne($itemDestino);

        if (!$modelDestino) {
            return "Item não encontrado";
        }

        $itemOrigem = substr($origem, 1);

        $tipoOrigem = substr($origem, 0, 1);

        if ($tipoOrigem == 'A') {
            $modelOrigem = \app\modules\performance\models\Anexo::findOne($itemOrigem);

            if (!$modelOrigem) {
                return "Anexo não encontrado";
            }

            $modelOrigem->anexo_arvore_id = $itemDestino;
        } else {
            $modelOrigem = \app\modules\performance\models\AnexoArvore::findOne($itemOrigem);

            if (!$modelOrigem) {
                return "Item não encontrado";
            }

            $modelOrigem->parent_id = $itemDestino;
        }

        $meusContextos = GenericSearch::filterMyContextosGestor()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($modelDestino->contexto_id, $meusContextos)) {
            throw new HttpException(500, "Erro! Pasta não pertence a seus contextos");
        }

        if (!in_array($modelOrigem->contexto_id, $meusContextos)) {
            throw new HttpException(500, "Erro! Pasta não pertence a seus contextos");
        }

        if (!$modelOrigem->save()) {
            return "Erro ao mover o item, motivo: " . \GuzzleHttp\json_encode($modelOrigem->getErrors());
        }

        //posição nova

        //irmaos        
        $irmaos = AnexoArvore::find()
            ->select('id')
            ->where([
                'parent_id' => $modelOrigem->parent_id,
                'contexto_id' => $modelOrigem->contexto_id,
            ])
            ->andWhere(['!=', 'id', $modelOrigem->id])
            ->column();

        $novaOrdem = [];

        $i = 0;
        foreach ($irmaos as $k => $irmao) {

            if ($i == $posicao) {
                $novaOrdem[$i] = $modelOrigem->id;
                $j = $i + 1;
                $i = $j;
                $novaOrdem[$j] = $irmao;
            } else {
                $novaOrdem[$i] = $irmao;
            }
            $i++;
        }

        foreach ($novaOrdem as $k => $v) {
            $aA = AnexoArvore::findOne($v);

            if (!$aA) {
                throw new HttpException(500, "Erro! Irmão " . $v . " não encontrado");
            }

            $aA->position = $k;

            if (!$aA->save()) {
                return "Erro ao salvar " . $aA . " motivo: " . json_encode($aA->getErrors());
            }
        }

        return true;
    }

    public function actionArvoreAnexoExclui($id, $contexto_id, $aplicacao_id)
    {

        \app\models\Base::loga("Excluiu uma pasta", $_GET, $_POST);

        $id = substr($id, 1);

        $model = \app\modules\performance\models\AnexoArvore::findOne($id);

        if (!$model) {
            throw new HttpException(500, "Pasta não encontrada");
        }

        $meusContextos = GenericSearch::filterMyContextosGestor()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($model->contexto_id, $meusContextos)) {
            throw new HttpException(500, "Erro! Pasta não pertence a seus contextos");
        }

        if ($model->contexto->tipoLicenca != 'Licenciado') {
            throw new HttpException(500, "Cliente não Licenciado");
        }

        if (!$model->contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }

        $totalAnexoArvore = \app\modules\performance\models\AnexoArvore::find()
            ->where([
                'contexto_id' => $model->contexto_id
            ])
            ->count();

        if ($totalAnexoArvore == 1) {
            return "<div style='padding:20px'>Não é possível excluir todas as pastas</div>";
        }

        if ($model->parent_id == 0) {
            return "<div style='padding:20px'>Não é possível excluir a pasta inicial</div>";
        }

        $sql = "SELECT  id,
        NAME,
        parent_id 
        FROM    (SELECT * FROM anexo_arvore
        ORDER BY parent_id, id) sorted,
        (SELECT @pv := '$model->id') initialisation
            WHERE FIND_IN_SET(parent_id, @pv)
            AND LENGTH(@pv := CONCAT(@pv, ',', id))";

        $anexoArvoresFilhos = Yii::$app->db
            ->createCommand($sql)
            ->bindValue(':pai', $model->id)
            ->queryAll();

        $excluir = [];
        $excluir[] = $model->id;

        foreach ($anexoArvoresFilhos as $k => $anexoArvoresFilho) {
            $excluir[] = $anexoArvoresFilho['id'];
        }

        Anexo::updateAll(['anexo_arvore_id' => null], ['in', 'anexo_arvore_id', $excluir]);

        if (\app\modules\performance\models\AnexoArvore::deleteAll(['id' => $excluir])) {
            return 1;
        }
        return "Erro ao excluir a pasta, motivo: " . json_encode($model->getErrors());
    }

    public function actionArvoreAnexoBuscaEstrutura($contexto, $inventario_dados = null)
    {

        $meusContextos = GenericSearch::filterMyContextosGestor()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($contexto, $meusContextos)) {
            throw new HttpException(500, "Erro! Pasta não pertence a seus contextos");
        }

        //$estrutura = \app\modules\performance\models\AnexoArvore::estrutura($contexto, null, $inventario_dados);
        $estrutura = \app\modules\performance\models\AnexoArvore::estruturaSemArquivos($contexto, null, $inventario_dados);

        return $estrutura;
    }

    public function actionCreateRelatorio($contexto_id, $aplicacao_id)
    {

        \app\models\Base::loga("Acessou o relatório de auditoria", $_GET, $_POST, 35);

        $this->layout = '//empty';

        $contexto = \app\modules\performance\models\Contexto::find()
            ->where([
                'id' => $contexto_id,
                'active' => \app\modules\performance\models\Contexto::ATIVO,
            ])
            ->one();

        if (!$contexto) {
            return '<div class="alert alert-danger">Erro! Cliente não encontrado!</div>';
        }

        if ($contexto->tipoLicenca != 'Licenciado') {
            return '<br /><div class="alert alert-danger">Erro! Cliente não Licenciado!</div>';
        }

        if (!$contexto->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }

        $meusContextos = \app\models\GenericSearch::filterMyContextosGestor()
            ->query
            ->select('contexto.id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'contexto.id', $contexto->id])
            ->column();

        if (!$meusContextos) {
            throw new HttpException(500, "Erro! Cliente não permitido para seu usuário");
        }

        $path = Yii::getAlias('@webroot') . '/uploads';

        $nomeClienteExplode = explode(" ", $contexto->cliente->nome);
        $nomeClientePadrao = implode("", $nomeClienteExplode);
        $nomeCliente = implode("-", $nomeClienteExplode);

        $template = \Yii::$app->basePath . '/web/uploads/LaudoSegurancaPadrao' . $nomeClientePadrao . '.docx';
        $arquivo = \Yii::$app->basePath . '/web/uploads/Laudo-de-Segurança-Patrimonial-' . $nomeCliente . '.docx';

        $BodyFontStyle = array('name' => 'Times New Roman', 'bold' => false, 'size' => 11,);
        $BodyFontStyleCenter = array('name' => 'Times New Roman', 'bold' => false, 'size' => 11, 'text-align' => 'center', 'align' => 'center');
        $fontStyle9ITNR = array('name' => 'Times New Roman', 'bold' => false, 'italic' => true, 'size' => 9, 'text-align' => 'left', 'align' => 'left');
        $fontStyle9TNR = array('name' => 'Times New Roman', 'bold' => false, 'italic' => false, 'size' => 9, 'text-align' => 'left', 'align' => 'left');
        $fontStyle11ITNR = array('name' => 'Times New Roman', 'bold' => false, 'italic' => true, 'size' => 11, 'text-align' => 'left', 'align' => 'left');
        $fontStyle11TNR = array('name' => 'Times New Roman', 'bold' => false, 'italic' => false, 'size' => 11, 'text-align' => 'left', 'align' => 'left');
        $fontStyle11TNRB = array('name' => 'Times New Roman', 'bold' => true, 'italic' => false, 'size' => 11, 'text-align' => 'left', 'align' => 'left');
        $fontStyle11TNC = array('name' => 'Times New Roman', 'bold' => false, 'italic' => false, 'size' => 11, 'text-align' => 'center', 'align' => 'center');
        $fontStyle10TNC = array('name' => 'Times New Roman', 'bold' => false, 'italic' => false, 'size' => 10, 'text-align' => 'center', 'align' => 'center');
        $fontStyle10TNL = array('name' => 'Times New Roman', 'bold' => false, 'italic' => false, 'size' => 10, 'text-align' => 'left', 'align' => 'left');
        $fontStyle10TBL = array('name' => 'Times New Roman', 'bold' => true, 'italic' => false, 'size' => 10, 'text-align' => 'left', 'align' => 'left');

        $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template);

        $meses = [
            '01' => 'janeiro',
            '02' => 'fevereiro',
            '03' => 'março',
            '04' => 'abril',
            '05' => 'maio',
            '06' => 'junho',
            '07' => 'julho',
            '08' => 'agosto',
            '09' => 'setembro',
            '10' => 'outubro',
            '11' => 'novembro',
            '12' => 'dezembro',
        ];

        $mes = date('m');
        if (isset($meses[$mes])) {
            $mesExtenso = $meses[$mes];
        } else {
            $mesExtenso = 'N/D';
        }
        $data_extenso = date('d') . ' de ' . $mesExtenso . ' de ' . date('Y');


        $templateProcessor->setValue('contexto_nome', $contexto->name);

        $templateProcessor->setValue('data_extenso', $data_extenso);

        $templateProcessor->setValue('cliente_nome', $contexto->cliente->nome);

        $templateProcessor->setValue('consultor_nome', $contexto->advogadoNomeSimples);

        $token = md5('gledson' . date('dmY'));

        //  putenv("PHANTOMJS_EXECUTABLE=C://phantomjs/bin/phantomjs");

        /*
        if (file_exists('C://xampp/htdocs/psec/web/img/docs/figura_perfil_desempenho_' . $contexto->id . '.png')) {
            unlink('C://xampp/htdocs/psec/web/img/docs/figura_perfil_desempenho_' . $contexto->id . '.png');
        }
        $casper = new Casper('/var/www/html/psec/node_modules/casperjs/bin/', '/var/www/html/psec/tmp');
        $casper->setViewPort(1024, 768);
        $url = Url::home(true);
        $casper->start($url . 'site/grafico-perfil-desempenho-token?token=' . $token . '&contexto_id=' . $contexto->id . '&aplicacao_id=' . $aplicacao_id);
        $casper->wait(2000);
        $casper->captureSelector('#grafico1', '/var/www/html/psec/web/img/docs/figura_perfil_desempenho_' . $contexto->id . '.png');
        $casper->run();

        $templateProcessor->setImageValue('grafico_perfil', [
            'path' => '/var/www/html/psec/web/img/docs/figura_perfil_desempenho_' . $contexto->id . '.png',
            'width' => 600,
            'height' => 600,
        ]);
        */

        $tableContextoAnalisado = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 1,
            'borderColor' => 'black',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
        ]);
        $tableContextoAnalisado->addRow();
        $tableContextoAnalisado->addCell(2000, ['noWrap' => false, 'gridSpan' => 3,  'borderBottomColor' => '#FFFFFF'])->addText('Razão social', $fontStyle9ITNR);
        $tableContextoAnalisado->addRow();
        $tableContextoAnalisado->addCell(2000, ['noWrap' => false, 'gridSpan' => 3, 'borderTopColor' => '#FFFFFF',])->addText($contexto->name, $fontStyle11TNR);
        $tableContextoAnalisado->addRow();
        $tableContextoAnalisado->addCell(1000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('CEP', $fontStyle9ITNR);
        $tableContextoAnalisado->addCell(3500, ['noWrap' => false])->addText('Endereço', $fontStyle9ITNR);
        $tableContextoAnalisado->addCell(1500, ['noWrap' => false])->addText('CNPJ', $fontStyle9ITNR);
        $tableContextoAnalisado->addRow();
        $tableContextoAnalisado->addCell(1000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF'])->addText($contexto->cep, $fontStyle11ITNR);
        $tableContextoAnalisado->addCell(3500, ['noWrap' => false])->addText($contexto->endereco, $fontStyle11ITNR);
        $tableContextoAnalisado->addCell(1500, ['noWrap' => false])->addText($contexto->cpf_cnpj, $fontStyle11ITNR);

        $templateProcessor->setComplexBlock('contexto_analisado', $tableContextoAnalisado);

        $inicioDoProjetoInformacaoGlobal = '-';
        $dataApresentacaoResultadosInformacaoGlobal = '-';
        $naturezaInformacaoGlobal = '-';
        $estruturacaoInformacaoGlobal = '-';

        $inventarioScopeInformacaoGlobal = InventarioScope::find()
            ->joinWith(['scope', 'inventarioDados'])
            ->where([
                'inventario_dados.id' => 38,
                'inventario_dados.status' => InventarioDados::ATIVO,
                'scope.contexto_id' => $contexto->id,
                'scope.status' => Scope::ATIVO,
            ])
            ->one();

        if ($inventarioScopeInformacaoGlobal) {
            $inventarioRespostaInformacaoGlobals = InventarioResposta::find()
                ->where(['inventario_scope_id' => $inventarioScopeInformacaoGlobal->id])
                ->all();

            foreach ($inventarioRespostaInformacaoGlobals as $inventarioRespostaInformacaoGlobal) {
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 727) {
                    $inicioDoProjetoInformacaoGlobal = $inventarioRespostaInformacaoGlobal->resposta;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 728) {
                    $dataApresentacaoResultadosInformacaoGlobal = $inventarioRespostaInformacaoGlobal->resposta;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 729) {
                    $naturezaInformacaoGlobal = '';
                    foreach (json_decode($inventarioRespostaInformacaoGlobal->alternativas_checkbox) as $check) {
                        $naturezaInformacaoGlobal .= "- " . $check . '<w:br/>';
                    }
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 730) {
                    $estruturacaoInformacaoGlobal = '';
                    foreach (json_decode($inventarioRespostaInformacaoGlobal->alternativas_checkbox) as $check) {
                        $estruturacaoInformacaoGlobal .= "- " . $check . '<w:br/>';
                    }
                }
            }
        }

        $tableInformacoesGlobais = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 1,
            'borderColor' => 'black',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
        ]);
        $tableInformacoesGlobais->addRow();
        $tableInformacoesGlobais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Início do projeto', $fontStyle9ITNR);
        $tableInformacoesGlobais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Data da apresentação dos resultados', $fontStyle9ITNR);
        $tableInformacoesGlobais->addRow();
        $tableInformacoesGlobais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inicioDoProjetoInformacaoGlobal, $fontStyle11TNR);
        $tableInformacoesGlobais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($dataApresentacaoResultadosInformacaoGlobal, $fontStyle11TNR);
        $tableInformacoesGlobais->addRow();
        $tableInformacoesGlobais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Natureza', $fontStyle9ITNR);
        $tableInformacoesGlobais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Estruturação', $fontStyle9ITNR);
        $tableInformacoesGlobais->addRow();
        $tableInformacoesGlobais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($naturezaInformacaoGlobal, $fontStyle11TNR);
        $tableInformacoesGlobais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($estruturacaoInformacaoGlobal, $fontStyle11TNR);

        $templateProcessor->setComplexBlock('informacoes_globais', $tableInformacoesGlobais);

        $edificacoesAuditadasDimensionamentoEstrutural = '-';
        $pavimentosDimensionamentoEstrutural = '-';
        $unidadesDeConvivenciaDimensionamentoEstrutural = '-';
        $acessosDePessoasAPeDimensionamentoEstrutural = '-';
        $acessosDeVeiculosDimensionamentoEstrutural = '-';
        $ambientesControladosDimensionamentoEstrutural = '-';

        if ($inventarioScopeInformacaoGlobal) {
            $inventarioRespostaInformacaoGlobals = InventarioResposta::find()
                ->where(['inventario_scope_id' => $inventarioScopeInformacaoGlobal->id])
                ->all();

            foreach ($inventarioRespostaInformacaoGlobals as $inventarioRespostaInformacaoGlobal) {
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 733) {
                    $edificacoesAuditadasDimensionamentoEstrutural = $inventarioRespostaInformacaoGlobal->resposta;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 734) {
                    $pavimentosDimensionamentoEstrutural = $inventarioRespostaInformacaoGlobal->resposta;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 735) {
                    $unidadesDeConvivenciaDimensionamentoEstrutural = $inventarioRespostaInformacaoGlobal->resposta;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 736) {
                    $acessosDePessoasAPeDimensionamentoEstrutural = $inventarioRespostaInformacaoGlobal->resposta;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 737) {
                    $acessosDeVeiculosDimensionamentoEstrutural = $inventarioRespostaInformacaoGlobal->resposta;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 739) {
                    $ambientesControladosDimensionamentoEstrutural = $inventarioRespostaInformacaoGlobal->resposta;
                }
            }
        }

        $tableDimensionamentoEstrutural = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 1,
            'borderColor' => 'black',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
        ]);
        $tableDimensionamentoEstrutural->addRow();
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Edificações auditadas', $fontStyle9ITNR);
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Pavimentos', $fontStyle9ITNR);
        $tableDimensionamentoEstrutural->addRow();
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($edificacoesAuditadasDimensionamentoEstrutural, $fontStyle11TNR);
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($pavimentosDimensionamentoEstrutural, $fontStyle11TNR);
        $tableDimensionamentoEstrutural->addRow();
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Unidades de convivência', $fontStyle9ITNR);
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Acessos de pessoas a pé', $fontStyle9ITNR);
        $tableDimensionamentoEstrutural->addRow();
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($unidadesDeConvivenciaDimensionamentoEstrutural, $fontStyle11TNR);
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($acessosDePessoasAPeDimensionamentoEstrutural, $fontStyle11TNR);
        $tableDimensionamentoEstrutural->addRow();
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Acessos de veículos', $fontStyle9ITNR);
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Ambientes controlados', $fontStyle9ITNR);
        $tableDimensionamentoEstrutural->addRow();
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($acessosDeVeiculosDimensionamentoEstrutural, $fontStyle11TNR);
        $tableDimensionamentoEstrutural->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($ambientesControladosDimensionamentoEstrutural, $fontStyle11TNR);

        $templateProcessor->setComplexBlock('dimensionamento_estrutural', $tableDimensionamentoEstrutural);

        $responsavelPatrimonialDimensionamentoRecursosHumanos = '-';
        $vigilantesDimensionamentoRecursosHumanos = '-';
        $facilitiesDimensionamentoRecursosHumanos = '-';

        if ($inventarioScopeInformacaoGlobal) {
            $inventarioRespostaInformacaoGlobals = InventarioResposta::find()
                ->where(['inventario_scope_id' => $inventarioScopeInformacaoGlobal->id])
                ->all();

            foreach ($inventarioRespostaInformacaoGlobals as $inventarioRespostaInformacaoGlobal) {
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 740) {
                    $responsavelPatrimonialDimensionamentoRecursosHumanos = $inventarioRespostaInformacaoGlobal->alternativas_radiobox;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 741) {
                    $vigilantesDimensionamentoRecursosHumanos = $inventarioRespostaInformacaoGlobal->alternativas_radiobox;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 742) {
                    $facilitiesDimensionamentoRecursosHumanos = $inventarioRespostaInformacaoGlobal->alternativas_radiobox;
                }
            }
        }

        $tableDimensionamentoRecursosHumanos = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 1,
            'borderColor' => 'black',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
        ]);

        $tableDimensionamentoRecursosHumanos->addRow();
        $tableDimensionamentoRecursosHumanos->addCell(2000, ['noWrap' => false, 'gridSpan' => 2,  'borderBottomColor' => '#FFFFFF'])->addText('Responsável patrimonial', $fontStyle9ITNR);
        $tableDimensionamentoRecursosHumanos->addRow();
        $tableDimensionamentoRecursosHumanos->addCell(2000, ['noWrap' => false, 'gridSpan' => 2, 'borderTopColor' => '#FFFFFF',])->addText($responsavelPatrimonialDimensionamentoRecursosHumanos, $fontStyle11TNR);
        $tableDimensionamentoRecursosHumanos->addRow();
        $tableDimensionamentoRecursosHumanos->addCell(2000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Segurança Humana (vigilantes)', $fontStyle9ITNR);
        $tableDimensionamentoRecursosHumanos->addCell(2000, ['noWrap' => false])->addText('Facilities', $fontStyle9ITNR);
        $tableDimensionamentoRecursosHumanos->addRow();
        $tableDimensionamentoRecursosHumanos->addCell(2000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF'])->addText($vigilantesDimensionamentoRecursosHumanos, $fontStyle11TNR);
        $tableDimensionamentoRecursosHumanos->addCell(2000, ['noWrap' => false])->addText($facilitiesDimensionamentoRecursosHumanos, $fontStyle11TNR);

        $templateProcessor->setComplexBlock('dimensionamento_recursos_humanos', $tableDimensionamentoRecursosHumanos);

        $cftvDimensionamentoSegurancaEletronica = '-';
        $controleAcessoDimensionamentoSegurancaEletronica = '-';
        $alarmeIntrusaoDimensionamentoSegurancaEletronica = '-';
        $preventivoIncendioDimensionamentoSegurancaEletronica = '-';

        if ($inventarioScopeInformacaoGlobal) {
            $inventarioRespostaInformacaoGlobals = InventarioResposta::find()
                ->where(['inventario_scope_id' => $inventarioScopeInformacaoGlobal->id])
                ->all();

            foreach ($inventarioRespostaInformacaoGlobals as $inventarioRespostaInformacaoGlobal) {
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 743) {
                    $cftvDimensionamentoSegurancaEletronica = $inventarioRespostaInformacaoGlobal->alternativas_radiobox;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 744) {
                    $controleAcessoDimensionamentoSegurancaEletronica = $inventarioRespostaInformacaoGlobal->alternativas_radiobox;
                }
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 745) {
                    $alarmeIntrusaoDimensionamentoSegurancaEletronica = $inventarioRespostaInformacaoGlobal->alternativas_radiobox;
                }
            }
        }

        $tableDimensionamentoSegurancaEletronica = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 1,
            'borderColor' => 'black',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
        ]);
        $tableDimensionamentoSegurancaEletronica->addRow();
        $tableDimensionamentoSegurancaEletronica->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Circuito Fechado de Televisão', $fontStyle9ITNR);
        $tableDimensionamentoSegurancaEletronica->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Sistema de Controle de Acessos', $fontStyle9ITNR);
        $tableDimensionamentoSegurancaEletronica->addRow();
        $tableDimensionamentoSegurancaEletronica->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($cftvDimensionamentoSegurancaEletronica, $fontStyle11TNR);
        $tableDimensionamentoSegurancaEletronica->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($controleAcessoDimensionamentoSegurancaEletronica, $fontStyle11TNR);
        $tableDimensionamentoSegurancaEletronica->addRow();
        $tableDimensionamentoSegurancaEletronica->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Sistema de Alarmes de Intrusão', $fontStyle9ITNR);
        $tableDimensionamentoSegurancaEletronica->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Sistema Preventivo de Incêndio', $fontStyle9ITNR);
        $tableDimensionamentoSegurancaEletronica->addRow();
        $tableDimensionamentoSegurancaEletronica->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($alarmeIntrusaoDimensionamentoSegurancaEletronica, $fontStyle11TNR);
        $tableDimensionamentoSegurancaEletronica->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($preventivoIncendioDimensionamentoSegurancaEletronica, $fontStyle11TNR);

        $templateProcessor->setComplexBlock('dimensionamento_seguranca_eletronica', $tableDimensionamentoSegurancaEletronica);

        $relacaoPrestadoresServico = '-';

        if ($inventarioScopeInformacaoGlobal) {
            $inventarioRespostaInformacaoGlobals = InventarioResposta::find()
                ->where(['inventario_scope_id' => $inventarioScopeInformacaoGlobal->id])
                ->all();
            $relacaoPrestadoresServico = new \PhpOffice\PhpWord\Element\TextRun();

            foreach ($inventarioRespostaInformacaoGlobals as $inventarioRespostaInformacaoGlobal) {
                if ($inventarioRespostaInformacaoGlobal->inventarioPergunta->id == 746) {
                    $relacaoPrestadoresServico->addText('- ' . $inventarioRespostaInformacaoGlobal->resposta);
                    $relacaoPrestadoresServico->addTextBreak(1);
                }
            }
            $templateProcessor->setComplexValue('relacao_prestadores_servico', $relacaoPrestadoresServico);
        } else {

            $templateProcessor->setValue('relacao_prestadores_servico', $relacaoPrestadoresServico);
        }


        $templateProcessor->setValue('consultor_nome', $contexto->advogadoNomeSimples);

        $templateProcessor->setValue('consultor_email', $contexto->advogadoEmailSimples);

        $scopeRoot = Scope::find()
            ->where([
                'contexto_id' => $contexto->id,
                'status' => Scope::ATIVO,
            ])
            ->andWhere(['is', 'parent_id', new \yii\db\Expression('null')])
            ->one();

        $scopeAspectoEstrutural = Scope::find()
            ->where([
                'parent_id' => $scopeRoot->id ?? '',
                'name' => 'Aspectos Estruturais',
                'status' => Scope::ATIVO,
            ])
            ->one();

        $scopesAspectosEstruturais = Scope::getRecursiveScopesIds($scopeAspectoEstrutural->id);

        $inventarioScopesEstruturais = InventarioScope::find()
            ->joinWith('scope')
            ->where([
                'scope.contexto_id' => $contexto->id,
                'scope.status' => Scope::ATIVO,
                'inventario_scope.status' => InventarioScope::ATIVO,
            ])
            ->andWhere(['in', 'scope.id', $scopesAspectosEstruturais])
            ->all();

        $tableInventarioScopesAspectosEstruturais = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 1,
            'borderColor' => 'black',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
        ]);
        $tableInventarioScopesAspectosEstruturais->addRow();
        $tableInventarioScopesAspectosEstruturais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Área de atenção', $fontStyle9ITNR);
        $tableInventarioScopesAspectosEstruturais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Subárea de atenção', $fontStyle9ITNR);
        $tableInventarioScopesAspectosEstruturais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Processo auditado', $fontStyle9ITNR);
        $tableInventarioScopesAspectosEstruturais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Criticidade', $fontStyle9ITNR);

        foreach ($inventarioScopesEstruturais as $inventarioScopeEstrutural) {

            $inventarioScopeCriticidade = '';

            if ($inventarioScopeEstrutural->inventarioDados->tipo == \app\models\InventarioDados::TIPO_ROPA) {
                $inventarioScopeCriticidade = $inventarioScopeEstrutural->risco;
            }
            if ($inventarioScopeEstrutural->inventarioDados->tipo == \app\models\InventarioDados::TIPO_GENERICO) {
                $inventarioScopeCriticidade = $inventarioScopeEstrutural->risco;
            }
            if ($inventarioScopeEstrutural->inventarioDados->tipo == \app\models\InventarioDados::TIPO_FORNECEDOR) {
                $inventarioScopeCriticidade = $inventarioScopeEstrutural->risco_fornecedor;
            }
            if ($inventarioScopeEstrutural->inventarioDados->tipo == \app\models\InventarioDados::TIPO_SEGURANCA) {
                $inventarioScopeCriticidade = $inventarioScopeEstrutural->risco_seguranca;
            }
            $tableInventarioScopesAspectosEstruturais->addRow();
            $tableInventarioScopesAspectosEstruturais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeEstrutural->avo, $fontStyle11TNR);
            $tableInventarioScopesAspectosEstruturais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeEstrutural->scope->name, $fontStyle11TNR);
            $tableInventarioScopesAspectosEstruturais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeEstrutural->nome, $fontStyle11TNR);
            $tableInventarioScopesAspectosEstruturais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeCriticidade, $fontStyle11TNR);
        }

        $templateProcessor->setComplexBlock('criticidade_aspectos_estruturais', $tableInventarioScopesAspectosEstruturais);

        $scopeAspectoOperacional = Scope::find()
            ->where([
                'parent_id' => $scopeRoot->id ?? '',
                'name' => 'Aspectos Operacionais',
                'status' => Scope::ATIVO,
            ])
            ->one();

        $scopesAspectosOperacionais = Scope::getRecursiveScopesIds($scopeAspectoOperacional->id);

        $inventarioScopesOperacionais = InventarioScope::find()
            ->joinWith('scope')
            ->where([
                'scope.contexto_id' => $contexto->id,
                'scope.status' => Scope::ATIVO,
                'inventario_scope.status' => InventarioScope::ATIVO,
            ])
            ->andWhere(['in', 'scope.id', $scopesAspectosOperacionais])
            ->all();

        $tableInventarioScopesAspectosOperacionais = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 1,
            'borderColor' => 'black',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
        ]);
        $tableInventarioScopesAspectosOperacionais->addRow();
        $tableInventarioScopesAspectosOperacionais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Área de atenção', $fontStyle9ITNR);
        $tableInventarioScopesAspectosOperacionais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Subárea de atenção', $fontStyle9ITNR);
        $tableInventarioScopesAspectosOperacionais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Processo auditado', $fontStyle9ITNR);
        $tableInventarioScopesAspectosOperacionais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Criticidade', $fontStyle9ITNR);

        foreach ($inventarioScopesOperacionais as $inventarioScopeOperacional) {

            $inventarioScopeCriticidade = '';

            if ($inventarioScopeOperacional->inventarioDados->tipo == \app\models\InventarioDados::TIPO_ROPA) {
                $inventarioScopeCriticidade = $inventarioScopeOperacional->risco;
            }
            if ($inventarioScopeOperacional->inventarioDados->tipo == \app\models\InventarioDados::TIPO_GENERICO) {
                $inventarioScopeCriticidade = $inventarioScopeOperacional->risco;
            }
            if ($inventarioScopeOperacional->inventarioDados->tipo == \app\models\InventarioDados::TIPO_FORNECEDOR) {
                $inventarioScopeCriticidade = $inventarioScopeOperacional->risco_fornecedor;
            }
            if ($inventarioScopeOperacional->inventarioDados->tipo == \app\models\InventarioDados::TIPO_SEGURANCA) {
                $inventarioScopeCriticidade = $inventarioScopeOperacional->risco_seguranca;
            }
            $tableInventarioScopesAspectosOperacionais->addRow();
            $tableInventarioScopesAspectosOperacionais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeOperacional->avo, $fontStyle11TNR);
            $tableInventarioScopesAspectosOperacionais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeOperacional->scope->name, $fontStyle11TNR);
            $tableInventarioScopesAspectosOperacionais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeOperacional->nome, $fontStyle11TNR);
            $tableInventarioScopesAspectosOperacionais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeCriticidade, $fontStyle11TNR);
        }

        $templateProcessor->setComplexBlock('criticidade_aspectos_operacionais', $tableInventarioScopesAspectosOperacionais);


        $scopeAspectoGerencial = Scope::find()
            ->where([
                'parent_id' => $scopeRoot->id ?? '',
                'name' => 'Aspectos Gerenciais',
                'status' => Scope::ATIVO,
            ])
            ->one();

        $scopesAspectosGerenciais = Scope::getRecursiveScopesIds($scopeAspectoGerencial->id);

        $inventarioScopesGerenciais = InventarioScope::find()
            ->joinWith('scope')
            ->where([
                'scope.contexto_id' => $contexto->id,
                'scope.status' => Scope::ATIVO,
                'inventario_scope.status' => InventarioScope::ATIVO,
            ])
            ->andWhere(['in', 'scope.id', $scopesAspectosGerenciais])
            ->all();

        $tableInventarioScopesAspectosGerenciais = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 1,
            'borderColor' => 'black',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
        ]);
        $tableInventarioScopesAspectosGerenciais->addRow();
        $tableInventarioScopesAspectosGerenciais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Área de atenção', $fontStyle9ITNR);
        $tableInventarioScopesAspectosGerenciais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Subárea de atenção', $fontStyle9ITNR);
        $tableInventarioScopesAspectosGerenciais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Processo auditado', $fontStyle9ITNR);
        $tableInventarioScopesAspectosGerenciais->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#FFFFFF'])->addText('Criticidade', $fontStyle9ITNR);

        foreach ($inventarioScopesGerenciais as $inventarioScopeGerencial) {

            $inventarioScopeCriticidade = '';

            if ($inventarioScopeGerencial->inventarioDados->tipo == \app\models\InventarioDados::TIPO_ROPA) {
                $inventarioScopeCriticidade = $inventarioScopeGerencial->risco;
            }
            if ($inventarioScopeGerencial->inventarioDados->tipo == \app\models\InventarioDados::TIPO_GENERICO) {
                $inventarioScopeCriticidade = $inventarioScopeGerencial->risco;
            }
            if ($inventarioScopeGerencial->inventarioDados->tipo == \app\models\InventarioDados::TIPO_FORNECEDOR) {
                $inventarioScopeCriticidade = $inventarioScopeGerencial->risco_fornecedor;
            }
            if ($inventarioScopeGerencial->inventarioDados->tipo == \app\models\InventarioDados::TIPO_SEGURANCA) {
                $inventarioScopeCriticidade = $inventarioScopeGerencial->risco_seguranca;
            }
            $tableInventarioScopesAspectosGerenciais->addRow();
            $tableInventarioScopesAspectosGerenciais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeGerencial->avo, $fontStyle11TNR);
            $tableInventarioScopesAspectosGerenciais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeGerencial->scope->name, $fontStyle11TNR);
            $tableInventarioScopesAspectosGerenciais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeGerencial->nome, $fontStyle11TNR);
            $tableInventarioScopesAspectosGerenciais->addCell(3000, ['noWrap' => false, 'borderTopColor' => '#FFFFFF',])->addText($inventarioScopeCriticidade, $fontStyle11TNR);
        }

        $templateProcessor->setComplexBlock('criticidade_aspectos_gerenciais', $tableInventarioScopesAspectosGerenciais);

        $minimoComprometedor = 20;
        $minimoExcelencia = 80;

        $coletaReferencia = Coleta::find()
            ->where([
                'contexto_id' => $contexto->id,
                'status' => Coleta::ATIVO,
            ])
            ->andWhere(['is not', 'data_coleta', new \yii\db\Expression('null')])
            ->orderBy('data_coleta DESC, id DESC')
            ->one();

        $coletaReferenciaIndicadores = ColetaIndicador::find()
            ->select([
                'coleta_indicador.id as id',
                'coleta_indicador.nome as nome',
                'coleta_indicador.pontuacao as pontuacao',
                'coleta_indicador.vertical_indicador_id as vertical_indicador_id',
                'coleta_indicador.conceito as conceito',
                'coleta_indicador.estrutura_id as estrutura_id',
                'vertical_indicador.usa_interpolacao as usainterpolacao',
            ])
            ->joinWith(['estrutura', 'coletaAlternativas', 'verticalIndicador'])
            ->where([
                'coleta_estrutura.coleta_id' => $coletaReferencia->id,
                'coleta_estrutura.status' => ColetaEstrutura::ATIVO,
                'coleta_indicador.status' => ColetaIndicador::ATIVO
            ])
            ->asArray()
            ->orderBy('coleta_indicador.ordem_estruturada ASC, coleta_indicador.id ASC')
            ->all();

        $coletaReferenciaListaIndicacoresExcelencia = [];
        $coletaReferenciaListaIndicacoresComprometedor = [];
        $coletaReferenciaListaIndicacoresMercado = [];

        foreach ($coletaReferenciaIndicadores as $coletaReferenciaIndicador) {

            $listaNomeIndicadores[] = $coletaReferenciaIndicador['nome'];

            $listaValoresIndicadores[] = ['y' => (int) $coletaReferenciaIndicador['pontuacao']];

            $minimoTemp = 0;
            $maximoTemp = 0;
            foreach ($coletaReferenciaIndicador['coletaAlternativas'] as $coletaAlternativaExcelencia) {
                if ($coletaAlternativaExcelencia['nivel_referencia'] < $minimoTemp) {
                    $minimoTemp = $coletaAlternativaExcelencia['nivel_referencia'];
                }
                if ($coletaAlternativaExcelencia['nivel_referencia'] > $maximoTemp) {
                    $maximoTemp = $coletaAlternativaExcelencia['nivel_referencia'];
                }
            }
            $coletaReferenciaIndicador['minimo'] = $minimoTemp;
            $coletaReferenciaIndicador['maximo'] = $maximoTemp;
            $coletaReferenciaIndicador['vertical_indicador_id'] = $coletaReferenciaIndicador['vertical_indicador_id'];
            $coletaReferenciaIndicador['usainterpolacao'] = $coletaReferenciaIndicador['usainterpolacao'];

            $coletaReferenciaIndicador['sparkline'] = '';
            if (isset($indicadorSparkline[$coletaReferenciaIndicador['vertical_indicador_id']])) {
                $coletaReferenciaIndicador['sparkline'] = implode(",", $indicadorSparkline[$coletaReferenciaIndicador['vertical_indicador_id']]);
            }

            if ($coletaReferenciaIndicador['pontuacao'] >= $minimoExcelencia) {
                $coletaReferenciaListaIndicacoresExcelencia[] = $coletaReferenciaIndicador;
            } elseif ($coletaReferenciaIndicador['pontuacao'] <= $minimoComprometedor) {
                $coletaReferenciaListaIndicacoresComprometedor[] = $coletaReferenciaIndicador;
            } else {
                $coletaReferenciaListaIndicacoresMercado[] = $coletaReferenciaIndicador;
            }
        }

        $indicadoresComprometedor = new \PhpOffice\PhpWord\Element\TextRun();

        foreach ($coletaReferenciaListaIndicacoresComprometedor as $comprometedor) {
            $indicadoresComprometedor->addText('- ' . $comprometedor['nome']);
            $indicadoresComprometedor->addTextBreak(1);
        }

        $templateProcessor->setComplexValue('indicadores_comprometimento', $indicadoresComprometedor);

        $indicadoresMercado = new \PhpOffice\PhpWord\Element\TextRun();

        foreach ($coletaReferenciaListaIndicacoresMercado as $mercado) {
            $indicadoresMercado->addText('- ' . $mercado['nome']);
            $indicadoresMercado->addTextBreak(1);
        }

        $templateProcessor->setComplexValue('indicadores_competitividade', $indicadoresMercado);

        $indicadoresExcelencia = new \PhpOffice\PhpWord\Element\TextRun();

        foreach ($coletaReferenciaListaIndicacoresExcelencia as $excelencia) {
            $indicadoresExcelencia->addText('- ' . $excelencia['nome']);
            $indicadoresExcelencia->addTextBreak(1);
        }

        $templateProcessor->setComplexValue('indicadores_excelencia', $indicadoresExcelencia);

        $riscoCenario = \app\modules\risk\models\RiscoCenario::find()
            ->where([
                'coleta_vinculo' => $coletaReferencia->id,
                'risco_cenario.status' => \app\modules\risk\models\Risco::ATIVO,
            ])
            ->one();

        $i = 1;

        $tableRisco = new \PhpOffice\PhpWord\Element\Table([
            //  'borderSize' => 10,
            //  'borderColor' => 'green',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
            'cellMargin' => 80,
        ]);

        if ($riscoCenario) {
            foreach ($riscoCenario->riscos as $risco) {

                $tableRisco->addRow();
                $tableRisco->addCell(3500, ['noWrap' => false])->addText('R' . $i . ' - ' . $risco->nome, $fontStyle11TNR);
                $tableRisco->addCell(500, ['noWrap' => false])->addText(' ', $fontStyle11TNR);
                $tableRisco->addRow();
                $tableRisco->addCell(3500, ['noWrap' => false, 'borderSize' => 1,
                    'borderColor' => '#000000',
                    'borderRightColor' => '#FFFFFF',
                    'borderBottomColor' => '#FFFFFF',
                    'bgColor' => '#D3D3D3',
                ])->addText('Identificação', $fontStyle11TNRB);
                $tableRisco->addCell(500, ['noWrap' => false, 'borderSize' => 1,
                    'borderColor' => '#000000',
                    'borderLeftColor' => '#FFFFFF',
                    'borderBottomColor' => '#FFFFFF',
                    'bgColor' => '#D3D3D3',
                ])->addText(' ', $fontStyle11TNRB);
                $tableRisco->addRow();
                $tableRisco->addCell(3500, ['noWrap' => false, 'borderSize' => 1,
                    'borderColor' => '#000000',
                    'borderRightColor' => '#FFFFFF',
                    'borderBottomColor' => '#FFFFFF',
                ])->addText('Descrição', $fontStyle10TBL);
                $tableRisco->addCell(500, ['noWrap' => false, 'borderSize' => 1,
                    'borderColor' => '#000000',
                    'borderLeftColor' => '#FFFFFF',
                    'borderBottomColor' => '#FFFFFF',
                ])->addText('TS', $fontStyle10TBL);
                $tableRisco->addRow();
                $tableRisco->addCell(3500, ['noWrap' => false, 'borderSize' => 1,
                    'borderColor' => '#FFFFFF',
                    'borderLeftColor' => '#000000',
                    'borderRightColor' => '#FFFFFF',
                    'borderBottomColor' => '#000000',
                ])->addText(strip_tags($risco->descricao), $fontStyle11TNR);
                $tableRisco->addCell(500, ['noWrap' => false, 'borderSize' => 1,
                    'borderColor' => '#FFFFFF',
                    'borderLeftColor' => '#FFFFFF',
                    'borderRightColor' => '#000000',
                    'borderBottomColor' => '#000000',
                ])->addText($risco->taxa_substituicao . '%', $fontStyle10TNC);
                $tableRisco->addRow();
                $tableRisco->addCell(3500, ['noWrap' => false, 'borderBottomColor' => '#000000'])->addText('', $fontStyle11TNR);
                $tableRisco->addCell(500, ['noWrap' => false, 'borderBottomColor' => '#000000'])->addText('', $fontStyle10TNC);

                $i++;
            }
        }

        $templateProcessor->setComplexValue('riscos', $tableRisco);


        $parecerTecnicoColetas = \app\modules\performance\models\ParecerTecnicoColeta::find()
            ->joinWith('coleta')
            ->where([
                'coleta.contexto_id' => $contexto->id,
                'parecer_tecnico_coleta.status' => \app\modules\performance\models\ParecerTecnicoColeta::ATIVO,
            ])
            ->all();

        // $pareceresTecnicos = '';
        // foreach ($parecerTecnicoColetas as $parecerTecnicoColeta) {
        //     $pareceresTecnicos .=  $parecerTecnicoColeta->parecer;           
        // }

        $parecerTecnico = new \PhpOffice\PhpWord\Element\TextRun();

        foreach ($parecerTecnicoColetas as $parecerTecnicoColeta) {
            $parecerTecnico->addText($parecerTecnicoColeta->parecer);
            $parecerTecnico->addTextBreak(1);
        }

        $templateProcessor->setComplexValue('parecer_tecnico', $parecerTecnico);

        $recomendacaoTecnicas = RecomendacaoSeguranca::find()
            ->where([
                'contexto_id' => $contexto->id,
                'status' => RecomendacaoSeguranca::ATIVO,
            ])
            ->all();

        $tableRecomendacao = new \PhpOffice\PhpWord\Element\Table([
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
            'cellMargin' => 80,
            'align' => 'left',
        ]);


        foreach ($recomendacaoTecnicas as $recomendacaoTecnica) {

            $prioridade = "-";
            $prioridadeColor = "-";

            if ($recomendacaoTecnica->prioridade == RecomendacaoSeguranca::IMPORTANTE) {
                $prioridade = "Importante";
                $prioridadeColor = "#dc3545";
            }

            if ($recomendacaoTecnica->prioridade == RecomendacaoSeguranca::RECOMENDAVEL) {
                $prioridade = "Recomendável";
                $prioridadeColor = "#ffc107";
            }

            if ($recomendacaoTecnica->prioridade == RecomendacaoSeguranca::DESEJAVEL) {
                $prioridade = "Desejável";
                $prioridadeColor = "#28a745";
            }

            $tableRecomendacao->addRow();
            $tableRecomendacao->addCell(6000, ['noWrap' => false, 'gridSpan' => 2,
                'borderSize' => 1,
                'borderColor' => '#000000',
                'borderRightColor' => '#000000',
                'borderBottomColor' => '#FFFFFF',
                'bgColor' => $prioridadeColor,
            ])->addText($prioridade, $fontStyle11TNRB);

            $tableRecomendacao->addRow();

            $tableRecomendacao->addCell(3000, ['noWrap' => false, 'borderSize' => 1,
                'borderColor' => '#000000',
                'borderRightColor' => '#FFFFFF',
                'borderLeftColor' => '#000000',
                'borderBottomColor' => '#FFFFFF',
            ])->addText('Área de Preocupação', $fontStyle10TBL);

            $tableRecomendacao->addCell(3000, ['noWrap' => false, 'borderSize' => 1,
                'borderColor' => '#000000',
                'borderRightColor' => '#000000',
                'borderLeftColor' => '#FFFFFF',
                'borderBottomColor' => '#FFFFFF',
            ])->addText('Local', $fontStyle10TBL);

            $tableRecomendacao->addRow();

            $tableRecomendacao->addCell(3000, ['noWrap' => false, 'borderSize' => 1,
                'borderColor' => '#000000',
                'borderRightColor' => '#FFFFFF',
                'borderBottomColor' => '#FFFFFF',
                'bordeTopColor' => '#FFFFFF',
            ])->addText($recomendacaoTecnica->area_preocupacao, $fontStyle10TNC);

            $tableRecomendacao->addCell(3000, ['noWrap' => false, 'borderSize' => 1,
                'borderColor' => '#000000',
                'borderRightColor' => '#000000',
                'borderBottomColor' => '#FFFFFF',
                'borderLeftColor' => '#FFFFFF',
                'bordeTopColor' => '#FFFFFF',
            ])->addText($recomendacaoTecnica->local, $fontStyle10TNC);

            $tableRecomendacao->addRow();

            $tableRecomendacao->addCell(6000, ['noWrap' => false, 'gridSpan' => 2,
                'borderSize' => 1,
                'borderColor' => '#000000',
                'borderRightColor' => '#000000',
                'borderBottomColor' => '#FFFFFF',
            ])->addText('Recomendação', $fontStyle10TBL);

            $tableRecomendacao->addRow();

            $tableRecomendacao->addCell(6000, ['noWrap' => false, 'gridSpan' => 2,
                'borderSize' => 1,
                'borderColor' => '#000000',
                'borderRightColor' => '#000000',
                'borderBottomColor' => '#FFFFFF',
                'bordeTopColor' => '#FFFFFF',
                'align' => 'left',
            ])->addText('${recomendacao_descricao_' . $recomendacaoTecnica->id . '}', $fontStyle10TNC);

            $tableRecomendacao->addRow();

            $tableRecomendacao->addCell(6000, ['noWrap' => false, 'gridSpan' => 2,
                'borderSize' => 1,
                'borderColor' => '#000000',
                'borderRightColor' => '#000000',
                'borderBottomColor' => '#FFFFFF',
            ])->addText('Riscos associados', $fontStyle10TBL);

            $tableRecomendacao->addRow();

            $tableRecomendacao->addCell(6000, ['noWrap' => false, 'gridSpan' => 2,
                'borderSize' => 1,
                'borderColor' => '#000000',
                'borderRightColor' => '#000000',
                'borderBottomColor' => '#000000',
                'bordeTopColor' => '#FFFFFF',
                'align' => 'left',
            ])->addText('${recomendacao_riscos_' . $recomendacaoTecnica->id . '}', $fontStyle10TNL);

            $tableRecomendacao->addRow();
            $tableRecomendacao->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#000000'])->addText('', $fontStyle11TNR);
            $tableRecomendacao->addCell(3000, ['noWrap' => false, 'borderBottomColor' => '#000000'])->addText('', $fontStyle10TNC);

            $i++;
        }

        $templateProcessor->setComplexValue('recomendacao_tecnica', $tableRecomendacao);

        foreach ($recomendacaoTecnicas as $recomendacaoTecnica) {

            $recomendacaoDescricao = new \PhpOffice\PhpWord\Element\TextRun();

            $recomendacaoDescricao->addText(str_replace("</p>", "", str_replace("<p>", "", $recomendacaoTecnica->descricao)), ['align' => 'left',]);

            $templateProcessor->setComplexValue('recomendacao_descricao_' . $recomendacaoTecnica->id, $recomendacaoDescricao);
        }

        foreach ($recomendacaoTecnicas as $recomendacaoTecnica) {

            $recomendacaoRisco = new \PhpOffice\PhpWord\Element\TextRun();

            foreach ($recomendacaoTecnica->getRecomendacaoSegurancaTemRiscos()->all() as $recomendacaoTemRisco) {
                $recomendacaoRisco->addText('- ' . $recomendacaoTemRisco->risco->nome . ' ', $fontStyle10TNL);
                $recomendacaoRisco->addTextBreak(1);
            }

            $templateProcessor->setComplexValue('recomendacao_riscos_' . $recomendacaoTecnica->id, $recomendacaoRisco);
        }

        /*
        $parser = new \HTMLtoOpenXML\Parser();
        $ooXml = $parser->fromHTML($pareceresTecnicos);
            
         $tableParecerTecnico = new \PhpOffice\PhpWord\Element\Table([
            'borderSize' => 0,
            'borderColor' => 'black',
            'width' => 100 * 50,
            'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
        ]);
        $tableParecerTecnico->addRow();
        $tableParecerTecnico->addCell(100 * 50, ['noWrap' => false, 'borderSize' => 0, 'borderColor' => 'white'])->addText($ooXml, $BodyFontStyle);
        
        
        $templateProcessor->setComplexBlock('pareceres_tecnicos', $tableParecerTecnico);
        //$templateProcessor->setValue('pareceres_tecnicos', $tableParecerTecnico);
        //

        
       
        $ultimaColeta = \app\modules\performance\models\Coleta::find()
                ->where([
                    'contexto_id' => $contexto->id,
                    'status' => \app\modules\performance\models\Coleta::ATIVO,
                ])
                ->orderBy('id DESC')
                ->one();

        $pontuacao = '';

        if ($ultimaColeta) {

            $dominios = [];
            $dominios[1] = 'Gestão de Consentimento';
            $dominios[2] = 'Gestão de Dados Pessoais';
            $dominios[3] = 'Gestão de Terceiros';
            $dominios[4] = 'Governança em Privacidade';
            $dominios[5] = 'Relacionamento com Titulares';
            $dominios[6] = 'Segurança de Informações';
            $dominios[7] = 'Transferência Internacional';
            $dominios[8] = 'Treinamentos e Conscientização';

            foreach ($dominios as $key => $dominio) {
                $coletaEstrutura = \app\modules\performance\models\ColetaEstrutura::find()
                        ->where([
                            'nome' => $dominio,
                            'coleta_id' => $ultimaColeta->id,
                        ])
                        ->one();
                
                if ($coletaEstrutura) {
                    $pontuacao = 'Pontuação de aderência do domínio: ' . $coletaEstrutura->pontuacao . ' pontos.';

                    $table = new \PhpOffice\PhpWord\Element\Table([
                        'borderSize' => 0,
                        'borderColor' => 'black',
                        'width' => 100 * 50,
                        'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
                    ]);
                    $table->addRow();
                    $table->addCell(, ['noWrap' => false])->addText('Controle', $BodyFontStyle);
                    $table->addCell(, ['noWrap' => false])->addText('Conceito', $BodyFontStyle);
                    $table->addCell(, ['noWrap' => false])->addText('Situação', $BodyFontStyle);
                    $table->addCell(null, ['noWrap' => false, 'text-align' => 'center', 'align' => 'center'])->addText('Pontuação', $BodyFontStyle);

                    $pves = \app\modules\performance\models\ColetaEstrutura::find()
                    ->select('id')
                    ->where([
                        'cod_pai' => $coletaEstrutura->id,                        
                    ])
                    ->column();

                    $pvfPves = array_merge($pves, [$coletaEstrutura->id]);

                    $indicadores = \app\modules\performance\models\ColetaIndicador::find()
                            ->where([                          
                                'status' => \app\modules\performance\models\ColetaIndicador::ATIVO,
                            ])
                            ->andWhere(['in', 'estrutura_id', $pvfPves])    
                            ->all();

                    foreach ($indicadores as $indicador) {
                        $table->addRow();
                        $table->addCell(, ['noWrap' => false])->addText($indicador->nome, $BodyFontStyle);
                        $table->addCell(, ['noWrap' => false])->addText($indicador->verticalIndicador->conceito, $BodyFontStyle);

                        if ($indicador->pontuacao == 100) {
                            $situacao = 'Conforme';
                        } elseif ($indicador->pontuacao == 0) {
                            $situacao = 'Não conforme';
                        } else {
                            $situacao = 'Necessita melhorias';
                        }

                        $table->addCell(, ['noWrap' => false])->addText($situacao, $BodyFontStyle);
                        $table->addCell(null, ['noWrap' => false, 'text-align' => 'center', 'align' => 'center'])->addText($indicador->pontuacao, $BodyFontStyleCenter);
                    }
                }

                $templateProcessor->setValue('pontuacao_' . $key, $pontuacao);
                $templateProcessor->setComplexBlock('cluster_' . $key, $table);

                $tableRecomendacao = new \PhpOffice\PhpWord\Element\Table([
                    'borderSize' => 0,
                    'borderColor' => 'black',                   
                    'width' => 100 * 50,
                    'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
                ]);
               
                $recomendacoesTecnicas = \app\modules\performance\models\RecomendacaoSeguranca::find()
                        ->where([
                            'area_preocupacao' => $dominio,
                            'contexto_id' => $contexto->id,
                            'status' => \app\modules\performance\models\RecomendacaoSeguranca::ATIVO,
                        ])
                        ->all();                              

                $espaco = '    ';        
                foreach ($recomendacoesTecnicas as $recomendacoesTecnica) {
    
                    $riscosAssociados = '';
                    $e = 0;
                    foreach ($recomendacoesTecnica->recomendacaoSegurancaTemRiscos as $risco1) {
                        if ($risco1->status == \app\modules\performance\models\RecomendacaoSegurancaTemRisco::ATIVO) {
                            $e++;
                            $riscosAssociados .= $espaco . '  -' . $risco1->risco->nome . '<w:br/>';
                        }
                    }
                    if ($e == 0) {
                        $riscosAssociados = 'Nenhum risco associado';
                    }

                    $local = str_replace("</p>", "###",  $recomendacoesTecnica->local);
                    $local = strip_tags($local);
                    $local = str_replace("###", "<w:br/>" . $espaco,  $local);

                    $tableRecomendacao->addRow();
                    $tableRecomendacao->addCell(20 *50, ['noWrap' => false])->addText('Grau: <w:br/> '.$espaco.' ' . strip_tags($recomendacoesTecnica->getPrioridadeLabel()), $BodyFontStyle);
                    $tableRecomendacao->addCell(80 * 50, ['noWrap' => false])->addText('Controle: <w:br/>'.$espaco. $local, $BodyFontStyle);
                    
                    $tableRecomendacao->addRow();
                    $tableRecomendacao->addCell(100 * 50, ['noWrap' => false, 'gridSpan' => 2])->addText('Recomendação: <w:br/> '.$espaco.' ' . strip_tags($recomendacoesTecnica->descricao), $BodyFontStyle);
                     
                    $tableRecomendacao->addRow();
                    $tableRecomendacao->addCell(100 * 50, ['noWrap' => false, 'gridSpan' => 2])->addText('Riscos associados: <w:br/>' . $riscosAssociados, $BodyFontStyle);
                     
                    $tableRecomendacao->addRow();
                    $tableRecomendacao->addCell(100 * 50, ['noWrap' => false, 'gridSpan' => 2, 'borderSize' => 0, 'borderColor' => 'white'])->addText(' ', $BodyFontStyle);
                    $tableRecomendacao->addRow();
                    $tableRecomendacao->addCell(100 * 50, ['noWrap' => false, 'gridSpan' => 2, 'borderSize' => 0, 'borderColor' => 'white'])->addText(' ', $BodyFontStyle);                     
                   
                } 

                if(empty($recomendacoesTecnicas)){
                    $tableRecomendacaoNenhuma = 'Nenhuma recomendação técnica cadastrada.';
                    $templateProcessor->setValue('recomendacao_' . $key, $tableRecomendacaoNenhuma);
                } else {
                    $templateProcessor->setComplexBlock('recomendacao_' . $key, $tableRecomendacao);
                }

                
            }
        }
        */



        $templateProcessor->saveAs($arquivo, 'Word97-2003');

        if (file_exists($arquivo)) {

            Yii::$app->response->sendFile($arquivo);
        } else {
            throw new \yii\web\HttpException(500, "Laudo de Segurança não encontrado");
        }
    }
}
