<?php

namespace App\Services\Equipment;

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

class ServerPartService extends EquipmentService
{
    private $_form = null;
    private $_helper = null;
    public function __construct(ServerPartModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('ServerPart');
    }
    public 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->getPKField(),
                'title_field'      => $this->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->getPKField(),
                'title_field'      => $this->getTitleField(),
                'table'            => $this->model->getTable(),
                'useAutoIncrement' => $this->model->useAutoIncrement(),
                'class_path' => $this->getClassPaths(false)
            ]);
        }
        return $this->_helper;
    }
    //각 파트별 서비스
    private function getPartService(string $type): PartService
    {
        return service('part_' . strtolower($type) . 'service');
    }
    //기본 기능부분
    protected function getEntity_process(mixed $entity): ServerPartEntity
    {
        return $entity;
    }
    private function getFormDatasForServerPart(array $formDatas): array
    {
        if (!array_key_exists('serverinfo_uid', $formDatas)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 서버번호가 지정되지 않았습니다.");
        }
        if (!array_key_exists('type', $formDatas)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 부품형식이 지정되지 않았습니다.");
        }
        if (!array_key_exists('billing', $formDatas)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 청구방법이 지정되지 않았습니다.");
        }
        //서버정보 가져오기
        $serverEntity = service('equipment_serverservice')->getEntity($formDatas['serverinfo_uid']);
        if (!$serverEntity instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$formDatas['serverinfo_uid']}에 해당하는 서버정보을 찾을수 없습니다.");
        }
        //서비스정보 가져오기
        $serviceEntity = null;
        if ($serverEntity->getServiceInfoUid()) {
            $serviceEntity = service('customer_serviceservice')->getEntity($serverEntity->getServiceInfoUid());
        }
        //각 파트정보 가져오기
        $partEntity = $this->getPartService($formDatas['type'])->getEntity($formDatas['part_uid']);
        if (!$serviceEntity instanceof ServiceEntity) {
        }
        //해당 파트정보에 고객번호,서비스번호 설정
        $formDatas['clientinfo_uid']  = $serverEntity->getClientInfoUid();
        $formDatas['serviceinfo_uid'] = $serverEntity->getServiceInfoUid();
        //해당 파트정보의 Title을 서버파트정보의 Titlte 설정
        $formDatas['title'] = $partEntity->getTitle();
        //청구방식에 따른 결제일 설정
        $formDatas['billing_at'] = null;
        if ($formDatas['billing'] === PAYMENT['BILLING']['MONTH']) {
            if (!$serviceEntity instanceof ServiceEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 매월결제 상품은 서비스정보가 지정된 후 설정하실 수 있습니다.");
            }
            $formDatas['billing_at'] = $serviceEntity->getBillingAt();
        } elseif ($formDatas['billing'] === PAYMENT['BILLING']['ONETIME']) {
            if (!$serviceEntity instanceof ServiceEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 매월결제 상품은 서비스정보가 지정된 후 설정하실 수 있습니다.");
            }
            $formDatas['billing_at'] = date("Y-m-d");
        }
        return array($serverEntity, $serviceEntity, $partEntity, $formDatas);
    }
    protected function create_process(array $formDatas): CommonEntity
    {
        //서버파트 생성
        list($serverEntity, $serviceEntity, $partEntity, $formDatas) = $this->getFormDatasForServerPart($formDatas);
        $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 ($serviceEntity instanceof ServiceEntity) {
            //Billing형식이 Month이면 서비스 금액설정 호출
            if ($entity->getBilling() == PAYMENT['BILLING']['MONTH']) {
                service('customer_serviceservice')->updateAmount($serviceEntity);
            }
            //Billing형식이 Onetime이면 일회성결제 생성
            if ($entity->getBilling() == PAYMENT['BILLING']['ONETIME']) {
                service('paymentservice')->createByServerPart($entity);
            }
        }
        return $entity;
    }
    protected function modify_process($entity, array $formDatas): CommonEntity
    {
        list($serverEntity, $serviceEntity, $partEntity, $formDatas) = $this->getFormDatasForServerPart($formDatas);
        //서버파트 수정
        $oldEntity = clone $entity;
        $entity = parent::modify_process($entity, $formDatas);
        if (!$entity instanceof ServerPartEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 PaymentEntity만 가능");
        }
        //해당 파트정보가 변경
        if ($oldEntity->getPartUid() != $entity->getPartUid()) {
            $this->getPartService($entity->getType())->detachFromServerPart($oldEntity);
            $this->getPartService($entity->getType())->attachToServerPart($entity);
        }
        //서비스가 정의 되어 있으면
        if ($serviceEntity instanceof ServiceEntity) {
            //Billing형식이 Month이면 서비스 금액설정 호출
            if ($entity->getBilling() == PAYMENT['BILLING']['MONTH']) {
                service('customer_serviceservice')->updateAmount($serviceEntity);
            }
            //Billing형식이 Onetime이면 일회성결제 수정
            if ($entity->getBilling() == PAYMENT['BILLING']['ONETIME']) {
                service('paymentservice')->modifyByServerPart($oldEntity, $entity);
            }
        }
        return $entity;
    }
    protected function delete_process($entity): CommonEntity
    {
        $this->getPartService($entity->getType())->detachFromServerPart($entity);
        $entity = parent::delete_process($entity);
        if (!$entity instanceof ServerPartEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 PaymentEntity만 가능");
        }
        //서비스가 정의 되어 있으면
        //월비용 서버파트 인경우 서비스 금액 재설정
        if ($entity->getServiceInfoUid() !== null && $entity->getBilling() == PAYMENT['BILLING']['MONTH']) {
            //서비스정보 가져오기
            $serviceEntity = service('customer_serviceservice')->getEntity($entity->getServiceInfoUid());
            if (!$serviceEntity instanceof ServiceEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$entity->getServiceInfoUid()}에 해당하는 서비스정보를 찾을 수 없습니다.");
            }
            service('customer_serviceservice')->updateAmount($serviceEntity);
        }
        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"];
                    $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);
        }
    }
}
