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

use Core\service\registry\MessageRegistry;
use app\repository\channel\ChannelRepository;
use app\service\api\BaseApiService;


/**
 * Weapp Subscribe Service
 * @package app\service\api\channel
 */
class WeappSubscribeService extends BaseApiService
{

    /**
     * 获取订阅模板列表
     * @return array
     */
    public function templates(): array
    {

        $configs = $this->channelRepository()->listNotifyConfigs('weapp');


        $messageMap = [];
        foreach ($this->messageRegistry()->all() as $msg) {
            $messageMap[(string)($msg['code'] ?? '')] = $msg;
        }

        $templates = [];
        foreach ($configs as $row) {

            if ((int)($row['status'] ?? 0) !== 1) {
                continue;
            }

            $driver = (string)($row['driver'] ?? '');
            if (strpos($driver, '.weapp_subscribe') === false) {
                continue;
            }

            $config = json_decode((string)($row['config_value'] ?? '{}'), true);
            $config = is_array($config) ? $config : [];
            $templateId = (string)($config['template_id'] ?? '');
            if ($templateId === '') {
                continue;
            }


            $scene = explode('.', $driver, 2)[0] ?? '';


            $messageCode = '';
            $messageDef = null;
            foreach ($messageMap as $code => $def) {
                $defScene = (string)($def['scene'] ?? '');
                $defDrivers = $def['driver_types'] ?? [];
                if ($defScene === $scene && in_array('weapp_subscribe', $defDrivers, true)) {
                    $messageCode = $code;
                    $messageDef = $def;
                    break;
                }
            }

            $templates[] = [
                'code' => $messageCode,
                'title' => $messageDef['title'] ?? $driver,
                'group' => $messageDef['group'] ?? '',
                'scene' => $scene,
                'template_id' => $templateId,
                'page' => (string)($config['page'] ?? ''),
                'sort' => (int)($row['sort'] ?? 0),
            ];
        }


        usort($templates, static function (array $a, array $b): int {
            return $a['sort'] - $b['sort'];
        });

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

    /**
     * 获取渠道仓储实例
     * @return ChannelRepository
     */
    private function channelRepository(): ChannelRepository
    {
        return $this->app->make(ChannelRepository::class);
    }

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