<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\WxserverAccount;
use cores\BaseController;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class Wxserver extends BaseController
{
    public function index()
    {
        $obj = new \app\common\library\wxserver\Server();
        $data = $obj->getAuditStatus('wxe3ed157849bd07b5', 428711396);
        return $this->renderSuccess($data);
    }

    public function verifyTicket()
    {
        $xmlData = file_get_contents("php://input");
        $obj = new \app\common\library\wxserver\Server();
        $obj->getVerifyTicket($xmlData);
        echo 'success';
    }

    /**
     * @notes:授权回调
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public function redirect()
    {
        $authorization_code = $this->request->get('auth_code');
        if ($authorization_code) {
            $obj = new \app\common\library\wxserver\Server();
            $obj->authorizationInfo($authorization_code);
        }
        echo 'success';
    }

    public function callback()
    {
        $time = date('Y-m-d H:i:s');
        Db::table('yoshop_wx_server')->insertGetId(['content' => '推送开始', 'created_at' => $time]);
        $query = $this->request->query();
        $xmlData = file_get_contents("php://input");
        if ($query) {
            Db::table('yoshop_wx_server')->insertGetId(['content' => $query, 'created_at' => $time]);
            $arr = explode('/', $query);
            $appid = end($arr);
            if ($xmlData && $appid) {
                Db::table('yoshop_wx_server')->insertGetId(['content' => $xmlData, 'created_at' => $time]);
                $obj = new \app\common\library\wxserver\Server();
                $data = $obj->decryptXml($xmlData);
                if (!empty($data['MsgType']) && $data['MsgType'] == 'event' && !empty($data['Event'])) {
                    $up = [];
                    if ($data['Event'] == 'weapp_audit_success') {
                        $up['audit_status'] = 2;
                    } elseif ($data['Event'] == 'weapp_audit_fail') {
                        $up['audit_status'] = 3;
                    } elseif ($data['Event'] == 'weapp_audit_delay') {
                        $up['audit_status'] = 4;
                    }
                    if (!empty($data['Reason'])) {
                        $up['audit_reason'] = $data['Reason'];
                    }
                    if ($up) {
                        $model = new WxserverAccount();
                        $model->update($up, ['appid' => $appid]);
                    }
                }
            }
        }
        echo 'success';
    }
}