package com.yiqi.msg.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaUniformMessage;
import cn.hutool.json.JSONUtil;
import com.yiqi.app.domain.AppUser;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.config.CompositeWxMaService;
import com.yiqi.common.config.WxMaProperties;
import com.yiqi.common.core.domain.entity.SysUser;
import com.yiqi.msg.dto.MessageKeywordMappingDto;
import com.yiqi.msg.dto.MessagePushDto;
import com.yiqi.msg.service.UnifiedPushService;
import com.yiqi.system.domain.SysMessageConfig;
import com.yiqi.system.service.ISysMessageConfigService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author douya
 * @description
 * @date 2024/11/28
 */
@Slf4j
@Service
public class UnifiedPushServiceImpl implements UnifiedPushService {

    @Autowired
    private ISysMessageConfigService sysMessageConfigService;
    @Autowired
    private CompositeWxMaService compositeWxMaService;
    @Autowired
    private WxMaProperties wxMaProperties;
    @Autowired
    private IAppUserService appUserService;


    @Override
    @Async
    public void pushMessage(MessagePushDto pushDto) {
        SysMessageConfig sysMessageConfig = sysMessageConfigService.selectSysMessageConfigByCode(pushDto.getPushKey());
        if (sysMessageConfig == null) {
            return;
        }
        //小程序推送开启
        if (sysMessageConfig.getIsRoutine().equals(1)) {
            pushXcxMessage(sysMessageConfig, pushDto);
        }
        //公众号推送开启
        if (sysMessageConfig.getIsWechat().equals(1)) {
            pushGzhMessage(sysMessageConfig, pushDto);
        }
        //短信推送开启
        if (sysMessageConfig.getIsSms().equals(1)) {
            pushSmsMessage(sysMessageConfig, pushDto);
        }
        //app开启
        if (sysMessageConfig.getIsApp().equals(1)) {
            pushAppMessage(sysMessageConfig, pushDto);
        }
    }

    /**
     * 小程序推送
     * <p>
     * [{"fromKeyword":"refundAmount","toKeyword":"amount1","tplContent":"{refundAmount}"},{"fromKeyword":"orderSn","toKeyword":"character_string3","tplContent":"{orderSn}"},{"fromKeyword":"consumeAmount","toKeyword":"amount5","tplContent":"{consumeAmount}"},{"fromKeyword":"shopName","toKeyword":"thing12","tplContent":"{shopName}"}]
     *
     * @param sysMessageConfig
     * @param pushDto
     */
    private void pushXcxMessage(SysMessageConfig sysMessageConfig, MessagePushDto pushDto) {
        String templateContent = sysMessageConfig.getRoutineContent();
        List<MessageKeywordMappingDto> keywordMappings = JSONUtil.toList(JSONUtil.parseArray(templateContent), MessageKeywordMappingDto.class);
        if (null == keywordMappings) {
            log.error("消息关键词映射内容为空【{}】", sysMessageConfig.getCode());
        }
        Map<String, String> pushContentMap = JSONUtil.toBean(pushDto.getPushContent(), Map.class);
        //2,设置模版信息（keyword1：类型，keyword2：内容）
        List<WxMaSubscribeMessage.MsgData> templateDataList = new ArrayList<>(2);
        for (MessageKeywordMappingDto km : keywordMappings) {
            //匹配映射字段
            String value = km.getTplContent();
            if (StringUtils.isNotBlank(km.getFromKeyword())) {
                String[] array = km.getFromKeyword().split(",");
                for (String key : array) {
                    String replace = pushContentMap.get(key);
                    value = value.replaceAll("\\{" + key + "\\}", replace);
                }
            } else {
                //模板关键字为空，则不需要动态替换
                value = km.getTplContent();
            }
            WxMaSubscribeMessage.MsgData templateData = new WxMaSubscribeMessage.MsgData(km.getToKeyword(), value);
            templateDataList.add(templateData);
        }
        //3，设置推送消息
        AppUser appUser = appUserService.selectAppUserById(pushDto.getPushUserId());

        WxMaSubscribeMessage templateMessage = new WxMaSubscribeMessage();
        templateMessage.setTemplateId(sysMessageConfig.getRoutineTempid());
        templateMessage.setToUser(appUser.getWxOpenId());
        templateMessage.setData(templateDataList);
        //4，发起推送
        try {
            compositeWxMaService.getWxapp().getSubscribeService().sendSubscribeMsg(templateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
            System.out.println("小程序推送失败：" + e.getMessage());
        }
    }

    /**
     * app推送
     *
     * @param sysMessageConfig
     * @param pushDto
     */
    private void pushAppMessage(SysMessageConfig sysMessageConfig, MessagePushDto pushDto) {
    }

    /**
     * 短信推送
     *
     * @param sysMessageConfig
     * @param pushDto
     */
    private void pushSmsMessage(SysMessageConfig sysMessageConfig, MessagePushDto pushDto) {
    }

    /**
     * 公众号推送
     *
     * @param sysMessageConfig
     * @param pushDto
     */
    private void pushGzhMessage(SysMessageConfig sysMessageConfig, MessagePushDto pushDto) {
    }
}
