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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.tmerclub.cloud.api.multishop.bo.EsShopDetailBO;
import com.tmerclub.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.tmerclub.cloud.api.platform.feign.SysUserFeignClient;
import com.tmerclub.cloud.api.platform.vo.SysUserVO;
import com.tmerclub.cloud.api.product.feign.SpuBrowseLogFeignClient;
import com.tmerclub.cloud.api.product.feign.SpuFeignClient;
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.product.vo.SpuVO;
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.ImMsgBizUser;
import com.tmerclub.cloud.im.service.ImMsgBizUserService;
import com.tmerclub.cloud.im.socket.multishop.ShopOnlineWebSocketServer;
import com.tmerclub.cloud.im.socket.platform.SysOnlineWebSocketServer;
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.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @author Lzk
 */
@RestController
@RequestMapping("/im")
@Tag(name = "用户聊天接口")
public class UserController {

    @Autowired
    private ImMsgBizUserService imMsgBizUserService;
    @DubboReference
    private SysUserFeignClient sysUserFeignClient;
    @DubboReference
    private ShopDetailFeignClient shopDetailFeignClient;
    @DubboReference
    private SpuBrowseLogFeignClient spuBrowseLogFeignClient;
    @DubboReference
    private SpuFeignClient spuFeignClient;

    @PostMapping("/conversations")
    @Operation(summary = "最后的对话信息列表项", description = "获取最后的对话信息列表项")
    public ResponseEntity<PageVO<ConversationVO>> conversations(PageDTO pageDTO) {
        Long userId = AuthUserContext.get().getUserId();
        PageVO<ImMsgBizUser> imMsgBizUserPage = imMsgBizUserService.pageByUserId(pageDTO, userId);
        List<ImMsgBizUser> imMsgBizUserList = imMsgBizUserPage.getList();
        List<ConversationVO> conversationList = new ArrayList<>(com.tmerclub.cloud.common.constant.Constant.INITIAL_CAPACITY);
        for (ImMsgBizUser imMsgBizUser : imMsgBizUserList) {
            ConversationVO conversation = new ConversationVO();
            conversation.setChatType(imMsgBizUser.getSendType());
            conversation.setShopId(imMsgBizUser.getBizId());
            conversation.setUserId(imMsgBizUser.getUserId());
            conversation.setLatestMsg(imMsgBizUser.getLastMsgContent());
            conversation.setUnread(imMsgBizUser.getUserUnreadNum());
            // todo 东8区，不应该写死"+8"后续优化
            conversation.setTimestamp(imMsgBizUser.getLastMsgTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            conversation.setTimeStr(DateUtil.format(Date.from(imMsgBizUser.getLastMsgTime().atZone(ZoneId.systemDefault()).toInstant()), "yyyy/MM/dd"));
            conversation.setLatestMsgTime(imMsgBizUser.getLastMsgTime());
            conversation.setType(imMsgBizUser.getLastMsgType());
            conversation.setEmployeeId(imMsgBizUser.getEmployeeId());
            if (Objects.equals(imMsgBizUser.getSendType(), SendType.PLATFORM)) {
                ServerResponseEntity<SysUserVO> sysUserResponse = sysUserFeignClient.getSysUserByUserId(imMsgBizUser.getEmployeeId());
                if (!sysUserResponse.isSuccess()) {
                    throw new LuckException(sysUserResponse.getMsg());
                }
                SysUserVO sysUser = sysUserResponse.getData();
                if (sysUser != null) {
                    conversation.setFriendName(sysUser.getNickName());
                }
            } else if (Objects.equals(imMsgBizUser.getSendType(), SendType.SHOP)) {
                ServerResponseEntity<EsShopDetailBO> shopResponse = shopDetailFeignClient.getShopByShopId(imMsgBizUser.getBizId());
                if (!shopResponse.isSuccess()) {
                    throw new LuckException(shopResponse.getMsg());
                }
                EsShopDetailBO shopDetail = shopResponse.getData();
                if (shopDetail != null && shopDetail.getShopStatus() != null) {
                    conversation.setPic(shopDetail.getShopLogo());
                    conversation.setFriendName(shopDetail.getShopName());
                    conversation.setShopStatus(shopDetail.getShopStatus());
                }
            }
            if (Objects.equals(conversation.getChatType(), SendType.SHOP)) {
                Boolean isExist = MapUtil.isExistKeyPrefix(ShopOnlineWebSocketServer.SHOP_ONLINE_EMPLOYEE_MAP, Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + conversation.getShopId() + Constant.UNDERLINE);
                conversation.setIsOnline(isExist);
            } else if (Objects.equals(conversation.getChatType(), SendType.PLATFORM)) {
                Boolean isExist = MapUtil.isExistKeyPrefix(SysOnlineWebSocketServer.SYS_ONLINE_MAP, Constant.ONLINE_SYS_PREFIX);
                conversation.setIsOnline(isExist);
            }
            conversationList.add(conversation);
        }
        PageVO<ConversationVO> conversationPage = new PageVO<>();
        BeanUtils.copyProperties(imMsgBizUserPage, conversationPage);
        conversationPage.setList(conversationList);
        return ResponseEntity.ok(conversationPage);
    }

    @GetMapping("/recentBrowse")
    @Operation(summary = "最近浏览的商品", description = "获取最近浏览的商品")
    public ResponseEntity<List<SpuVO>> recentBrowse(Long shopId) {
        Long userId = AuthUserContext.get().getUserId();
        ServerResponseEntity<List<Long>> serverResponseEntity = spuBrowseLogFeignClient.recentBrowse(userId, shopId);
        if (!serverResponseEntity.isSuccess()) {
            throw new LuckException(serverResponseEntity.getMsg());
        }
        List<Long> spuIds = serverResponseEntity.getData();
        if (CollectionUtil.isEmpty(spuIds)) {
            return ResponseEntity.ok(Collections.emptyList());
        }
        ServerResponseEntity<List<SpuVO>> spuResponse = spuFeignClient.listSpuBySpuIds(spuIds);
        if (!spuResponse.isSuccess()) {
            throw new LuckException(spuResponse.getMsg());
        }
        List<SpuVO> spuVOList = spuResponse.getData();
        return ResponseEntity.ok(spuVOList);
    }

}
