package com.gree.mall.manager.logic.wxCustomer;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gree.mall.manager.constant.ChatMessageConstant;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.plus.entity.PeSingleChatMessage;
import com.gree.mall.manager.plus.service.PeSingleChatMessageService;
import com.gree.mall.manager.utils.RedisUtil;
import com.tencent.wework.Finance;
import com.tencent.wework.FinanceClient;
import com.tencent.wework.dto.ChatMessageDTO;
import io.lettuce.core.RedisClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 企业微信单聊消息 服务实现类
 * </p>
 *
 * @author XieHua
 * @since 2021-12-14
 */
@Service
public class SingleChatMessageLogic {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PeSingleChatMessageService peSingleChatMessageService;

 /*   @Value("${wechat.company.privateKey}")
    private String privateKey;*/

    /**
     * 同步企业微信消息
     *
     * @param seq
     * @return
     */
    public Boolean syncChatMessage(Long seq, String signSecret, String privateKey, String corpId) throws InterruptedException {

        Object redisValue = redisUtil.get(Constant.RedisPrefix.CHAT_MESSAGE_SEQ_KEY+corpId);
        if (redisValue != null)
            seq = Long.parseLong(String.valueOf(redisValue));
        else
            seq = 0L;

        long limit = 1000L;
        FinanceClient financeClient = FinanceClient.newInstance(corpId, signSecret, privateKey);
        while (true) {
            List<ChatMessageDTO> chatMessageList = financeClient.getChatMessageList(seq, limit);
            if (CollectionUtils.isEmpty(chatMessageList))
                break;
            for (ChatMessageDTO chatMessageDTO : chatMessageList) {
                //跳过切换企业日志
                if (chatMessageDTO.getAction().equals("switch"))
                    continue;

                // wb开头代表为机器人  _external结尾为外部消息
                if (chatMessageDTO.getFrom().startsWith("wb") || !chatMessageDTO.getMsgId().endsWith("_external"))
                    continue;

                PeSingleChatMessage chatMessage = this.convertFromChatMessage(chatMessageDTO);
                peSingleChatMessageService.save(chatMessage);
                execTaskA(chatMessage, financeClient);
            }
            seq = chatMessageList.get(chatMessageList.size() - 1).getSeq();
            redisUtil.set(Constant.RedisPrefix.CHAT_MESSAGE_SEQ_KEY+corpId, seq);

            if (chatMessageList.size() < limit)
                break;

        }
        return Boolean.TRUE;
    }

    @Async
    public String execTaskA(PeSingleChatMessage chatMessage, FinanceClient financeClient) throws InterruptedException {
        JSONObject jsonObject = JSON.parseObject(chatMessage.getContent());
        if (!StringUtils.isEmpty(jsonObject.getString("filesize")) &&  new BigDecimal(jsonObject.getString("filesize")).compareTo(new BigDecimal(Constant.HHCD_FILE_SIZE)) > 0){
            return null;
        }
        String filePath = financeClient.getSwitchType(chatMessage.getMsgType(), jsonObject.getString("sdkfileid"), jsonObject.getString("fileext"), Convert.toLong(chatMessage.getSeq()), jsonObject.getInteger("type"), jsonObject.getString("filename"));
        chatMessage.setFileUrl(filePath);
        peSingleChatMessageService.lambdaUpdate().eq(PeSingleChatMessage::getSeq, chatMessage.getSeq()).update(chatMessage);
        return filePath;
    }

    /**
     * 转换为SingleChatMessage对象
     *
     * @param chatMessageDTO ChatMessageDTO对象
     * @return SingleChatMessage对象
     */

    private PeSingleChatMessage convertFromChatMessage(ChatMessageDTO chatMessageDTO) throws InterruptedException {
        PeSingleChatMessage chatMessage = new PeSingleChatMessage();

        chatMessage.setMsgId(chatMessageDTO.getMsgId());
        chatMessage.setMsgType(chatMessageDTO.getMsgType());
        chatMessage.setSeq(Convert.toStr(chatMessageDTO.getSeq()));
        chatMessage.setFileUrl(chatMessageDTO.getFileUrl());
        chatMessage.setContent(chatMessageDTO.getBody());
        chatMessage.setRoomId(chatMessageDTO.getRoomId());
        chatMessage.setAction(chatMessageDTO.getAction());
        chatMessage.setCreatedTime(new Date());
        chatMessage.setModifiedTime(new Date());

        if (chatMessageDTO.getFrom().startsWith("wo") || chatMessageDTO.getFrom().startsWith("wm")) {
            chatMessage.setFromType(2);
            chatMessage.setExternalUserId(chatMessageDTO.getFrom());
            chatMessage.setUserId(JSONUtil.toJsonStr(chatMessageDTO.getToList()));
        } else {
            chatMessage.setFromType(1);
            chatMessage.setUserId(chatMessageDTO.getFrom());
            chatMessage.setExternalUserId(JSONUtil.toJsonStr(chatMessageDTO.getToList()));
        }

        chatMessage.setSendTime(chatMessageDTO.getMsgTime());
        // TODO: 异步处理聊天记录中的文件

        return chatMessage;
    }

}
