package vip.xiaonuo.weixin.gongzhong.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.coldchain.modular.alarmuser.entity.AlarmUser;
import vip.xiaonuo.coldchain.modular.alarmuser.service.AlarmUserService;
import vip.xiaonuo.coldchain.modular.push.entity.WeChatUser;
import vip.xiaonuo.coldchain.modular.push.utils.PushUtil;
import vip.xiaonuo.dev.modular.config.service.DevConfigService;

import java.util.List;
import java.util.Objects;

@CrossOrigin
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wx/mp")
public class WxMpController {

    private final WxMpService wxMpService;
    private final WxMpMessageRouter wxMpMessageRouter;
    private final AlarmUserService alarmUserService;
    private final DevConfigService devConfigService;

    @GetMapping("/auth")
    public String check(@RequestParam String signature, @RequestParam String timestamp, @RequestParam String nonce, @RequestParam String echostr) {
        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);
        boolean checkSignature = wxMpService.checkSignature(timestamp, nonce, signature);
        log.info("\n校验结果：{}", checkSignature);
        return echostr;
    }

    @SneakyThrows
    @GetMapping("/auth/page")
    public void check(@RequestParam(required = false) String code, @RequestParam(required = false) String state, HttpServletResponse response) {
        log.info("\n接收到来自微信服务器的授权消息：code={}，state={}", code, state);
        if (StrUtil.isBlank(code)) {
            response.getWriter().println("授权失败，请重新授权");
            return;
        }

        WeChatUser weChatUser = PushUtil.getUserInfo(code);
        log.info("获取用户信息:{}", JSONUtil.toJsonStr(weChatUser));

        List<AlarmUser> userList = alarmUserService.getByOpenId(weChatUser.getOpenid());
        AlarmUser alarmUser;

        if (CollUtil.isNotEmpty(userList)) {
            //检查用户的组织机构
            long count = userList.stream().filter(x -> !Objects.equals(x.getCreateOrg(), "-1")).count();
            if (count > 0) {
                //进入授权页面
                String redirect = devConfigService.getValueByKey("wx_front_authed_page");
                if (StrUtil.isNotBlank(redirect)) {
                    response.sendRedirect(redirect);
                } else {
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().println("您已授权！\\^o^/");
                }
                return;
            }
            alarmUser = userList.get(0);
        } else {
            //没有用户信息则创建用户
            alarmUser = alarmUserService.subscribe(weChatUser.getOpenid());
        }

        String redirect = devConfigService.getValueByKey("wx_front_not_auth_page") + "?id=" + alarmUser.getId();
        log.info("进入用户授权页面 {}", redirect);
        response.sendRedirect(redirect);
    }


    @SneakyThrows
    @PostMapping("/auth")
    public String wxEventListener(@RequestBody String param,
                            @RequestParam(required = false) String signature,
                            @RequestParam(required = false) String timestamp,
                            @RequestParam(required = false) String nonce) {
        log.info("\n接收微信事件：[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                signature, timestamp, nonce, param);

        // 微信时间在wxMpMessageRouter中处理
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(param);
        WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
        // 将响应消息转换为xml格式返回
        return outMessage == null ? "" : outMessage.toXml();
    }
}
