package com.sqx.modules.wxMsg.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.sqx.common.utils.DateUtils;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.utils.InvitationCodeUtil;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.weixin.annotation.WxMsgController;
import net.dreamlu.weixin.properties.DreamWeixinProperties;
import net.dreamlu.weixin.spring.DreamMsgControllerAdapter;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;


/**
 * 微信公众号消息
 */
@Slf4j
@WxMsgController("/weixin/wx")
public class WeiXinMsgController extends DreamMsgControllerAdapter {
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private MessageService messageService;

    /**
     * 处理接收到的关注/取消关注事件
     * @param inFollowEvent 处理接收到的关注/取消关注事件
     */
    @Override
    protected void processInFollowEvent(InFollowEvent inFollowEvent) {
        String s = JSONObject.toJSONString(inFollowEvent);
        log.error(s);
        log.error(inFollowEvent.getEvent());
        log.error(inFollowEvent.getEventKey());
        OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
        String event = inFollowEvent.getEvent();
        if ("subscribe".equals(event)) {
            createUser(inFollowEvent.getFromUserName(),inFollowEvent.getEventKey());
            String care = commonInfoService.findOne(416).getValue();
            outMsg.setContent(care);
            render(outMsg);
        }

    }

    /**
     * 处理接收到的文本消息
     * @param inTextMsg 处理接收到的文本消息
     */
    @Override
    protected void processInTextMsg(InTextMsg inTextMsg) {

    }

    /**
     * 处理接收到的自定义菜单事件
     * @param inMenuEvent 处理接收到的自定义菜单事件
     */
    @Override
    protected void processInMenuEvent(InMenuEvent inMenuEvent) {
        OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
        outMsg.setContent("菜单消息~");
        render(outMsg);
    }

    /**
     * 处理接收到的地址位置消息(用户端主动发送当前位置信息)
     * @param inLocationMsg 处理接收到的地址位置消息
     */
    @Override
    protected void processInLocationMsg(InLocationMsg inLocationMsg) {

        super.processInLocationMsg(inLocationMsg);
    }

    /**
     * 处理接收到的扫描带参数二维码事件
     * @param inQrCodeEvent 处理接收到的扫描带参数二维码事件
     */
    @Override
    protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
        if ("SCAN".equals(inQrCodeEvent.getEvent())) {
            createUser(inQrCodeEvent.getFromUserName(),inQrCodeEvent.getEventKey());
            OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
            String content = commonInfoService.findOne(416).getValue();
            outMsg.setContent(content);
            render(outMsg);
        }else if("subscribe".equals(inQrCodeEvent.getEvent())){
            String eventKey = inQrCodeEvent.getEventKey();
            log.info("eventKey"+eventKey);
            if (eventKey != null && eventKey.contains("qrscene_")) {
                eventKey = eventKey.split("_")[1];
                log.info("relation"+eventKey);
                if (eventKey.contains("-")) {
                    eventKey = eventKey.split("-")[0];
                    log.info("eventKey"+eventKey);
                }
            }
            createUser(inQrCodeEvent.getFromUserName(),eventKey);
            OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
            String content = commonInfoService.findOne(416).getValue();
            outMsg.setContent(content);
            render(outMsg);
        }
    }

    public void createUser(String fromUserName,String eventKey){
        UserEntity userEntity = userService.queryByWxOpenId(fromUserName);
        if (userEntity == null) {
            userEntity = new UserEntity();
            userEntity.setUserName("公众号用户");
            userEntity.setPlatform("公众号");
            userEntity.setCreateTime(DateUtils.format(new Date()));
            userEntity.setUpdateTime(DateUtils.format(new Date()));
            userEntity.setStatus(1);
            userEntity.setWxOpenId(fromUserName);
            userEntity.setTempId(eventKey);
            userEntity.setInvitationCode(InvitationCodeUtil.toSerialCode());
            userEntity.setZhiRate(new BigDecimal(commonInfoService.findOne(207).getValue()));
            userEntity.setFeiRate(new BigDecimal(commonInfoService.findOne(208).getValue()));

            userService.save(userEntity);
            UserMoney userMoney = new UserMoney();
            userMoney.setUserId(userEntity.getUserId());
            userMoney.setMoney(BigDecimal.valueOf(0));
            userMoney.setCustomizationMoney(BigDecimal.valueOf(0));

            userMoneyDao.insert(userMoney);

            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("恭喜您，账号注册成功！");
            messageInfo.setTitle("系统通知");
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(userEntity.getUserName());
            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
            messageInfo.setCreateAt(DateUtils.format(new Date()));
            messageInfo.setIsSee("0");
            messageService.saveBody(messageInfo);
        } else {
            userEntity.setTempId(eventKey);
            userService.updateById(userEntity);
        }
    }

    /**
     * 处理接收到的上报地理位置事件(用户端自动推送当前位置信息)
     * @param inLocationEvent 处理接收到的上报地理位置事件
     */
    @Override
    protected void processInLocationEvent(InLocationEvent inLocationEvent) {
        System.out.println("处理接收到的上报地理位置事件:" + inLocationEvent.getFromUserName() + "," + inLocationEvent.getLongitude() + "," + inLocationEvent.getLatitude());


    }

}
