<?php

namespace App\Services\Equipment;

use App\Entities\Equipment\ServerEntity;
use App\Helpers\Equipment\ServerHelper;
use App\Models\Equipment\ServerModel;
use App\Services\Customer\ServiceService;
use App\Services\Equipment\EquipmentService;

class ServerService extends EquipmentService
{
    private ?ServiceService $_serviceService = null;
    private ?ServerPartService $_serverPartService = null;
    public function __construct()
    {
        parent::__construct(new ServerModel(), new ServerHelper());
        $this->addClassName('Server');
    }
    public function getFormFields(): array
    {
        return [
            "clientinfo_uid",
            "serviceinfo_uid",
            "code",
            "type",
            "title",
            "price",
            "manufactur_at",
            "format_at",
            "status",
        ];
    }
    public function getFormFilters(): array
    {
        return [
            "clientinfo_uid",
            "serviceinfo_uid",
            "type",
            "title",
            "status"
        ];
    }
    public function getIndexFields(): array
    {
        return [
            'clientinfo_uid',
            'serviceinfo_uid',
            "type",
            'title',
            'price',
            'manufactur_at',
            "format_at",
            'status',
        ];
    }
    public function getIndexFilters(): array
    {
        return [
            'clientinfo_uid',
            'serviceinfo_uid',
            'type',
            "title",
            'status'
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['clientinfo_uid', 'status'];
    }
    final public function getServiceService(): ServiceService
    {
        if ($this->_serviceService === null) {
            $this->_serviceService = new ServiceService();
        }
        return $this->_serviceService;
    }
    final public function getServerPartService(): ServerPartService
    {
        if (!$this->_serverPartService) {
            $this->_serverPartService = new ServerPartService();
        }
        return $this->_serverPartService;
    }

    //partEntity 정보 추가
    protected function getEntity_process(mixed $entity): ServerEntity
    {
        if (!$entity instanceof ServerEntity) {
            throw new \Exception(__METHOD__ . "에서 형식오류:ServerEntity만 허용됩니다.");
        }
        return $entity;
    }
    final public function getTotalAmount(int $uid): int
    {
        $entity = $this->getEntity($uid);
        if (!$entity instanceof ServerEntity) {
            throw new \Exception(__METHOD__ . "에서 오류발생:[{$uid}]에 대한 서버정보를 찾을수 없습니다.");
        }
        $total_amount = $entity->getPrice(); //서버금액(price)
        //해당 서비스(서버) 관련 결제방식(Billing)이 Month인 ServerPart 전체를 다시 검사하여 월청구액을 합산한다.
        foreach ($this->getServerPartService()->getEntities(['serverinfo_uid' => $entity->getPK()]) as $serverPartEntity) {
            if ($serverPartEntity->getBilling() === PAYMENT['BILLING']['MONTH']) {
                $total_amount += $serverPartEntity->getAmount();
            }
        }
        return $total_amount;
    }
    //create용 장비코드 마지막번호 가져오기
    final public function getLastestCode(string $format, int $default): string
    {
        return $this->getModel()->getLastestCode($format, $default);
    }
    final public function codeCheck(array $formDatas)
    {
        //코드 패턴체크
        $pattern = env("Server.Prefix.code.pattern", false);
        if (!$pattern) {
            throw new \Exception(__METHOD__ . "에서 code의 prefix[Server.Prefix.code.pattern]가 정의되지 않았습니다.");
        }
        if (!array_key_exists('code', $formDatas)) {
            throw new \Exception("Server코드가 정의되지 않았습니다");
        }
        if (!preg_match($pattern, $formDatas['code'])) {
            throw new \Exception("Server코드[{$formDatas['code']}의 형식이 맞지않습니다");
        }
    }
    //기본 기능부분
    //FieldForm관련용
    public function getFormOption(string $field, $options = []): array
    {
        switch ($field) {
            case 'serviceinfo_uid':
                $options = $this->getServiceService()->getEntities();
                break;
            default:
                $options = parent::getFormOption($field, $options);
                break;
        }
        return $options;
    }
    public function setFormData(string $field, array $requestDatas, array $formDatas): array
    {
        switch ($field) {
            case 'CPU':
            case 'RAM':
                $formDatas[$field] = $requestDatas[$field] ?? null;
                $formDatas["{$field}_cnt"] = $requestDatas["{$field}_cnt"] ?? null;
                break;
            case 'DISK':
                $formDatas[$field] = $requestDatas[$field] ?? null;
                $formDatas["{$field}_cnt"] = $requestDatas["{$field}_cnt"] ?? null;
                $formDatas["{$field}_extra"] = $requestDatas["{$field}_extra"] ?? null;
                break;
            default:
                $formDatas = parent::setFormData($field, $requestDatas, $formDatas);
        }
        return $formDatas;
    }
    // 수정
    public function modify(mixed $entity, array $formDatas): ServerEntity
    {
        return parent::modify($entity, $formDatas);
    }
    //삭제
    public function delete(mixed $entity): ServerEntity
    {
        //기존 ServerPart정보 삭제
        foreach ($this->getServerPartService()->getEntities(['serverinfo_uid' => $entity->getPK()]) as $serverPartEntity) {
            $this->getServerPartService()->delete($serverPartEntity);
        }
        return parent::delete($entity);
    }
    //List 검색용
    //OrderBy 처리
    public function setOrderBy(mixed $field = null, mixed $value = null): void
    {
        $this->getModel()->orderBy("code ASC,title ASC");
        parent::setOrderBy($field, $value);
    }
}
