<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\adminapi\service;

use think\facade\Request;
use app\common\service\Config as ConfigService;
use app\common\model\SmsTemplate as SmsTemplateModel;

/**
 * @package app\adminapi\service
 * @class Message
 * @author xzncit 2024-01-23
 */
class Message {

    /**
     * 列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params=[]){
        $array           = [];
        $array["total"]  = SmsTemplateModel::count();
        $result          = SmsTemplateModel::page($params["current"]??1,$params["size"]??10)->select()->toArray();
        $array["list"]   = [];
        foreach($result as $key=>$value){
            $array["list"][$key]            = $value;
        }

        return $array;
    }

    /**
     * 详情
     * @param $id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        $type = ConfigService::getArray("sms.type");
        $row = SmsTemplateModel::where("id",$id)->find();
        if($type == "tencent"){
            $matches = [];
            preg_match_all('/\${(.*?)}/im',$row["template_content"]??"",$matches);
            foreach($matches[0] as $k=>$v){
                $row["template_content"] = str_replace($v,'{'.($k+1).'}',$row["template_content"]);
            }
        }

        return $row;
    }

    /**
     * 保存
     * @param array $params
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function save($params=[]){
        if(!SmsTemplateModel::where("id",$params["id"]??0)->count()){
            throw new \Exception("您要编辑的短信模板不存在",0);
        }

        return SmsTemplateModel::where("id",$params["id"])->save([
            "status"        => $params["status"],
            "template_id"   => $params["template_id"]
        ]);
    }

    /**
     * 短信设置
     * @param array $params
     * @return array|bool|mixed|null
     * @throws \think\db\exception\DbException
     */
    public static function setting($params=[]){
        if(Request::isGet()){
            return ConfigService::getArray("sms");
        }

        return ConfigService::save($params,"sms");
    }

}