<?php

namespace app\controller\admin;

use app\extra\basic\Base;
use app\extra\tools\OssRegionExtend;
use app\middleware\AuthMiddleware;
use app\model\system\SystemConfig;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Route;
use support\Request;
use support\Response;
use LinFly\Annotation\Route\Middleware;


#[Controller(prefix: "/api/config"),Middleware(AuthMiddleware::class)]
class Config extends Base
{


    /**
     * 获取配置信息
     */
    #[Route(path: "list",methods: "get")]
    public function getConfigList(Request $request): Response
    {
        try {
            $type = $request->get("type","service");
            $data = (new SystemConfig)->where("type",$type)->where("status",1)->field("name,value")->select()->toArray();
            $result = [];
            foreach ($data as $item) {
                $result[$item['name']] = $item['value'];
            }
            if ($type == "sms") {
                $result['channel'] = $this->getSmsChannel();
                $result['login_sms'] = '您的验证码为：${code}，请勿泄露于他人！';
            }
            return successTrans("success.data",$result);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    /**
     * 保存通用配置
     * @param Request $request
     * @return Response
     */
    #[Route(path: "save",methods: "post")]
    public function setConfigData(Request $request): Response
    {
        try {
            $param = $request->post();
            if (isset($param['data']['channel'])) unset($param['data']['channel']);
            foreach ($param['data'] as $k => $v){
                if(is_array($v)) $v = implode(",",$v);
                sConf($param['type'].'.'.$k, $v);
            }
            return successTrans("success.data",[]);
        } catch (\Throwable $exception){
            return error($exception->getMessage());
        }
    }

    /**
     * 获取地区列表
     * @return Response
     */
    #[Route(path: "regin",methods: "get")]
    public function getConfigRegin(): Response
    {
        try {
            return successTrans(100010,[
                "oss"       => OssRegionExtend::OssRegion(),
                "cos"       => OssRegionExtend::CosRegion(),
                "qiniu"     => OssRegionExtend::QiniuRegion(),
            ]);
        } catch (\Exception $exception) {
            return error($exception->getMessage());
        }
    }

}