<?php

namespace App\Services\Customer;

use App\DTOs\Customer\ClientDTO;
use App\Entities\Customer\ClientEntity;
use App\Entities\PaymentEntity;
use App\Forms\Customer\ClientForm;
use App\Helpers\Customer\ClientHelper;
use App\Models\Customer\ClientModel;
use RuntimeException;

class ClientService extends CustomerService
{
    private $_form = null;
    private $_helper = null;
    public function __construct(ClientModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('Client');
    }
    protected function getDTOClass(): string
    {
        return ClientDTO::class;
    }
    public function createDTO(array $formDatas): ClientDTO
    {
        return new ClientDTO($formDatas);
    }
    public function getEntityClass(): string
    {
        return ClientEntity::class;
    }
    public function getFormService(): ClientForm
    {
        if ($this->_form === null) {
            $this->_form = new ClientForm();
            $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(): ClientHelper
    {
        if ($this->_helper === null) {
            $this->_helper = new ClientHelper();
            $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 = [
            'site',
            'name',
            'email',
            'phone',
            'role',
        ];
        $filters = [
            'site',
            'role',
            'status',
        ];
        $indexFilter     = $filters;
        $batchjobFilters = ['site', 'role', 'status'];
        switch ($action) {
            case 'create':
            case 'create_form':
                break;
            case 'modify':
            case 'modify_form':
                $fields = [...$fields, 'status'];
                break;
            case 'view':
                $fields = [...$fields, 'status', 'created_at'];
                break;
            case 'index':
            case 'download':
                $fields = [
                    'site',
                    'name',
                    'email',
                    'phone',
                    'role',
                    'account_balance',
                    'coupon_balance',
                    'point_balance',
                    'status',
                    'created_at',
                    'updated_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);
    }
    final public function updateBalance(int|ClientEntity $uid, string $title, string $key, int $value, string $status): ClientEntity
    {
        $entity = is_int($uid) ? $this->getEntity($uid) : $uid;
        if (!$entity instanceof ClientEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$uid}에 해당하는 서비스정보를 찾을수 없습니다.");
        }

        $calculatedValue = null;
        $balance = 0;
        $title   = "";
        $field   = "";
        switch ($key) {
            case PAYMENT['PAY']['ACCOUNT']:
                $balance = $entity->getAccountBalance();
                $title = "예치금";
                $field = "account_balance";
                break;
            case PAYMENT['PAY']['COUPON']:
                $balance = $entity->getCouponBalance();
                $title = "쿠폰";
                $field = "coupon_balance";
                break;
            case PAYMENT['PAY']['POINT']:
                $balance = $entity->getPointBalance();
                $title = "포인트";
                $field = "point_balance";
                break;
        }
        //입금,추가 처리
        if ($status === STATUS['DEPOSIT']) {
            $calculatedValue = $balance + $value;
        }
        //출금,사용 처리
        if ($status === STATUS['WITHDRAWAL']) {
            if ($balance < $value) {
                throw new RuntimeException(sprintf(
                    "%s 에서 오류발생: %s 고객의 %s[ %s ]이/가 사용한 %s 금액/수[ %s ]이/가 부족합니다.",
                    static::class . '->' . __FUNCTION__,
                    $entity->getTitle(),
                    $title,
                    number_format($balance),
                    $title,
                    number_format($value)
                ));
            }
            $calculatedValue = $balance - $value;
        }
        if (!is_int($calculatedValue) || $calculatedValue < 0) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 {$entity->getTitle()} 고객 {$title}의 계산결과 값이 NULL이거나 0보다 작은 값입니다.");
        }
        //balance 수정
        $formDatas = [$field => $calculatedValue, 'status' => $status];
        return parent::modify_process($entity, $formDatas);
    }
    //pay방식에따른 결제처리
    final public function updateWalletByPayment(PaymentEntity $entity): void
    {
        $service = null;
        switch ($entity->getPay()) {
            case PAYMENT['PAY']['ACCOUNT']:
                $service = service('customer_wallet_accountservice');
                break;
            case PAYMENT['PAY']['COUPON']:
                $service = service('customer_wallet_couponservice');
                break;
            case PAYMENT['PAY']['POINT']:
                $service = service('customer_wallet_pointservice');
                break;
            default:
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$entity->getPay()}는 지정되지 않은 지불방식입니다.");
                // break;
        }
        $formDatas = [
            'clientinfo_uid' => $entity->getClientInfoUID(),
            'bank'           => '결제차감',
            'title'          => $entity->getTitle(),
            'alias'          => '결제차감',
            'issue_at'       => date('Y-m-d'),
            'amount'       => $entity->getAmount(),
            'status'       => STATUS['WITHDRAWAL'],
        ];
        $fields = array_keys($formDatas);
        $service->getFormService()->setFormFields($fields);
        $service->getFormService()->setFormRules('create', $fields);
        $service->create_process($formDatas);
    }
    //기본 기능부분
    protected function getEntity_process(mixed $entity): ClientEntity
    {
        return $entity;
    }
    protected function create_process(array $formDatas): ClientEntity
    {
        return parent::create_process($formDatas);
    }
    protected function modify_process($entity, array $formDatas): ClientEntity
    {
        return parent::modify_process($entity, $formDatas);
    }
    //List 검색용
    //FormFilter 조건절 처리
    //검색어조건절처리
    public function setSearchWord(string $word): void
    {
        $this->model->orLike($this->model->getTable() . '.alias', $word, 'both');
        parent::setSearchWord($word);
    }
    //OrderBy 처리
    public function setOrderBy(mixed $field = null, mixed $value = null): void
    {
        $this->model->orderBy("site ASC,name ASC");
        parent::setOrderBy($field, $value);
    }
}
