package com.storlead.message.service.impl;

import cn.hutool.core.util.StrUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.common.enums.ErrorMsgCode;
import com.storlead.framework.common.util.HtmlUtils;
import com.storlead.message.pojo.entity.MessageTemplateEventDetailEntity;
import com.storlead.message.service.WechatMessageService;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IUserService;
import com.storlead.wecom.service.CorpWeChatService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-04-26 10:14
 */
@Log4j2
@Service
public class WechatMessageServiceImpl implements WechatMessageService {


    @Resource
    private IUserService userService;

    @Autowired
    private CorpWeChatService corpWeChatService;

    /**
     * @param eventDetail  短信模板
     * @param map 参数
     * @param receiverUserIds 接收人
     * @param callbackParam 回调参数
     * @return
     */
    @Override
    public Result sendWechatMessage(MessageTemplateEventDetailEntity eventDetail, Map map, Collection<Long> receiverUserIds, String callbackParam){
        //发送企业微信
        try {
            MessageTemplateEventDetailEntity templateEntity = eventDetail;
            if (Objects.isNull(templateEntity)) {
                return Result.error(ErrorMsgCode.WECHAT_SMS_100006);
            }
            if (CollectionUtils.isEmpty(receiverUserIds)) {
                return Result.error(ErrorMsgCode.WECHAT_SMS_100008);
            }
            String title = templateEntity.getMessageTitle();
            title = title.replace("<br>","\n");
            Object titleRemark = Objects.nonNull(map) ? map.get("titleRemark") : null;
            if (Objects.nonNull(titleRemark)) {
                title = title.replace("${titleRemark}$",titleRemark.toString());
            }

            String content = templateEntity.getMessageCentent();

            Iterator <Map.Entry< Integer, String >> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry< Integer, String > entry = iterator.next();
                String value =  HtmlUtils.userContent(entry.getValue());
                content = content.replace("${"+entry.getKey()+"}$",value);
            }
            content = content.replace("<br>","\n");
            String router =""+ (StrUtil.isNotBlank(templateEntity.getCallbackUrl()) ? templateEntity.getCallbackUrl() : map.get("callbackUrl"));
            if (StrUtil.isNotBlank(router)) {
                Object id = Objects.nonNull(map) ? map.get("id") : null;
                Object jump = Objects.nonNull(map) ? map.get("jump") : null;
                if (StrUtil.isNotBlank(router)) {
                    if (Objects.nonNull(id)) {
                        router = router.replace("${id}$",id.toString());
                    } else {
                        router = router.replace("${id}$","");
                    }
                    if (Objects.nonNull(jump)) {
                        router = router.replace("${jump}$",jump.toString());
                    } else {
                        router = router.replace("${jump}$","");
                    }
                }
            }
            List<UserEntity> userEntityList = userService.getUserListByStaffIds(receiverUserIds);
            if (CollectionUtils.isEmpty(userEntityList)) {
                return Result.error(ErrorMsgCode.WECHAT_SMS_100009);
            }
            List<String> wxUseridList = userEntityList.stream().map(e->e.getXworkUserId()).collect(Collectors.toList());
            Set<String> userids = new HashSet<>(wxUseridList);

            if ("card".equals(eventDetail.getTemplateMessageView())) {
                corpWeChatService.sendTextCardMsgByUserId(title,content,userids,router);
            } else {
                corpWeChatService.sendTextMsg(content,userids,null,null);
            }
        } catch (Exception e) {
            log.error("目标提醒发送企业微信失败 错误为 " + e);
            return Result.error(ErrorMsgCode.WECHAT_SMS_100007.getCode(),e.getMessage());
        }
        return Result.ok();
    }

    @Override
    public Result sendWechatMessage(MessageTemplateEventDetailEntity eventDetail, Map map, Collection<Long> receiverUserIds, String callbackParam, String appCode) {
        //发送企业微信
        try {
            MessageTemplateEventDetailEntity templateEntity = eventDetail;
            if (Objects.isNull(templateEntity)) {
                return Result.error(ErrorMsgCode.WECHAT_SMS_100006);
            }
            if (CollectionUtils.isEmpty(receiverUserIds)) {
                return Result.error(ErrorMsgCode.WECHAT_SMS_100008);
            }
            String title = templateEntity.getMessageTitle();
            title = title.replace("<br>","\n");
            Object titleRemark = Objects.nonNull(map) ? map.get("titleRemark") : null;
            if (Objects.nonNull(titleRemark)) {
                title = title.replace("${titleRemark}$",titleRemark.toString());
            }
            String content = templateEntity.getMessageCentent();
            Iterator <Map.Entry< Integer, String >> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry< Integer, String > entry = iterator.next();
                String value =  HtmlUtils.userContent(entry.getValue());
                content = content.replace("${"+entry.getKey()+"}$",value);
            }
            content = content.replace("<br>","\n");
            String router =""+ (StrUtil.isNotBlank(templateEntity.getCallbackUrl()) ? templateEntity.getCallbackUrl() : map.get("callbackUrl"));
            if (StrUtil.isNotBlank(router)) {
                Object id = Objects.nonNull(map) ? map.get("id") : null;
                Object jump = Objects.nonNull(map) ? map.get("jump") : null;
                if (StrUtil.isNotBlank(router)) {
                    if (Objects.nonNull(id)) {
                        router = router.replace("${id}$",id.toString());
                    } else {
                        router = router.replace("${id}$","");
                    }
                    if (Objects.nonNull(jump)) {
                        router = router.replace("${jump}$",jump.toString());
                    } else {
                        router = router.replace("${jump}$","");
                    }
                }
            }
            List<UserEntity> userEntityList = userService.getUserListByStaffIds(receiverUserIds);
            if (CollectionUtils.isEmpty(userEntityList)) {
                return Result.error(ErrorMsgCode.WECHAT_SMS_100009);
            }
            List<String> wxUseridList = userEntityList.stream().map(e->e.getXworkUserId()).collect(Collectors.toList());
            Set<String> userids = new HashSet<>(wxUseridList);

                 corpWeChatService.sendTextCardMsgByUserIdByAppCode(title,content,router,userids,null,appCode);

        } catch (Exception e) {
            log.error("目标提醒发送企业微信失败 错误为 " + e);
            return Result.error(ErrorMsgCode.WECHAT_SMS_100007.getCode(),e.getMessage());
        }
        return Result.ok();
    }
}
