<?php

namespace App\Services\Equipment;

use App\Entities\Customer\ServiceEntity;
use App\Entities\Equipment\ServerEntity;
use App\Helpers\Equipment\ServerHelper;
use App\Interfaces\Customer\ServiceInterface;
use App\Models\Equipment\ServerModel;
use App\Services\Customer\ServiceService;
use App\Services\Equipment\EquipmentService;
use App\Services\Equipment\ServerPartService;
use App\Services\Part\IPService;
use App\Services\Part\SWITCHService;

class ServerService extends EquipmentService implements ServiceInterface
{
    private ?ServiceService $_serviceService = null;
    private ?ServerPartService $_serverPartService = null;
    private ?IPService $_ipService = null;
    private ?SWITCHService $_switchService = null;
    public function __construct()
    {
        parent::__construct(new ServerModel(), new ServerHelper());
        $this->addClassName('Server');
    }
    public function getFormFields(): array
    {
        return [
            "code",
            "type",
            "switch",
            "ip",
            "os",
            "title",
            "price",
            "manufactur_at",
        ];
    }
    public function getFormFilters(): array
    {
        return [
            "type",
            "os",
            "title",
            "status"
        ];
    }
    public function getIndexFields(): array
    {
        return [
            'clientinfo_uid',
            'serviceinfo_uid',
            "type",
            "switch",
            "ip",
            "os",
            'title',
            'price',
            'manufactur_at',
            "format_at",
            'status',
        ];
    }
    public function getIndexFilters(): array
    {
        return [
            'clientinfo_uid',
            'serviceinfo_uid',
            'type',
            "os",
            "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 getIPService(): IPService
    {
        if (!$this->_ipService) {
            $this->_ipService = new IPService();
        }
        return $this->_ipService;
    }
    final public function getSwitchService(): SWITCHService
    {
        if (!$this->_switchService) {
            $this->_switchService = new SWITCHService();
        }
        return $this->_switchService;
    }
    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 getTotalServiceCount(array $where = []): array
    {
        $totalCounts = [
            'chiba_summary' => 0,
            'tokyo_summary' => 0,
            'all_summary' => 0,
            'normal' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'defence' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'dedicated' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'vpn' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'event' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'test' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'alternative' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
        ];
        $rows = $this->getModel()
            ->select("serverinfo.type,
                COUNT(CASE WHEN serviceinfo.location = 'chiba' THEN 1 END) AS chiba,
                COUNT(CASE WHEN serviceinfo.location = 'tokyo' THEN 1 END) AS tokyo,
                COUNT(CASE WHEN serviceinfo.location IN ('chiba', 'tokyo') THEN 1 END) AS summary")
            ->join('serviceinfo', 'serviceinfo.uid = serverinfo.serviceinfo_uid') // JOIN 조건
            ->where($where)
            ->groupBy('serverinfo.type')
            ->get()
            ->getResult();
        foreach ($rows as $row) {
            $totalCounts[$row->type]['chiba'] = $row->chiba;
            $totalCounts[$row->type]['tokyo'] = $row->tokyo;
            $totalCounts[$row->type]['summary'] = $row->summary;
            $totalCounts['chiba_summary'] += $row->chiba;
            $totalCounts['tokyo_summary'] += $row->tokyo;
            $totalCounts['all_summary'] = $totalCounts['chiba_summary'] + $totalCounts['tokyo_summary'];
        }
        // dd($totalCounts);
        return $totalCounts;
    }
    //서비스정보 설정
    public function setService(string $action, ServiceEntity $serviceEntity, array $serviceFormDatas): ServiceEntity
    {
        switch ($action) {
            case 'create':
                if (!array_key_exists('serverinfo_uid', $serviceFormDatas)) {
                    throw new \Exception(__METHOD__ . "에서 {$action}오류발생: 서버가 지정되지 않았습니다.\n" . var_export($serviceFormDatas, true));
                }
                $entity = $this->getEntity($serviceFormDatas['serverinfo_uid']);
                if (!$entity instanceof ServerEntity || $entity->getStatus() != STATUS['AVAILABLE']) {
                    throw new \Exception(__METHOD__ . "에서 {$action}오류발생: {$serviceFormDatas['serverinfo_uid']}에 대한 서버정보를 찾을수 없거나, 사용가능 서버가 아닙니다.");
                }
                $formDatas = [];
                //대체서버 추가용인지 확인
                if (array_key_exists('type', $serviceFormDatas)) {
                    $formDatas['type'] = $serviceFormDatas['type'];
                }
                $formDatas['clientinfo_uid']  = $serviceEntity->getClientInfoUID();
                $formDatas['serviceinfo_uid'] = $serviceEntity->getPK();
                $formDatas['status'] = STATUS['OCCUPIED'];
                $entity = parent::modify($entity, $formDatas);
                break;
            case 'modify':
                $entity = $serviceEntity->getServerEntity();
                if (!$entity instanceof ServerEntity) {
                    throw new \Exception(__METHOD__ . "에서 {$action}오류발생: {$serviceFormDatas['serverinfo_uid']}에 대한 서버정보를 찾을수 없거나, 사용가능 서버가 아닙니다.");
                }
                $formDatas = [];
                if (array_key_exists('type', $serviceFormDatas)) {
                    $formDatas['type'] = $serviceFormDatas['type'];
                }
                $entity = parent::modify($entity, $formDatas);
                break;
            case 'delete':
                if (!array_key_exists('serverinfo_uid', $serviceFormDatas)) {
                    throw new \Exception(__METHOD__ . "에서 {$action}오류발생: 서버가 지정되지 않았습니다.");
                }
                $entity = $this->getEntity($serviceFormDatas['serverinfo_uid']);
                if (!$entity instanceof ServerEntity) {
                    throw new \Exception(__METHOD__ . "에서 {$action}오류발생: 해지 할 서버정보를 찾을수 없습니다.");
                }
                $formDatas = [];
                $formDatas['clientinfo_uid']  = null;
                $formDatas['serviceinfo_uid'] = null;
                $formDatas['format_at'] = date("Y-m-d");
                $formDatas['status'] = STATUS['AVAILABLE'];
                $entity = parent::modify($entity, $formDatas);
                //서버파트정보해지
                $this->getServerPartService()->setServer('delete', $entity, []);
                break;
            default:
                throw new \Exception(__METHOD__ . "에서 오류발생:{$action}은 정의되지 않은 작업입니다.");
                // break;
        }
        return $serviceEntity->setServerEntity($entity);
    }
    //기본 기능부분
    //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 create(array $formDatas): ServerEntity
    {
        //서버정보 생성
        $entity = parent::create($formDatas);
        //서버의 Type별 서버파트정보등록(서버파트연결 자동등록용)
        $entity = $this->getServerPartService()->setServer('create', $entity, []);
        if ($entity->getSwitch() !== null) {  //Switch가 정의되어 있으면
            $entity = $this->getSwitchService()->setServer('create', $entity, []);
        }
        // dd($entity);
        if ($entity->getIP() !== null) {  //IP가 정의되어 있으면
            $entity = $this->getIPService()->setServer('create', $entity, []);
        }
        return $entity;
    }
    //수정
    public function modify(mixed $entity, array $formDatas): ServerEntity
    {
        //수정전 정보
        $oldEntity = clone $entity; //반드시 clone 할것
        //ip값이 없으면 null처리
        if (array_key_exists('ip', $formDatas) && !$formDatas['ip']) {
            $formDatas['ip'] = null;
        }
        //서버정보 수정
        $entity = parent::modify($entity, $formDatas);
        //서비스가 연결되어 있고 대체서버가 아니면, 서비스정보수정(청구액수정)
        if ($entity->getServiceInfoUID() !== null && $entity->getType() !== "alternative") {
            $this->getServiceService()->setAmount($this->getServiceService()->getEntity($entity->getServiceInfoUID()));
        }
        //Switch정보 수정
        if ($oldEntity->getSwitch() !== null) { //기존 서버정보에 Switch가 정의되어 있으면
            $oldEntity = $this->getSwitchService()->setServer('delete', $oldEntity, []);
        }
        if ($entity->getSwitch() !== null) { //Switch가 정의되어 있으면
            $entity = $this->getSwitchService()->setServer('create', $entity, []);
        }
        //IP정보 수정
        if ($oldEntity->getIP() !== null) { //기존 서버정보에 IP가 정의되어 있으면
            $oldEntity = $this->getIPService()->setServer('delete', $oldEntity, []);
        }
        if ($entity->getIP() !== null) { //IP가 정의되어 있으면
            $entity = $this->getIPService()->setServer('create', $entity, []);
        }
        return $entity;
    }
    //삭제
    public function delete(mixed $entity): ServerEntity
    {
        //서비스가 연결되어있거나 , 사용가능 상태가 아니면 삭제불가
        if ($entity->getServiceInfoUID() !== null || $entity->getStatus() !== STATUS['AVAILABLE']) {
            throw new \Exception("서비스중인 서버는 삭제하실수 없습니다.");
        }
        //서버파트정보해지
        $entity = $this->getServerPartService()->setServer('delete', $entity, []);
        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);
    }
}
