<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\domain\channel;

use Core\service\aggregator\ChannelMessageAggregator;
use Core\service\registry\MessageRegistry;
use app\repository\channel\ChannelMessageConfigRepository;
use Core\service\BaseCoreService;

/**
 * 渠道消息服务
 * Class CoreChannelMessageService
 * @package app\service\domain\channel
 */
class CoreChannelMessageService extends BaseCoreService
{
    /**
     * 获取渠道消息配置
     * @param string $channel
     * @return array
     */
    public function config(string $channel): array
    {
        if (!$this->catalog()->hasChannel($channel)) {
            return ['code' => 1, 'msg' => 'Unknown error'];
        }

        $savedMap = [];
        foreach ($this->repository()->listByChannel($channel) as $row) {
            $messageCode = trim((string)($row['message_code'] ?? ''));
            if ($messageCode === '') {
                continue;
            }
            $savedMap[$messageCode] = $row;
        }

        $groups = $this->aggregator()->build();
        foreach ($groups as &$group) {
            $items = is_array($group['items'] ?? null) ? $group['items'] : [];
            foreach ($items as &$item) {
                $code = trim((string)($item['code'] ?? ''));
                $saved = $savedMap[$code] ?? [];
                $item['status'] = isset($saved['status']) ? (int)$saved['status'] : 0;
                $item['sort'] = isset($saved['sort']) ? (int)$saved['sort'] : 0;
                $configValue = json_decode((string)($saved['config_value'] ?? '{}'), true);
                $item['config'] = is_array($configValue) ? $configValue : [];
            }
            $group['items'] = $items;
        }
        unset($group, $item);

        return ['code' => 0, 'data' => $groups];
    }

    /**
     * 保存渠道消息配置
     * @param string $channel
     * @param array $items
     * @return array
     */
    public function save(string $channel, array $items): array
    {
        if (!$this->catalog()->hasChannel($channel)) {
            return ['code' => 1, 'msg' => 'Unknown error'];
        }

        $allowed = [];
        foreach ($this->messageRegistry()->all() as $item) {
            $code = trim((string)($item['code'] ?? ''));
            if ($code !== '') {
                $allowed[$code] = true;
            }
        }

        foreach ($items as $item) {
            if (!is_array($item)) {
                continue;
            }
            $code = trim((string)($item['code'] ?? ''));
            if ($code === '' || !isset($allowed[$code])) {
                continue;
            }
            $status = (int)($item['status'] ?? 0) ? 1 : 0;
            $sort = (int)($item['sort'] ?? 0);
            $config = is_array($item['config'] ?? null) ? $item['config'] : [];
            $this->repository()->saveConfig($channel, $code, [
                'status' => $status,
                'sort' => $sort,
                'config' => $config,
            ]);
        }

        return ['code' => 0, 'msg' => ''];
    }

    /**
     * 获取渠道目录服务实例
     * @return CoreChannelCatalogService
     */
    private function catalog(): CoreChannelCatalogService
    {
        return $this->app->make(CoreChannelCatalogService::class);
    }

    /**
     * 获取渠道消息配置仓储实例
     * @return ChannelMessageConfigRepository
     */
    private function repository(): ChannelMessageConfigRepository
    {
        return $this->app->make(ChannelMessageConfigRepository::class);
    }

    /**
     * 获取渠道消息聚合器实例
     * @return ChannelMessageAggregator
     */
    private function aggregator(): ChannelMessageAggregator
    {
        return $this->app->make(ChannelMessageAggregator::class);
    }

    /**
     * 获取消息注册表实例
     * @return MessageRegistry
     */
    private function messageRegistry(): MessageRegistry
    {
        return $this->app->make(MessageRegistry::class);
    }
}
