
package com.tmerclub.cloud.im.controller.platform;

import cn.hutool.core.date.DateUtil;
import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.user.feign.UserFeignClient;
import com.tmerclub.cloud.api.user.vo.UserApiVO;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.MapUtil;
import com.tmerclub.cloud.im.constants.Constant;
import com.tmerclub.cloud.im.constants.SendType;
import com.tmerclub.cloud.im.model.ImMsgBizEmployeeRecent;
import com.tmerclub.cloud.im.model.ImMsgBizUserHistory;
import com.tmerclub.cloud.im.service.ImMsgBizEmployeeRecentService;
import com.tmerclub.cloud.im.service.ImMsgBizUserHistoryService;
import com.tmerclub.cloud.im.socket.app.UserOnlineWebSocketServer;
import com.tmerclub.cloud.im.vo.ConversationVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Lzk
 */
@RestController
@RequestMapping("/p/im")
@Tag(name = "平台聊天接口")
public class SysController {
    @Autowired
    private ImMsgBizEmployeeRecentService imMsgBizEmployeeRecentService;

    @Autowired
    private ImMsgBizUserHistoryService imMsgBizUserHistoryService;
    @DubboReference
    private UserFeignClient userFeignClient;

    @PostMapping("/conversations")
    @Operation(summary = "最后的对话信息列表项", description = "获取最后的对话信息列表项")
    public ResponseEntity<PageVO<ConversationVO>> conversations(PageDTO pageDTO) {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        PageVO<ImMsgBizEmployeeRecent> imMsgBizEmployeeRecentPage = imMsgBizEmployeeRecentService.pageBySendTypeAndBizIdAndEmployeeId(pageDTO, SendType.PLATFORM, uidInfoBO.getTenantId(), uidInfoBO.getUserId());
        List<ImMsgBizEmployeeRecent> imMsgBizEmployeeRecentList = imMsgBizEmployeeRecentPage.getList();
        List<ConversationVO> conversationList = new ArrayList<>(com.tmerclub.cloud.common.constant.Constant.INITIAL_CAPACITY);
        for (ImMsgBizEmployeeRecent imMsgBizEmployeeRecent : imMsgBizEmployeeRecentList) {
            ImMsgBizUserHistory imMsgBizUserHistoryParam = new ImMsgBizUserHistory();
            imMsgBizUserHistoryParam.setSendType(SendType.PLATFORM);
            imMsgBizUserHistoryParam.setBizId(imMsgBizEmployeeRecent.getBizId());
            imMsgBizUserHistoryParam.setEmployeeId(imMsgBizEmployeeRecent.getEmployeeId());
            imMsgBizUserHistoryParam.setUserId(imMsgBizEmployeeRecent.getUserId());
            ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.getByParam(imMsgBizUserHistoryParam);
            ConversationVO conversation = new ConversationVO();
            conversation.setChatType(imMsgBizUserHistory.getSendType());
            conversation.setShopId(imMsgBizEmployeeRecent.getBizId());
            conversation.setUserId(imMsgBizEmployeeRecent.getUserId());
            conversation.setLatestMsg(imMsgBizUserHistory.getContent());
            conversation.setUnread(imMsgBizEmployeeRecent.getEmployeeUnreadNum());
            // todo 东8区，不应该写死"+8"后续优化
            conversation.setTimestamp(imMsgBizUserHistory.getCreateTime().toInstant().toEpochMilli());
            conversation.setTimeStr(DateUtil.format(Date.from(imMsgBizUserHistory.getCreateTime().toInstant()), "yyyy/MM/dd"));
            conversation.setLatestMsgTime(LocalDateTime.ofInstant(imMsgBizUserHistory.getCreateTime().toInstant(), ZoneId.systemDefault()));
            conversation.setType(imMsgBizUserHistory.getType());
            conversation.setEmployeeId(imMsgBizUserHistory.getEmployeeId());
            UserApiVO user = getUserApiVO(imMsgBizEmployeeRecent.getUserId());
            if (Objects.nonNull(user)) {
                conversation.setPic(user.getPic());
                conversation.setFriendName(user.getNickName());
            } else {
                conversation.setFriendName("*用户已注销*");
            }
            Boolean isExist = MapUtil.isExistKeyPrefix(UserOnlineWebSocketServer.USER_ONLINE_MAP, Constant.ONLINE_USER_PREFIX + conversation.getUserId() + Constant.UNDERLINE);
            conversation.setIsOnline(isExist);
            conversationList.add(conversation);
        }

        PageVO<ConversationVO> conversationPage = new PageVO<>();
        BeanUtils.copyProperties(imMsgBizEmployeeRecentPage, conversationPage);
        conversationPage.setList(conversationList);
        return ResponseEntity.ok(conversationPage);
    }

    @GetMapping("/userInfo")
    @Operation(summary = "获取用户信息", description = "获取用户信息")
    public ResponseEntity<List<ConversationVO>> userInfo(Long userId) {
        List<ConversationVO> conversations = new ArrayList<>(com.tmerclub.cloud.common.constant.Constant.INITIAL_CAPACITY);
        UserApiVO user = getUserApiVO(userId);
        if (Objects.nonNull(user)) {
            ConversationVO conversation = new ConversationVO();
            conversation.setUserId(userId);
            conversation.setFriendName(user.getNickName());
            conversation.setPic(user.getPic());
            conversations.add(conversation);
        }
        return ResponseEntity.ok(conversations);
    }

    private UserApiVO getUserApiVO(Long userId) {
        ServerResponseEntity<UserApiVO> userApiResponse = userFeignClient.getInsiderUserData(userId);
        if (!userApiResponse.isSuccess()) {
            throw new LuckException(userApiResponse.getMsg());
        }
        return userApiResponse.getData();
    }

}
