package cn.reghao.tnb.content.app.chat.service;

import cn.reghao.file.api.iface.OssService;
import cn.reghao.tnb.auth.api.iface.AccountQuery;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.chat.db.mapper.*;
import cn.reghao.tnb.content.app.chat.model.constant.MsgType;
import cn.reghao.tnb.content.app.chat.model.dto.chat.ChatRecordGetRet;
import cn.reghao.tnb.content.app.chat.model.dto.chat.ChatRecordGetRetList;
import cn.reghao.tnb.content.app.chat.model.dto.message.CodeBlockResult;
import cn.reghao.tnb.content.app.chat.model.dto.message.FileMsgResult;
import cn.reghao.tnb.content.app.chat.model.po.message.CodeBlockMessage;
import cn.reghao.tnb.content.app.chat.model.po.message.FileMessage;
import cn.reghao.tnb.content.app.chat.model.po.message.TextMessage;
import cn.reghao.tnb.user.api.dto.ContactDetail;
import cn.reghao.tnb.user.api.dto.UserInfo;
import cn.reghao.tnb.user.api.iface.UserContactService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2022-04-30 11:16:02
 */
@Service
public class ChatRecordService {
    @DubboReference(check = false, retries = 0, timeout = 60_000)
    private AccountQuery accountQuery;
    @DubboReference(check = false)
    private UserContactService contactService;
    @DubboReference(check = false)
    private OssService ossService;

    private final ChatRecordMapper chatRecordMapper;
    private final TextMessageMapper textMessageMapper;
    private final CodeBlockMessageMapper codeBlockMessageMapper;
    private final FileMessageMapper fileMessageMapper;

    public ChatRecordService(ChatRecordMapper chatRecordMapper, TextMessageMapper textMessageMapper,
                             CodeBlockMessageMapper codeBlockMessageMapper, FileMessageMapper fileMessageMapper) {
        this.chatRecordMapper = chatRecordMapper;
        this.textMessageMapper = textMessageMapper;
        this.codeBlockMessageMapper = codeBlockMessageMapper;
        this.fileMessageMapper = fileMessageMapper;
    }


    public ChatRecordGetRetList getChatRecords(long receiverId, long recordId, int limit) {
        long loginUser = UserContext.getUserId();
        List<ChatRecordGetRet> list = chatRecordMapper.findChatRecordGetRet(receiverId, loginUser, recordId, limit);
        list.forEach(chatRecordGetRet -> {
            try {
                long userId1 = accountQuery.getUserIdLong(chatRecordGetRet.getUserId());
                UserInfo userInfo = contactService.getUserInfo(userId1);
                if (userInfo != null) {
                    chatRecordGetRet.setNickname(userInfo.getScreenName());
                    chatRecordGetRet.setAvatar(userInfo.getAvatarUrl());
                    setRecordMessage(loginUser, chatRecordGetRet);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        ChatRecordGetRetList chatRecordGetRetList = new ChatRecordGetRetList();
        chatRecordGetRetList.setRows(list);
        if (list.isEmpty()) {
            chatRecordGetRetList.setRecordId(0);
        } else {
            chatRecordGetRetList.setRecordId(list.get(list.size()-1).getRecordId());
        }
        chatRecordGetRetList.setLimit(limit);
        return chatRecordGetRetList;
    }

    private void setRecordMessage(long userId, ChatRecordGetRet chatRecordGetRet) throws Exception {
        long recordId1 = chatRecordGetRet.getRecordId();
        int msgType = chatRecordGetRet.getMsgType();
        boolean revoke = chatRecordGetRet.isRevoke();
        String createAt = chatRecordGetRet.getCreatedAt();
        if (revoke) {
            //
        } else if (msgType == MsgType.text.getCode()) {
            TextMessage textMessage = textMessageMapper.findByRecordId(recordId1);
            chatRecordGetRet.setContent(textMessage.getContent());
        } else if (msgType == MsgType.media.getCode()) {
            FileMessage fileMessage = fileMessageMapper.findByRecordId(recordId1);
            String uploadId = fileMessage.getUploadId();
            int channelCode = 110;
            String url = ossService.getSignedUrl(uploadId, null);

            String filename = fileMessage.getFilename();
            String suffix = getSuffix(filename);
            //String url = fileMessage.getUrl();
            FileMsgResult fileMsgResult = new FileMsgResult(fileMessage, url, userId, createAt);
            chatRecordGetRet.setFile(fileMsgResult);
        } else if (msgType == MsgType.chatRecord.getCode()) {

        } else if (msgType == MsgType.codeBlock.getCode()) {
            CodeBlockMessage codeBlockMessage = codeBlockMessageMapper.findByRecordId(recordId1);
            CodeBlockResult codeBlockResult = new CodeBlockResult(codeBlockMessage, userId);
            chatRecordGetRet.setCodeBlock(codeBlockResult);
        } else if (msgType == MsgType.vote.getCode()) {

        }
    }

    private String getSuffix(String filename) {
        int idx = filename.lastIndexOf(".");
        return idx == -1 ? "" : filename.substring(idx);
    }

    public ChatRecordGetRetList getChatRecords(int msgType, long receiverId, long recordId, int limit) {
        long loginUser = UserContext.getUserId();
        List<ChatRecordGetRet> list =
                chatRecordMapper.findChatRecordGetRetByMsgType(msgType, receiverId, loginUser, recordId, limit);
        list.forEach(chatRecordGetRet -> {
            long userId = accountQuery.getUserIdLong(chatRecordGetRet.getUserId());
            ContactDetail contactDetail = contactService.getContactDetail(userId);
            chatRecordGetRet.setNickname(contactDetail.getScreenName());
            chatRecordGetRet.setAvatar(contactDetail.getAvatarUrl());

            try {
                setRecordMessage(loginUser, chatRecordGetRet);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        ChatRecordGetRetList chatRecordGetRetList = new ChatRecordGetRetList();
        chatRecordGetRetList.setRows(list);
        if (list.isEmpty()) {
            chatRecordGetRetList.setRecordId(0);
        } else {
            chatRecordGetRetList.setRecordId(list.get(list.size()-1).getRecordId());
        }
        chatRecordGetRetList.setLimit(limit);
        return chatRecordGetRetList;
    }
}
