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

use app\model\ChannelMessageConfig;
use app\repository\BaseRepository;


/**
 * Channel Message Config Repository
 * @package app\repository\channel
 */
class ChannelMessageConfigRepository extends BaseRepository
{

    /**
     * 根据渠道获取消息配置列表
     * @param string $channel 渠道标识
     * @return array
     */
    public function listByChannel(string $channel): array
    {
        return ChannelMessageConfig::where('channel', $channel)->order('sort', 'asc')->order('id', 'asc')->select()->toArray();
    }


    /**
     * 保存消息配置
     * @param string $channel
     * @param string $messageCode
     * @param array $data
     * @return void
     */
    public function saveConfig(string $channel, string $messageCode, array $data): void
    {
        $row = ChannelMessageConfig::where([
            'channel' => $channel,
            'message_code' => $messageCode,
        ])->find();

        if (!$row) {
            $row = new ChannelMessageConfig();
            $row->channel = $channel;
            $row->message_code = $messageCode;
        }

        $row->status = (int)($data['status'] ?? 0);
        $row->sort = (int)($data['sort'] ?? 0);
        $row->config_value = json_encode($data['config'] ?? [], JSON_UNESCAPED_UNICODE);
        $row->save();
    }
}