package com.cyksj.web.controller.manage.gzh;

import cn.hutool.core.util.StrUtil;
import com.cyksj.common.util.IoKit;
import com.cyksj.common.util.StringUtil;
import com.cyksj.common.util.Xmls;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.dto.MsgEvent;
import com.cyksj.service.gzh.GzhService;
import com.cyksj.service.wechat.WeChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/*
 *项目名: netflix
 *文件名: GzhController
 *创建者: JavaZou
 *创建时间:2023/1/13 16:50
 */
@RestController
@RequestMapping("/manage/gzh")
@RequiredArgsConstructor
@Slf4j
public class GzhController {
	private final HttpServletRequest request;

	private final GzhService gzhService;

	private final WeChatService weChatService;

	@RequestMapping(value = "/msg/notify", method = {RequestMethod.GET, RequestMethod.POST})
	public String msgNotify(@RequestParam(value = "echostr", required = false) String echoStr) throws IOException {
		if (StrUtil.endWithIgnoreCase(request.getMethod(), RequestMethod.GET.name())) {
			if (StrUtil.isBlank(echoStr)) {
				return StrUtil.EMPTY;
			}
			//验证消息推送URL是否正确
			return echoStr;
		}

		String content = IoKit.toString(request.getInputStream(), IoKit.Charsets.UTF_8);
		log.info("公众号消息推送通知: \n{}", content);

		if (StringUtils.isBlank(content)) {
			return StringUtil.EMPTY;
		}
		MsgEvent msgEvent;
		try {
			msgEvent = Xmls.parseObject(content, MsgEvent.class);
		} catch (Exception e) {
			log.warn(" ! 解析公众号推送XML 失败.");
			return "";
		}
		if (null == msgEvent) {
			return "";
		}

		if (msgEvent.getMsgType() == null) {
			return "";
		}

		return gzhService.gzhMsg(msgEvent);
	}

	/**
	 * 生成永久渠道二维码
	 */
	@GetMapping("/get/notExpired/popularizeCode")
	public Result<String> getNotExpiredPopularizeCode(String sceneKey) throws Exception {
		//获取gzh带参数的二维码
		String url = weChatService.getNotExpiredWxGzhQrCode(sceneKey);
		return GatewayResponse.SUCCESS.newBuilder().toResult(url);
	}
}
