package com.tzld.piaoquan.api.service.wecom.impl;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONArray;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.tzld.piaoquan.api.common.enums.ReplyStrategyServiceEnum;
import com.tzld.piaoquan.api.dao.mapper.ReplyStaffMapper;
import com.tzld.piaoquan.api.model.bo.BucketDataParam;
import com.tzld.piaoquan.api.model.bo.GroupData;
import com.tzld.piaoquan.api.model.bo.MsgData;
import com.tzld.piaoquan.api.model.bo.ReplyBucketData;
import com.tzld.piaoquan.api.model.po.ReplyStaff;
import com.tzld.piaoquan.api.model.po.ReplyStaffExample;
import com.tzld.piaoquan.api.model.param.WeComPushMessageParam;
import com.tzld.piaoquan.api.model.vo.WeComPushMessageVo;
import com.tzld.piaoquan.api.service.wecom.WeComService;
import com.tzld.piaoquan.api.service.strategy.ReplyStrategyService;
import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
import com.tzld.piaoquan.growth.common.common.enums.ExceptionCodeEnum;
import com.tzld.piaoquan.growth.common.common.enums.StrategyStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class WeComServiceImpl implements WeComService {

    private static final String CORP_ID = "wwa4015dc7d652a21f";

    private static final int MAX_BYTES = 64;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ReplyStaffMapper replyStaffMapper;

    @ApolloJsonValue("${special.reply.staff.id:}")
    private List<Long> specialReplyStaffId;

    private Map<String, ReplyStrategyService> strategyServiceMap;

    @PostConstruct
    public void init() {
        strategyServiceMap = applicationContext.getBeansOfType(ReplyStrategyService.class);
    }

    @Override
    public CommonResponse<List<WeComPushMessageVo>> getPushMessage(WeComPushMessageParam param) {
        if (param == null || StringUtils.isEmpty(param.getCorpId()) || !CORP_ID.equals(param.getCorpId()) || StringUtils.isEmpty(param.getUserId())) {
            return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "参数错误");
        }

        ReplyStaffExample example = new ReplyStaffExample();
        example.createCriteria().andUserIdEqualTo(param.getUserId()).andIsDeleteEqualTo(0);
        List<ReplyStaff> replyStaffs = replyStaffMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(replyStaffs)) {
            return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "用户查询不到");
        }
        ReplyStaff replyStaff = replyStaffs.get(0);
        List<WeComPushMessageVo> res = new ArrayList<>();
        ReplyBucketData replyBucketData = getPushMessageData(replyStaff.getUserId(), replyStaff.getVideoIds());
        if (replyBucketData == null) {
            return CommonResponse.create(500, "数据异常");
        }
        List<GroupData> groupList = replyBucketData.getGroupList();
        log.info("getPushMessage groupList={}", groupList);
        if (CollectionUtils.isEmpty(groupList)) {
            return CommonResponse.create(500, "数据异常");
        }
        String name = replyStaff.getName();
        for (GroupData groupData : groupList) {
            if (CollectionUtils.isEmpty(groupData.getMsgDataList())) {
                continue;
            }
            WeComPushMessageVo weComPushMessageVo = new WeComPushMessageVo();
            weComPushMessageVo.setGroupIndex(groupData.getGroupIndex());
            List<MsgData> msgDataList = groupData.getMsgDataList();
            for (MsgData msgData : msgDataList) {
                if (msgData.getTitle().getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) {
                    String s = truncateString(msgData.getTitle(), MAX_BYTES - 3) + "...";
                    msgData.setTitle(s);
                }
            }
            MsgData msgData = new MsgData();
            msgData.setMsgType(3);
            if (replyStaff.getId() == 1) {
                msgData.setTitle("你好呀~我是智能助手芳华，专门陪您唠唠嗑、解解闷的！\uD83C\uDF39\n" +
                        "刚发现好多有趣视频想分享给您！偷偷告诉我——您平时最爱看【健康养生】、【历史故事】这类知识干货，还是【人生智慧】【怀旧经典】这些暖心内容呀？\n" +
                        "（悄悄加个选项\uD83D\uDC49【祝福音乐】\uD83C\uDFB5，马上帮您找！）");
            } else if (replyStaff.getId() == 3) {
                msgData.setTitle(String.format("很高兴认识您！我是%s，每天给您推荐精彩视频~", name));
            } else {
                msgData.setTitle("叔叔阿姨好，我是健康小助手，每天会为您定制全网热点视频，感谢您的关注，手动转发支持哦～");
            }

            msgDataList.add(0, msgData);
            weComPushMessageVo.setMsgDataList(msgDataList);
            res.add(weComPushMessageVo);
        }
        log.info("res={}", res);
        return CommonResponse.success(res);
    }

    @Override
    public List<WeComPushMessageVo> getPushMessageByUserId(List<ReplyStaff> replyStaffs) {
        if (CollectionUtils.isEmpty(replyStaffs)) {
            return null;
        }
        ReplyStaff replyStaff = replyStaffs.get(0);
        List<WeComPushMessageVo> res = new ArrayList<>();
        ReplyBucketData replyBucketData = getPushMessageData(replyStaff.getUserId(), replyStaff.getVideoIds());
        if (replyBucketData == null || CollectionUtils.isEmpty(replyBucketData.getGroupList())) {
            WeComPushMessageVo weComPushMessageVo = new WeComPushMessageVo();
            weComPushMessageVo.setGroupIndex(0);
            List<MsgData> msgDataList = new ArrayList<>();
            MsgData msgData = getTextMsgData(replyStaff.getId(), replyStaff.getName());
            msgDataList.add(msgData);
            weComPushMessageVo.setMsgDataList(msgDataList);
            res.add(weComPushMessageVo);
            return res;
        }
        List<GroupData> groupList = replyBucketData.getGroupList();
        log.info("getPushMessageByUserId groupList={}", groupList);
        for (GroupData groupData : groupList) {
            if (CollectionUtils.isEmpty(groupData.getMsgDataList())) {
                continue;
            }
            WeComPushMessageVo weComPushMessageVo = new WeComPushMessageVo();
            weComPushMessageVo.setGroupIndex(groupData.getGroupIndex());
            List<MsgData> msgDataList = groupData.getMsgDataList();
            for (MsgData msgData : msgDataList) {
                if (msgData.getTitle().getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) {
                    String s = truncateString(msgData.getTitle(), MAX_BYTES - 3) + "...";
                    msgData.setTitle(s);
                }
            }
            MsgData msgData = getTextMsgData(replyStaff.getId(), replyStaff.getName());
            msgDataList.add(0, msgData);
            weComPushMessageVo.setMsgDataList(msgDataList);
            res.add(weComPushMessageVo);
        }
        log.info("getPushMessageByUserId res={}", res);
        return res;
    }

    private MsgData getTextMsgData(Long replyStaffId, String name) {
        MsgData msgData = new MsgData();
        msgData.setMsgType(3);
        if (specialReplyStaffId.contains(replyStaffId)) {
            msgData.setTitle("欢迎加入票圈老年社区， 每天社群内为您推荐更多精彩视频内容，感谢您的关注！");
        } else if (replyStaffId == 1) {
            msgData.setTitle("你好呀~我是智能助手芳华，专门陪您唠唠嗑、解解闷的！\uD83C\uDF39\n" +
                    "刚发现好多有趣视频想分享给您！偷偷告诉我——您平时最爱看【健康养生】、【历史故事】这类知识干货，还是【人生智慧】【怀旧经典】这些暖心内容呀？\n" +
                    "（悄悄加个选项\uD83D\uDC49【祝福音乐】\uD83C\uDFB5，马上帮您找！）");
        } else if (replyStaffId == 3) {
            msgData.setTitle(String.format("很高兴认识您！我是%s，每天给您推荐精彩视频~", name));
        } else {
            msgData.setTitle("叔叔阿姨好，我是好看内容推荐官，每天会为您定制全网热点视频，感谢您的关注，手动转发支持哦~");
        }
        return msgData;
    }

    private ReplyBucketData getPushMessageData(String userId, String videoIds) {
        log.info("strategyServiceMap={}", JSON.toJSONString(strategyServiceMap));
        for (Map.Entry<String, ReplyStrategyService> stringReplyStrategyServiceEntry : strategyServiceMap.entrySet()) {
            ReplyStrategyService replyStrategyService = stringReplyStrategyServiceEntry.getValue();
            // 使用策略层
            if (replyStrategyService.support(ReplyStrategyServiceEnum.WE_COM_PUSH_MESSAGE_STRATEGY_V1)) {
                BucketDataParam bucketDataParam = new BucketDataParam();
                bucketDataParam.setGhId(userId);
                if (StringUtils.isNotEmpty(videoIds)) {
                    bucketDataParam.setStrategyStatus(StrategyStatusEnum.DEFAULT.status);
                    bucketDataParam.setVideos(JSONArray.parseArray(videoIds, Long.class));
                }
                return replyStrategyService.getResult(bucketDataParam);
            }
        }
        // 无执行策略 不会走到这里
        return null;
    }

    private String truncateString(String input, int maxBytes) {
        if (input == null || maxBytes <= 0) {
            return "";
        }

        byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
        if (bytes.length <= maxBytes) {
            return input; // 如果字节数已经在限制内，直接返回原字符串
        }

        // 截取字节数组
        byte[] truncatedBytes = new byte[maxBytes];
        System.arraycopy(bytes, 0, truncatedBytes, 0, maxBytes);

        // 将截取的字节数组转换回字符串
        String truncatedString = new String(truncatedBytes, StandardCharsets.UTF_8);

        // 处理可能的字符截断问题
        // 如果截取后字符串的字节数仍然大于 maxBytes，向前查找直到找到有效字符
        while (truncatedString.getBytes(StandardCharsets.UTF_8).length > maxBytes) {
            truncatedString = truncatedString.substring(0, truncatedString.length() - 1);
        }

        return truncatedString;
    }
}
