<?php

namespace App\Controllers;

use App\Controllers\BaseController;

use App\Entities\FormOptionEntity;
use App\Libraries\LogCollector;
use App\Services\MyLogService;
use CodeIgniter\HTTP\DownloadResponse;

use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;
use PhpOffice\PhpSpreadsheet\IOFactory;

use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use Psr\Log\LoggerInterface;

abstract class CommonController extends BaseController
{
    private $_db;
    private $_myAuth = null;
    private ?MyLogService $_myLogService = null;
    private $_viewDatas = [];
    private $_control = [];
    abstract public function getService(): mixed;
    abstract function getHelper(): mixed;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->isLoggedIn = false;
        $this->uri    = $request->getUri();
        if ($this->getMyAuth()->isLoggedIn()) {
            $this->isLoggedIn = true;
            $this->myAuthName = $this->getMyAuth()->getNameByAuthInfo();
            $this->myAuthUID = $this->getMyAuth()->getUIDByAuthInfo();
        }
        $this->_db = \Config\Database::connect();
    }
    final public function __get($name)
    {
        if (!array_key_exists($name, $this->_viewDatas)) {
            return null;
        }
        return $this->_viewDatas[$name];
    }
    final public function __set($name, $value): void
    {
        $this->_viewDatas[$name] = $value;
    }
    final protected function getMyAuth(): mixed
    {
        if (!$this->_myAuth) {
            $this->_myAuth = service('myauth');
        }
        return $this->_myAuth;
    }
    final public function getViewDatas(): array
    {
        return $this->_viewDatas;
    }
    final public function getMyLogService(): mixed
    {
        if (!$this->_myLogService) {
            $this->_myLogService = new MyLogService();
        }
        return $this->_myLogService;
    }
    //Index,FieldForm관련
    final protected function getControlDatas(): array
    {
        return $this->_control;
    }
    final protected function setAction(string $action): void
    {
        $this->_control['action'] = $action;
    }
    final protected function getAction(): string
    {
        if (!array_key_exists('action', $this->_control)) {
            throw new \Exception("action이 정의되지 않았습니다.");
        }
        return $this->_control['action'];
    }
    final protected function setFormFields(array $fields): void
    {
        $this->_control['form_fields'] = $fields;
    }
    final protected function getFormFields(): array
    {
        return $this->_control['form_fields'] ?? [];
    }
    final protected function setFieldRule(string $field, string $rule): void
    {
        if (!array_key_exists('field_rules', $this->_control)) {
            $this->_control['field_rules'] = [];
        }
        $this->_control['field_rules'][$field] = $rule;
    }
    final protected function setFieldRules(array $rules): void
    {
        $this->_control['field_rules'] = $rules;
    }
    final protected function getFieldRule(string $field): string
    {
        return $this->_control['field_rules'][$field] ?? [];
    }
    final protected function getFieldRules(): array
    {
        return $this->_control['field_rules'] ?? [];
    }
    final protected function setIndexFields(array $fields): void
    {
        $this->_control['index_fields'] = $fields;
    }
    final protected function getIndexFields(): array
    {
        return $this->_control['index_fields'] ?? [];
    }
    final protected function setViewFields(array $fields): void
    {
        $this->_control['view_fields'] = $fields;
    }
    final protected function getViewFields(): array
    {
        return $this->_control['view_fields'] ?? [];
    }
    final protected function setFilterFields(array $fields): void
    {
        $this->_control['filter_fields'] = $fields;
    }
    final protected function getFilterFields(): array
    {
        return $this->_control['filter_fields'] ?? [];
    }
    final protected function setBatchjobFields(array $fields): void
    {
        $this->_control['batchjob_fields'] = $fields;
    }
    final protected function getBatchjobFields(): array
    {
        return $this->_control['batchjob_fields'] ?? [];
    }
    final protected function setBatchjobButtions(array $fields): void
    {
        $this->_control['batchjob_buttions'] = $fields;
    }
    final protected function getBatchjobButtions(): array
    {
        return $this->_control['batchjob_buttions'] ?? [];
    }
    final protected function setFilterFieldOption(string $field, array $options): void
    {
        if (!array_key_exists('filter_optons', $this->_control)) {
            $this->_control['filter_optons'] = [];
        }
        //Filter Options 초기화
        $this->_control['filter_optons'][$field] = [
            "" => new FormOptionEntity(["uid" => "", "title" => lang("{$this->getService()->getClassName()}.label.{$field}") . " 선택"])
        ];
        foreach ($options as $option) {
            $this->_control['filter_optons'][$field][$option->getPK()] = $option;
        }
        // dd($this->_control['filter_optons'][$field]);
    }
    final protected function getFilterFieldOption(string $field): array
    {
        return $this->_control['filter_optons'][$field];
    }
    final protected function setFilterValues(): void
    {
        if (!array_key_exists('filter_values', $this->_control)) {
            $this->_control['filter_values'] = [];
        }
        foreach ($this->getFilterFields() as $field) {
            $this->_control['filter_values'][$field] = $this->request->getVar($field);
        }
    }
    final protected function getFilterValues(?string $field = null): mixed
    {
        if ($field === null) {
            return $this->_control['filter_values'] ?? [];
        }
        return array_key_exists($field, $this->_control['filter_values']) ? $this->_control['filter_values'][$field] : null;
    }

    protected function initAction(string $action, $fields = []): void
    {   //각 Field 초기화
        $this->setAction($action);
        $this->setFormFields(array_key_exists('formFields', $fields) ? $fields['formFields'] : $this->getService()->getFormFields());
        foreach ($this->getFormFields() as $field) {
            $this->setFieldRule($field, $this->getFormFieldRule($this->getAction(), $field));
        }
        $this->setIndexFields(array_key_exists('indexFields', $fields) ? $fields['indexFields'] : $this->getService()->getIndexFields());
        $this->setViewFields(array_key_exists('viewFields', $fields) ? $fields['viewFields'] : $this->getService()->getViewFields());
        $this->setFilterFields(array_key_exists('filterFields', $fields) ? $fields['filterFields'] : $this->getService()->getFilterFields());
        foreach ($this->getFilterFields() as $field) {
            $this->setFilterFieldOption($field, $this->getFormFieldOption($field));
        }
        $this->setBatchJobFields(array_key_exists('batchjobFields', $fields) ? $fields['batchjobFields'] : $this->getService()->getBatchJobFields());
        $this->setBatchJobButtions(array_key_exists('batchjobButtions', $fields) ? $fields['batchjobFields'] : $this->getService()->getBatchJobButtons());
    }
    protected function getFormFieldRule(string $action, string $field): string
    {
        if (is_array($field)) {
            throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
        }
        switch ($field) {
            default:
                $rule = $this->getService()->getFormFieldRule($action, $field);
                break;
        }
        return $rule;
    }
    protected function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            default:
                $options = $this->getService()->getFormFieldOption($field, $options);
                break;
        }
        if (!is_array($options)) {
            throw new \Exception(__FUNCTION__ . "에서 field의 options 값이 array가 아닙니다.\n" . var_export($options, true));
        }
        return $options;
    }
    protected function setValidation(Validation $validation, string $field, string $rule): Validation
    {
        switch ($field) {
            default:
                $validation->setRule($field, $field, $rule);
                break;
        }
        return $validation;
    }
    //Field관련
    //데이터 검증
    final protected function doValidate(array $rules, array $formDatas, ?Validation $validation = null): array
    {
        //변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요
        if (!$validation) {
            $validation = service('validation');
        }
        // dd($rules);
        foreach ($rules as $field => $rule) {
            $validation = $this->setValidation($validation, $field, $rule);
        }
        // dd($formDatas);
        if (!$validation->run($formDatas)) {
            throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode(
                "\n",
                $validation->getErrors()
            ));
        }
        return $formDatas;
        // return $validation->getValidated();
    }
    protected function getResultFail(string $message = MESSAGES["FAILED"]): RedirectResponse
    {
        LogCollector::debug($message);
        $this->getMyLogService()->save($this->getService()->getClassName(), $this->getAction(), $message, $this->getMyAuth()->getUIDByAuthInfo());
        if ($this->request->getMethod() === 'POST') {
            return redirect()->back()->withInput()->with('error', $message);
        }
        return redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
    }
    protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        helper(['form']);
        switch ($this->getAction()) {
            case 'create':
            case 'modify':
                $this->getMyLogService()->save($this->getService()->getClassName(), $this->getAction(), $message, $this->getMyAuth()->getUIDByAuthInfo());
                $result = $this->view($this->entity->getPK());
                break;
            case 'create_form':
            case 'modify_form':
            case 'login_form':
            case 'view':
            case 'index':
            case 'download':
                $this->control = $this->getControlDatas();
                $this->getHelper()->setViewDatas($this->getViewDatas());
                $actionTemplate = $this->request->getVar('ActionTemplate') ?? $actionTemplate;
                if ($actionTemplate) {
                    $view_file = $this->view_path . $actionTemplate . DIRECTORY_SEPARATOR . $this->getAction();
                } else {
                    $view_file = $this->view_path . $this->getAction();
                }
                $result = view($view_file, ['viewDatas' => $this->getViewDatas()]);
                break;
            default:
                $result = redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
                break;
        }
        return $result;
    }
    //Index,FieldForm관련

    //  생성
    protected function create_form_process(): void {}
    final public function create_form(): RedirectResponse|string
    {
        try {
            //각 Field 초기화
            // $this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            $this->initAction(__FUNCTION__);
            //filter_fields에 해당하는 값이 있을 경우 정의
            $this->setFilterValues();
            $this->create_form_process();
            helper(['form']);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
    //생성관련
    protected function create_process(array $formDatas): void
    {
        //데이터 검증
        $validDatas =  $this->doValidate($this->getFieldRules(), $formDatas);
        $this->entity =  $this->getService()->create($validDatas);
    }
    final public function create(): RedirectResponse|string
    {
        $this->_db->transStart();
        try {
            //각 Field 초기화
            $this->initAction(__FUNCTION__);
            //입력값정의
            $formDatas = [];
            foreach ($this->getFormFields() as $field) {
                $formDatas[$field] = $this->request->getPost($field);
            }
            // dd($formDatas);
            $this->create_process($formDatas);
            $this->_db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $this->_db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //수정관련
    protected function modify_form_process(mixed $entity): void
    {
        $this->entity = $entity;
    }
    final public function modify_form(mixed $uid): RedirectResponse|string
    {
        try {
            //각 Field 초기화
            // $this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            $this->initAction(__FUNCTION__);
            //filter_fields에 해당하는 값이 있을 경우 정의
            $this->setFilterValues();
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->modify_form_process($entity);
            helper(['form']);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
    protected function modify_process(mixed $entity, array $formDatas): void
    {
        //데이터 검증
        $validDatas =  $this->doValidate($this->getFieldRules(), $formDatas);
        $this->entity = $this->getService()->modify($entity, $validDatas);
    }
    final public function modify(int $uid): RedirectResponse|string
    {
        //Transaction Start
        $this->_db->transStart();
        try {
            //각 Field 초기화
            $this->initAction(__FUNCTION__);
            //입력값정의
            $formDatas = [];
            foreach ($this->getFormFields() as $field) {
                $formDatas[$field] = $this->request->getPost($field);
            }
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->modify_process($entity,  $formDatas);
            $this->_db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $this->_db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //단일필드작업
    final protected function toggle_process(mixed $entity, array $formDatas): void
    {
        //데이터 검증
        $validDatas =  $this->doValidate($this->getFieldRules(), $formDatas);
        $this->entity = $this->getService()->modify($entity, $validDatas);
    }
    final public function toggle(mixed $uid, string $field): RedirectResponse|string
    {
        //Transaction Start
        $this->_db->transStart();
        try {
            //각 Field 초기화:조건항목 Field는 한개만 존재하므로 Field와 Rule을 정의
            $this->setAction(__FUNCTION__);
            $this->setFormFields([$field]);
            $this->setFieldRule($field, $this->getFormFieldRule($this->getAction(), $field));
            //입력값정의
            $formDatas = [$field => $this->request->getVar($field)];
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->toggle_process($entity,  $formDatas);
            $this->_db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $this->_db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //일괄처리작업
    final protected function batchjob_process(array $uids, array $formDatas): void
    {
        $entities = [];
        foreach ($uids as $uid) {
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                LogCollector::debug(__METHOD__ . "에서 {$uid}에 대한 정보를 찾을수 없습니다.");
            } else {
                //데이터 검증
                $validDatas =  $this->doValidate($this->getFieldRules(), $formDatas);
                $entities[] = $this->getService()->modify($entity, $validDatas);
            }
        }
        $this->entities = $entities;
    }
    final public function batchjob(): RedirectResponse|string
    {
        //Transaction Start
        $this->_db->transStart();
        try {
            $selectedFields = [];
            //getBatchJobFields를 이용해서 선택된 Field 와 값정의
            $formDatas = [];
            foreach ($this->getService()->getBatchJobFields() as $field) {
                $value = $this->request->getPost($field);
                if ($value) {
                    $selectedFields[] = $field;
                    $formDatas[$field] = $value;
                }
            }
            if (!count($selectedFields)) {
                throw new \Exception("변경할 조건항목을 선택하셔야합니다.");
            }
            //변경할 UIDS 정의
            $uids = $this->request->getPost('batchjob_uids[]');
            if (!is_array($uids) || !count($uids)) {
                throw new \Exception("적용할 리스트을 선택하셔야합니다.");
            }
            //각 Field 초기화: 일괄작업은 선택된 조건항목 Field만 존재하므로 Field와 Rule을 정의
            $this->setAction(__FUNCTION__);
            $this->setFormFields([$selectedFields]);
            foreach ($selectedFields as $field) {
                $this->setFieldRule($field, $this->getFormFieldRule($this->getAction(), $field));
            }
            $this->batchjob_process($uids, $formDatas);
            $this->_db->transCommit();
            LogCollector::debug(sprintf("%s에서 총 %s개중 %s개 일괄작업을 완료하였습니다.", __METHOD__, count($uids), count($this->entities)));
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $this->_db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }

    //삭제,일괄삭제 공통사용
    protected function delete_process(mixed $entity): void
    {
        $this->entity = $this->getService()->delete($entity);
    }
    final public function delete(mixed $uid): RedirectResponse|string
    {
        //Transaction Start
        $this->_db->transStart();
        try {
            //각 Field 초기화:삭제는 다른 초기화 필요없음
            $this->setAction(__FUNCTION__);
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->delete_process($entity);
            $this->_db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $this->_db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //일괄삭제
    final protected function batchjob_delete_process(array $uids): void
    {
        $entities = [];
        foreach ($uids as $uid) {
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                LogCollector::debug(__METHOD__ . "에서 {$uid}에 대한 정보를 찾을수 없습니다.");
            } else {
                $entities[] = $this->getService()->delete($entity);
            }
        }
        $this->entities = $entities;
    }
    final public function batchjob_delete(): RedirectResponse|string
    {
        //Transaction Start
        $this->_db->transStart();
        try {
            //변경할 UIDS
            $uids = $this->request->getPost('batchjob_uids[]');
            if (!is_array($uids) || !count($uids)) {
                throw new \Exception("적용할 리스트를 선택하셔야합니다.");
            }
            //각 Field 초기화:삭제는 다른 초기화 필요없음
            $this->setAction(__FUNCTION__);
            $this->batchjob_delete_process($uids);
            $this->_db->transCommit();
            LogCollector::debug(sprintf("%s에서 총 %s개중 %s개 일괄삭제를 완료하였습니다.", __METHOD__, count($uids), count($this->entities)));
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $this->_db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }

    //View
    protected function view_process(mixed $entity): void
    {
        $this->entity = $entity;
    }
    final public function view(string $uid): RedirectResponse|string
    {
        try {
            //각 Field 초기화
            $this->initAction(__FUNCTION__);
            //FieldRule정의
            foreach ($this->getViewFields() as $field) {
                $this->setFieldRule($field, $this->getFormFieldRule($this->getAction(), $field));
            }
            //filter_fields에 해당하는 값이 있을 경우 정의
            $this->setFilterValues();
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->view_process($entity);
            helper(['form']);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }

    //리스트
    //조건절 처리
    final protected function setConditionForList(): void
    {
        $this->setFilterValues();
        //Filter 조건절 처리
        foreach ($this->getFilterFields() as $field) {
            $filter_value = $this->getFilterValues($field);
            if ($filter_value !== null && $filter_value !== '') {
                $this->getService()->setList_FormFilter($field, $filter_value);
            }
        }
        //검색어조건절 처리
        $this->word = $this->request->getVar('word');
        if ($this->word !== null && $this->word !== '') {
            $this->getService()->setList_WordFilter($this->word);
        }
        //날자검색
        $this->start  = $this->request->getVar('start');
        $this->end  = $this->request->getVar('end');
        if ($this->start !== null && $this->start !== '' && $this->end !== null && $this->end !== '') {
            $this->getService()->setList_DateFilter($this->start, $this->end);
        }
    }
    //PageNation 처리
    final protected function getPageOptiosForList(): array
    {
        $page_options = ["" => "줄수선택"];
        for ($i = $this->per_page; $i <= $this->total_count; $i += $this->per_page) {
            $page_options[$i] = $i;
        }
        $page_options[$this->total_count] = $this->total_count;
        return $page_options;
    }
    final protected function getPaginationForList($pager_group = 'default', int $segment = 0, $template = 'bootstrap_full')
    {
        //Page, Per_page필요부분
        $this->page = (int) $this->request->getVar('page') ?: 1;
        $this->per_page = (int) $this->request->getVar('per_page') ?: intval(DEFAULT_LIST_PERPAGE ?? 20);
        // 1.Views/Pagers/에 bootstrap_full.php,bootstrap_simple.php 생성
        // 2.app/Config/Pager.php/$templates에 'bootstrap_full => 'Pagers\bootstrap_full',
        // 'bootstrap_simple' => 'Pagers\bootstrap_simple', 추가
        $pager = service("pager");
        $pager->makeLinks($this->page, $this->per_page, $this->total_count, $template, $segment, $pager_group);
        $this->page = $pager->getCurrentPage($pager_group);
        $this->total_page = $pager->getPageCount($pager_group);
        return $pager->links($pager_group, $template);
    }
    protected function index_process(): void
    {
        //조건절 , OrcerBy , Limit 처리
        $this->setConditionForList();
        $this->order_field = $this->request->getVar('order_field');
        $this->order_value = $this->request->getVar('order_value');
        $this->getService()->setOrderBy($this->order_field, $this->order_value);
        $this->getService()->setLimit($this->per_page);
        $this->getService()->setOffset(($this->page - 1) * $this->per_page);
        $this->entities = $this->getService()->getEntities();
    }
    public function index(): RedirectResponse|string
    {
        try {
            //각 Field 초기화
            $this->initAction(__FUNCTION__);
            //Return Url정의
            $this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            //FieldRule정의
            foreach ($this->getIndexFields() as $field) {
                $this->setFieldRule($field, $this->getFormFieldRule($this->getAction(), $field));
            }
            // 현재 URL을 스택에 저장
            helper(['form']);
            //조건절 처리
            $this->setConditionForList();
            //TotalCount (SoftDelete적용이 되려면 countAllResults를 사용해야함)
            $this->total_count = $this->getService()->getTotalCount();
            //Pagination 처리
            $this->pagination = $this->getPaginationForList();
            //줄수 처리용
            $this->page_options = $this->getPageOptiosForList();
            $this->index_process();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $e->getMessage();
            // return $this->getResultFail($e->getMessage());
        }
    }

    //OUPUT Document 관련
    private function download_document(string $document_type, mixed $loaded_data): array
    {
        $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "excel";
        switch ($document_type) {
            case 'excel':
                $file_name = sprintf("%s_%s.xlsx", $this->getService()->getClassName(), date('Y-m-d_Hm'));
                $writer = IOFactory::createWriter($loaded_data, 'Xlsx');
                $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
                break;
            case 'pdf':
                $file_name = sprintf("%s_%s.pdf", $this->getService()->getClassName(), date('Y-m-d_Hm'));
                $writer = new Mpdf($loaded_data);
                $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
                break;
        }
        return array($full_path, $file_name);
    }
    // Download
    final public function download(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse|string
    {
        try {
            //각 Field 초기화
            $this->initAction(__FUNCTION__);
            //URL처리
            // $this->uri = $this->request->getUri();
            switch ($output_type) {
                case 'excel':
                case 'pdf':
                    helper(['form']);
                    $this->index_process();
                    $html = $this->getResultSuccess();
                    //data loading
                    $reader = new Html();
                    $loaded_data = $reader->loadFromString($html);
                    list($full_path, $file_name) = $this->download_document($output_type, $loaded_data);
                    $full_path .= DIRECTORY_SEPARATOR . $file_name;
                    break;
                default:
                    if (!$uid) {
                        throw new \Exception("{$output_type}은 반드시 uid의 값이 필요합니다.");
                    }
                    $entity = $this->getService()->getEntity($uid);
                    if (!$entity) {
                        throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
                    }
                    $this->entity = $entity;
                    list($file_name, $uploaded_filename) = $this->entity->getDownlaodFile();
                    $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $uploaded_filename;
                    break;
            }
            return $this->response->download($full_path, null)->setFileName($file_name);
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
}
