<?php

namespace App\Services\Equipment;

use RuntimeException;
use App\Services\Part\PartService;
use App\Models\Equipment\ServerPartModel;
use App\Helpers\Equipment\ServerPartHelper;
use App\Forms\Equipment\ServerPartForm;
use App\Entities\Part\PartEntity;
use App\Entities\Equipment\ServerPartEntity;
use App\Entities\Equipment\ServerEntity;
use App\DTOs\Equipment\ServerPartDTO;

class ServerPartService extends EquipmentService
{
    private $_form = null;
    private $_helper = null;
    public function __construct(ServerPartModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('ServerPart');
    }
    protected function getDTOClass(): string
    {
        return ServerPartDTO::class;
    }
    public function createDTO(array $formDatas): ServerPartDTO
    {
        return new ServerPartDTO($formDatas);
    }
    public function getEntityClass(): string
    {
        return ServerPartEntity::class;
    }
    public function getFormService(): ServerPartForm
    {
        if ($this->_form === null) {
            $this->_form = new ServerPartForm();
            $this->_form->setAttributes([
                'pk_field'         => $this->model->getPKField(),
                'title_field'      => $this->model->getTitleField(),
                'table'            => $this->model->getTable(),
                'useAutoIncrement' => $this->model->useAutoIncrement(),
                'class_path' => $this->getClassPaths(false)
            ]);
        }
        return $this->_form;
    }
    public function getHelper(): ServerPartHelper
    {
        if ($this->_helper === null) {
            $this->_helper = new ServerPartHelper();
            $this->_helper->setAttributes([
                'pk_field'         => $this->model->getPKField(),
                'title_field'      => $this->model->getTitleField(),
                'table'            => $this->model->getTable(),
                'useAutoIncrement' => $this->model->useAutoIncrement(),
                'class_path' => $this->getClassPaths(false)
            ]);
        }
        return $this->_helper;
    }
    public function action_init_process(string $action, array $formDatas = []): void
    {
        $fields = [
            "serverinfo_uid",
            "type",
            "billing",
            "part_uid",
            "cnt",
            "extra",
            "amount",
        ];
        $filters = [
            "serverinfo_uid",
            "type",
            "part_uid",
            "billing",
        ];
        $indexFilter = [
            "serverinfo_uid",
            "type",
            "billing",
        ];
        $batchjobFilters = ['billing', 'type'];
        switch ($action) {
            case 'create':
            case 'create_form':
            case 'modify':
            case 'modify_form':
                break;
            case 'view':
                $fields = [...$fields, 'created_at'];
                break;
            case 'index':
            case 'download':
                $fields = [...$fields, 'created_at'];
                break;
        }
        $this->getFormService()->setFormFields($fields);
        $this->getFormService()->setFormRules($action, $fields);
        $this->getFormService()->setFormFilters($filters);
        $this->getFormService()->setFormOptions($action, $filters, $formDatas);
        $this->getFormService()->setIndexFilters($indexFilter);
        $this->getFormService()->setBatchjobFilters($batchjobFilters);
    }
    //각 파트별 서비스
    private function getPartService(string $type): PartService
    {
        return service('part_' . strtolower($type) . 'service');
    }
    //기본 기능부분
    protected function getEntity_process(mixed $entity): ServerPartEntity
    {
        return $entity;
    }
    protected function create_process(array $formDatas): ServerPartEntity
    {
        if (!array_key_exists('type', $formDatas)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:부품형식이 지정되지 않았습니다.");
        }
        //각 파트정보 가져오기
        $partEntity = $this->getPartService($formDatas['type'])->getEntity($formDatas['part_uid']);
        //해당 파트정보 Title 설정용
        $formDatas['title'] = $partEntity->getTitle();
        //서버파트 생성
        $entity = parent::create_process($formDatas);
        if (!$entity instanceof ServerPartEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 ServerPartEntity만 가능");
        }
        //해당 파트별 설정 수정
        $this->getPartService($entity->getType())->attachToServerPart($entity);
        if ($entity->getServiceInfoUID() !== null) { //서비스가 정의 되어 있으면
            if ($entity->getBilling() == PAYMENT['BILLING']['MONTH']) { //Billing형식이 Month이면 서비스 금액설정 호출
                service('customer_serviceservice')->updateAmount($entity->getServiceInfoUID());
            }
            if ($entity->getBilling() == PAYMENT['BILLING']['ONETIME']) { //Billing형식이 Onetime이면 일회성결제 추가
                service('paymentservice')->createByServerPart($entity);
            }
        }
        return $entity;
    }
    protected function modify_process($entity, array $formDatas): ServerPartEntity
    {
        if (!array_key_exists('type', $formDatas)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:부품형식이 지정되지 않았습니다.");
        }
        //각 파트정보 가져오기
        $partEntity = $this->getPartService($formDatas['type'])->getEntity($formDatas['part_uid']);
        //해당 파트정보 Title 설정용
        $formDatas['title'] = $partEntity->getTitle();
        //서버파트 수정
        $entity = parent::modify_process($entity, $formDatas);
        if ($entity->getServiceInfoUID() !== null) {
            //서비스가 정의 되어 있으면 서비스 비용 수정
            if ($entity->getBilling() == PAYMENT['BILLING']['MONTH']) { //Billing형식이 Month이면 서비스 금액설정 호출
                service('customer_serviceservice')->updateAmount($entity->getServiceInfoUID());
            }
            if ($entity->getBilling() == PAYMENT['BILLING']['ONETIME']) { //Billing형식이 Onetime이면 일회성결제 추가
                service('paymentservice')->modifyByServerPart($entity);
            }
        }
        return $entity;
    }
    protected function delete_process($entity): ServerPartEntity
    {
        $this->getPartService($entity->getType())->detachFromServerPart($entity);
        $entity = parent::delete_process($entity);
        if ($entity->getServiceInfoUID() !== null) { //서비스가 정의 되어 있으면
            if ($entity->getBilling() == PAYMENT['BILLING']['MONTH']) { //Billing형식이 Month이면 서비스 금액설정 호출
                service('customer_serviceservice')->updateAmount($entity->getServiceInfoUID());
            }
        }
        return $entity;
    }
    //List 검색용
    //FormFilter 조건절 처리
    //검색어조건절처리

