<?php

namespace app\api\controller;

use app\api\service\TokenService;
use app\model\project\User as userModel;
use think\facade\Log;
use think\Request;
use app\api\validate\ArticleValidate;
use app\BaseController;
use app\model\ArticleModel;
use app\api\service\WeChatLoginService;
use think\facade\Cache;
use app\model\project\User;


class Wecaht extends BaseController
{


    public function index()
    {

        $body = file_get_contents('php://input');
        $simpleXml = simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA);
        $json = json_encode($simpleXml);
        $array = json_decode($json, true); // true表示转为关联数组
        Log::write('微信登录事件');
        Log::write($array);
        if ($array['Event'] == 'SCAN' || $array['Event'] == 'subscribe') {

            $EventKey = $array['EventKey'];
            if ($array['Event'] == 'subscribe') {
                $EventKeys = explode('_', $array['EventKey']);
                $EventKey = $EventKeys[1] . '_' . $EventKeys[2];
            }
            $cachekey = Cache::get($EventKey);
            if ($cachekey == $array['Ticket']) {
                $openid = $array['FromUserName'];
                Log::write('扫描成功');
                Cache::set($EventKey . '_wxopenid', $openid, 3000);

//                $user = User::where('wx_openid', $openid)->find();
//                if (empty($user)) {
//                    $user['wx_openid'] = $openid;
//                    $user['is_del'] = 1;
//                    $user['create_time'] = time();
//                    $user['headico'] = vconfig('default_user') ?? null;
//                    userModel::insert($user);
//                }

            }
        }
//        // 配置 Token（需与微信公众号后台设置一致）
//        define("WX_TOKEN", "YOUR_TOKEN_HERE");
//        // 处理微信服务器发送的 GET 验证请求
//        if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['echostr'])) {
//            $signature = $_GET['signature'] ?? '';
//            $timestamp = $_GET['timestamp'] ?? '';
//            $nonce = $_GET['nonce'] ?? '';
//            $echostr = $_GET['echostr'] ?? '';
//
//            // 参数缺失检测
//            if (empty($signature) || empty($timestamp) || empty($nonce) || empty($echostr)) {
//                exit('Invalid Request: Missing Parameters');
//            }
//
//            // 1. 生成本地签名
//            $tmpArr = [WX_TOKEN, $timestamp, $nonce];
//            sort($tmpArr, SORT_STRING); // 字典序排序
//            $tmpStr = implode('', $tmpArr); // 拼接字符串
//            $localSign = sha1($tmpStr); // SHA1 加密
//
//            // 2. 验证签名并返回 echostr
//            if ($localSign == $signature) {
//                header('Content-Type: text/plain; charset=utf-8');
//                exit($echostr);
//            } else {
//                exit('Signature Verification Failed');
//            }
//            return true;
//        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = 'VtUEf2MvC0dMMaDGwMT8';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    //检车微信openid是否登录 2秒轮询
    public function checkwxlogin()
    {
        $param = $this->request->post();
        $cachekey = $param['cachekey'];
        $openid = Cache::get($cachekey . '_wxopenid');
        if (empty($openid)) {
            return $this->returnMsg("等待用户扫码关注", 1);
        }
        $user = User::where('wx_openid', $openid)->find();
        if (empty($user)) {
            $redata = ['token' => '', 'expires_in' => 0, 'user_id' => 0, 'is_mobile' => 0];
        } elseif ($user) {
            if ($user['status'] != 1) {
                return $this->returnMsg('账号禁止登录', 0);
            }
            if ($user['is_del'] != 0) {
                return $this->returnMsg('账号已删除', 0);
            }
            $token = TokenService::generateToken($user['id'], $user->toArray());
            $update['token'] = $token;
            $update['last_login_time'] = time();
            User::where(['id' => $user['id']])->update($update);
            $redata = ['token' => $token, 'expires_in' => TokenService::EXPIRE, 'user_id' => $user['id'], 'is_mobile' => 1];

        }
        return $this->returnMsg("success", 1, $redata);
    }

    //生成二维码
    public function createwxewm()
    {
        try {
            $data = WeChatLoginService::createerwm();
        } catch (\Exception $e) {
            return $this->returnMsg($e->getMessage());
        }
        return $this->returnMsg("success", 1, $data);

    }

}