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

namespace app\api\controller\wechat;

use app\Controller;
use app\common\library\wechat\Wechat;
use think\facade\Request;
use xzncit\core\message\Raw;
use xzncit\core\Utils;
use app\common\service\wechat\Message;

/**
 * @package app\api\controller\wechat
 * @class Index
 * @author xzncit 2024-02-19
 */
class Index extends Controller {

    /**
     * 公众号推送接收
     * @return string
     */
    public function index(){
        try{
            $response = Wechat::create("wechat")->server->push(function ($data){
                $data = Utils::lowerCase($data ?? []);
                if(empty($data["msgtype"])){
                    throw new \Exception("empty msgtype.",0);
                }

                $message = new Message($data);
                $method = $data["msgtype"];
                if(!empty($method) && method_exists($message,$method)){
                    return $message->$method();
                }else{
                    return new Raw("success");
                }
            });

            return $response->send();
        }catch (\Exception $ex){
            return $ex->getMessage();
        }
    }

    /**
     * @return \think\response\Json
     * @throws \Exception
     */
    public function config(){
        return returnAjax("msg:ok",1,Wechat::create("wechat")->script->getJsSign(Request::param("url","","trim")));
    }

}