package com.miaxis.wx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.domain.entity.UserInfo;
import com.miaxis.common.utils.StringUtils;
import com.miaxis.common.utils.wx.MessageUtil;
import com.miaxis.feign.service.IWxSendService;
import com.miaxis.system.service.ISysUserService;
import com.miaxis.wx.mapper.WxMenuMapper;
import com.miaxis.wx.service.IWxGzhService;
import com.miaxis.wx.service.IWxMessageEvenService;
import com.qcloud.cos.COSClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 微信公众号业务层
 * @author wwl
 * @version 1.0
 * @date 2021/10/20 14:57
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WxGzhServiceImpl implements IWxGzhService {

    private final RedisTemplate redisTemplate;

    private final IWxSendService wxSendService;

    private final WxMenuMapper wxMenuMapper;

    private final COSClient cosClient;

    private final ISysUserService userService;

    private final IWxMessageEvenService wxMessageEvenService;

    @Value("${app.appid}")
    private String appid;

    @Value("${app.appSecret}")
    private String secret;


    /**
     * 获取微信公众号token
     * @return
     */
    @Override
    public String getGzhToken() {
        String token = "";
        Integer expiresIn;
        if (redisTemplate.hasKey(Constants.GZH_MESSAGE_TOKEN)){
            token = (String)redisTemplate.opsForValue().get(Constants.GZH_MESSAGE_TOKEN);
        }
        if (StringUtils.isEmpty(token)){
            String result = wxSendService.getAccessToken("client_credential",appid,secret);
            JSONObject json = JSONObject.parseObject(result);
            token = json.getString("access_token");
            expiresIn = json.getIntValue("expires_in");
            if (expiresIn <= 0){
                expiresIn = 7000;
            }

            redisTemplate.opsForValue().set(Constants.GZH_MESSAGE_TOKEN,token,expiresIn, TimeUnit.SECONDS);
        }

        return token;
    }



    /**
     * 微信推送消息处理
     * @param request
     * @return
     */
    @Override
    public String handlePublicMsg(HttpServletRequest request) {
        try {
            log.info("1....");
//            cn.hutool.json.JSONObject decryptMap = XML.toJSONObject(IOUtils.toString(request.getInputStream()));
//            cn.hutool.json.JSONObject jsonObjectData = decryptMap.getJSONObject("xml");


            cn.hutool.json.JSONObject jsonObjectData = new cn.hutool.json.JSONObject("{\"CreateTime\":1639474955,\"EventKey\":\"https://jpcj-h5.zzxcx.net\",\"ToUserName\":\"gh_628da25a95e5\",\"MsgType\":\"event\",\"MenuId\":442656773,\"Event\":\"VIEW\",\"FromUserName\":\"ovKTX50v7OAEPI_ERofpUvrNQCJU\"}");
            log.info("2-----jsonObjectData------"+jsonObjectData);



            //开发者微信号
            String toUserName = jsonObjectData.getStr("ToUserName");
            //发送方帐号（一个OpenID）
            String fromUserName = jsonObjectData.getStr("FromUserName");
            // 区分消息类型
            String msgType = jsonObjectData.getStr("MsgType");

            // 普通消息
            if (MessageUtil.MESSAGE_TEXT.equals(msgType)) { // 文本消息
                log.info("2.1...");
                String content = jsonObjectData.getStr("Content");
                if (content.startsWith("你好")){
                    return MessageUtil.initText(fromUserName, toUserName, "你好啊");
                }else if (content.startsWith("傻逼")){
                    return MessageUtil.initText(fromUserName, toUserName, "你才是煞笔");
                }else {
                    return MessageUtil.initText(fromUserName, toUserName, "文本消息-默认回复信息");
                }

            } else if (MessageUtil.MESSAGE_IMAGE.equals(msgType)) { // 图片消息
                log.info("2.2...");
                return MessageUtil.initText(fromUserName, toUserName, "抱歉，暂时无法识别图片信息！");
            }else if (MessageUtil.MESSAGE_EVENT.equals(msgType)) { // 事件消息
                log.info("3....");
                // 区分事件推送
                String event = jsonObjectData.getStr("Event");
                if (MessageUtil.MESSAGE_SUBSCRIBE.equals(event)) { // 关注事件 或 扫描二维码关注事件
                    log.info("3.1...");

                    //获取用户信息
                    String userInfoResult = wxSendService.userInfo(this.getGzhToken(), fromUserName, "zh_CN");
                    JSONObject jsonObj = JSONObject.parseObject(userInfoResult);
                    UserInfo user = userService.getStudentByOpenId(fromUserName);
                    UserInfo userInfo = new UserInfo();
                    if (user == null){
                        //保存用户信息
                        userInfo.setHeadImage(jsonObj.getString("headimgurl"));
                        userInfo.setNickName(jsonObj.getString("nickname"));
                        userInfo.setOpenid(jsonObj.getString("openid"));
                        userService.saveUserInfo(userInfo);
                    }

                    //存在Ticket为扫码关注
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(jsonObjectData.getStr("Ticket"))){
                        log.info("3.1.2..");
                        //根据Ticket  绑定信息到上级用户
                        String subscribeEvent = wxMessageEvenService.scanSubscribeEvent(fromUserName, jsonObjectData.getStr("Ticket"),this.getGzhToken(),userInfo.getNickName());
                        return MessageUtil.initText(fromUserName,toUserName,subscribeEvent);

                    }else {
                        return MessageUtil.initText(fromUserName, toUserName, jsonObj.getString("nickname")+"：关注事件");
                    }

                }  else if (MessageUtil.MESSAGE_UNSUBSCRIBE.equals(event)) { // 取消订阅事件
                    // todo 处理取消订阅事件

                } else if (MessageUtil.MESSAGE_SCAN.equals(event)) { // 已关注扫描二维码事件
                    log.info("3.2...");
                    return MessageUtil.initText(fromUserName, toUserName, "已关注扫描二维码事件");

                } else if (MessageUtil.MESSAGE_LOCATION.equals(event)) { // 上报地理位置事件
                    // todo 处理上报地理位置事件

                } else if (MessageUtil.MESSAGE_CLICK.equals(event)) { // 点击菜单拉取消息时的事件推送事件
                    log.info("3.3.....click:" + jsonObjectData.get("EventKey"));
                    //判断事件KEY值，与自定义菜单接口中KEY值对应
                    if ("generateTicket".equals(jsonObjectData.get("EventKey"))){ //获取分销二维码
                        String mediaId = wxMessageEvenService.gainTicketEvent(fromUserName, this.getGzhToken());
                        return MessageUtil.initImage(fromUserName,toUserName,mediaId);
                    }

                } else if (MessageUtil.MESSAGE_VIEW.equals(event)) { // 点击菜单跳转链接时的事件推送
                    // todo 处理点击菜单跳转链接时的事件推送
                }
            }
        } catch (Exception e) {
            log.error("处理微信公众号请求信息，失败", e);
        }
        return null;
    }


}
