package com.liquidnet.service.consumer.sweet.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.service.consumer.sweet.config.WechatMaConfigure;
import com.liquidnet.service.consumer.sweet.config.WechatMpConfigure;
import com.liquidnet.service.consumer.sweet.utils.RedisDataUtils;
import com.liquidnet.service.sweet.dto.param.SweetOpenSendMsgParam;
import com.liquidnet.service.sweet.entity.SweetAppletUsers;
import com.liquidnet.service.sweet.entity.SweetWechatUser;
import com.liquidnet.service.sweet.mapper.SweetAppletUsersMapper;
import com.liquidnet.service.sweet.vo.SweetWechatUsersVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 公众号模版消息 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-07-27
 */
@Slf4j
@Service
public class SweetWechatTemplateMsgServiceImpl {

    @Autowired
    WechatMpConfigure wechatMpConfigure;

    @Autowired
    WechatMaConfigure wechatMaConfigure;

    @Autowired
    private SweetAppletUsersMapper sweetAppletUserMapper;

    @Autowired
    private RedisDataUtils redisDataUtils;

    public Boolean openSendMsg(SweetOpenSendMsgParam param) {
        String openId = getOpenId(param.getPhone(), param.getSendTargetType());
        if (openId.isEmpty()) {
            return true;
        }
        WxMpTemplateMessage templateMessage = null;
        if (param.getJumpType() == 5) {
            templateMessage = getTemplateMessage(param.getTemplateId(), openId, param.getJumpUrl());
        } else {
            templateMessage = getTemplateMessage(param.getTemplateId(), openId, param.getJumpType(), param.getJumpAppletPagePath(), param.getJumpAppletUsePath());
        }
        // 添加模板数据
        String templateData = param.getTemplateData();
        JSONObject templateDataJObj = JSONObject.parseObject(templateData);
        for (Map.Entry<String, Object> entry : templateDataJObj.entrySet()) {
            templateMessage.addData(new WxMpTemplateData(entry.getKey(), String.valueOf(entry.getValue())));
        }
        String msgId = sendTmpMsg(templateMessage, param.getSendTargetType());
        if (null == msgId) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取templateMessage
     *
     * @param templateId
     * @param openId
     * @param url
     * @return
     */
    private WxMpTemplateMessage getTemplateMessage(String templateId, String openId, String url) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId) // 接收者openid
                .templateId(templateId) // 模板id
                .url(url) // 模板跳转链接
                .build();
        return templateMessage;
    }
    private WxMpTemplateMessage getTemplateMessage(String templateId, String openId, Integer jumpType, String jumpAppletPagePath, Boolean jumpAppletUsePath) {
        //配置小程序信息
        WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
        miniProgram.setAppid(wechatMaConfigure.getWxMaAppid(jumpType));//小程序appid
        miniProgram.setUsePath(jumpAppletUsePath);//true的话需要前端配合处理跳转
        miniProgram.setPagePath(jumpAppletPagePath);//用户点击时需要跳转的小程序页面

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId) // 接收者openid
                .templateId(templateId) // 模板id
                .miniProgram(miniProgram) // 模板跳转链接
                .build();
        return templateMessage;
    }
    private String getOpenId(String phone, Integer sendTargetType) { // sendTargetType 将来如果加入其他服务号用获取不同openId
        List<SweetAppletUsers> sweetAppletUsers = sweetAppletUserMapper.selectList(Wrappers.lambdaQuery(SweetAppletUsers.class).eq(SweetAppletUsers::getPurePhoneNumber, phone));
        if (CollectionUtils.isEmpty(sweetAppletUsers)) {
            log.info("getOpenId没有此applet用户：[phone=[{}]", phone);
            return "";
        } else {
            SweetAppletUsers sweetAppletUser = sweetAppletUsers.get(0);
            SweetWechatUsersVo sweetWechatUsers = redisDataUtils.getSweetWechatUsersOfUnionId(sweetAppletUser.getUnionId(), 1);
            if (null == sweetWechatUsers) {
                log.info("getOpenId没有此WechatUser用户：[phone={},unionId={}]", phone, sweetAppletUser.getUnionId());
                return "";
            } else {
                return sweetWechatUsers.getOpenId();
            }
        }
    }

    private String sendTmpMsg(WxMpTemplateMessage templateMessage, Integer sendTargetType) {
        String msgId = null;
        try {
            // 发送模板消息
            WxMpService wxMpService = wechatMpConfigure.getWxMpService(sendTargetType);
            log.info("sendTmpMsg-isAccessTokenExpired：[{}] ", wxMpService.getWxMpConfigStorage().isAccessTokenExpired());
            log.info("sendTmpMsg-getAccessToken：[{}] ", wxMpService.getWxMpConfigStorage().getAccessToken());
            msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            log.info("模版消息发送成功：[msgId={}]", msgId);
        } catch (WxErrorException e) {
            log.error("模版消息发送异常", e);
        }
        return msgId;
    }

}