    //서버추가시 기본파트 자동추가용
    public function defaultServerPart(ServerEntity $serverEntity): void
    {
        //*서버의 Title 대소문자구분 필요->서버의 Title로 구분해서 기본부품 추가
        foreach (SERVERPART['SERVER_PARTTYPES'] as $parttype) {
            //해당 서버의 chassis_uid에 해당하는 Default값이 있는지 체크 후 서버파트 추가
            if (array_key_exists($serverEntity->getChassisInfoUID(), SERVERPART[$parttype])) {
                foreach (SERVERPART[$parttype][$serverEntity->getChassisInfoUID()] as $part) {
                    //해당 파트정보 가져오기
                    $partEntity = $this->getPartService($parttype)->getEntity($part['UID']);
                    if (!$partEntity instanceof PartEntity) {
                        throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$part['UID']} 파트정보를 찾을수 없습니다.");
                    }
                    //서버파트정보 생성
                    $formDatas = [];
                    $formDatas['serverinfo_uid'] = $serverEntity->getPK();
                    $formDatas["part_uid"] = $partEntity->getPK();
                    $formDatas['billing'] = PAYMENT['BILLING']['BASE'];
                    $formDatas['type'] = $parttype;
                    $formDatas['title'] = $partEntity->getTitle(); //파트 제목
                    $formDatas['amount'] = $partEntity->getPrice(); //파트 금액
                    $formDatas['cnt'] = $part["CNT"];
                    $formDatas['extra'] = $part["EXTRA"];
                    //action 초기화
                    $fields = array_keys($formDatas);
                    $this->getFormService()->setFormFields($fields);
                    $this->getFormService()->setFormRules('create', $fields);
                    $this->create_process($formDatas);
                }
            }
        }
    }
    public function detachFromServer(ServerEntity $serverEntity): void
    {
        //서버정보에 해당하는 ServerPart정보 상태가 기본인것 제외한 모두 회수처리.
        foreach ($this->getEntities(['serverinfo_uid' => $serverEntity->getPK(), "billing !=" => PAYMENT['BILLING']['BASE']]) as $entity) {
            $this->getPartService($entity->getType())->detachFromServerPart($entity);
            parent::delete_process($entity);
        }
    }
}
