package com.qnfhq.modules.c2c.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import com.qnfhq.annotation.RepeatSubmit;
import com.qnfhq.common.ApiBaseController;
import com.qnfhq.common.constant.Constant;
import com.qnfhq.common.page.PageData;
import com.qnfhq.common.redis.RedisUtils;
import com.qnfhq.common.utils.MessageUtils;
import com.qnfhq.common.utils.Result;
import com.qnfhq.common.validator.ValidatorUtils;
import com.qnfhq.constant.CacheConstants;
import com.qnfhq.modules.c2c.dto.C2cMsgContactDTO;
import com.qnfhq.modules.c2c.dto.C2cMsgContentDTO;
import com.qnfhq.modules.c2c.dto.C2cMsgRelationDTO;
import com.qnfhq.modules.c2c.entity.C2cMsgContactEntity;
import com.qnfhq.modules.c2c.entity.C2cMsgRelationEntity;
import com.qnfhq.modules.c2c.enums.MsgTypeEnum;
import com.qnfhq.modules.c2c.service.C2cMsgContactService;
import com.qnfhq.modules.c2c.service.C2cMsgContentService;
import com.qnfhq.modules.c2c.service.C2cMsgRelationService;
import com.qnfhq.modules.user.entity.AppUserEntity;
import com.qnfhq.modules.user.service.AppUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.*;


/**
 * 聊天消息表
 *
 * @author yelz 30262728@qq.com
 * @since 1.0.0 2025-11-25
 */
@RestController
@RequestMapping("/c2cmsg")
@Tag(name="c2c聊天接口")
@Slf4j
public class C2cMsgContentController extends ApiBaseController {
    @Resource
    private C2cMsgContentService c2cMsgContentService;

    @Resource
    private C2cMsgRelationService c2cMsgRelationService;

    @Resource
    private C2cMsgContactService c2cMsgContactService;
    @Resource
    private AppUserService appUserService;
    @Resource
    private RedisUtils redisUtils;

    @PostMapping("/send")
    @RepeatSubmit(interval = 3000, message = "请求过于频繁")
    @Operation(summary = "发消息")
    public Result send(@RequestBody C2cMsgContentDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto);

        Long receptId = dto.getRecipientId();
        AppUserEntity receptUser = appUserService.getById(receptId);
        if(Objects.isNull(receptUser)) {
            return new Result().error(MessageUtils.message("c2c.msg.receptId.notexists"));//"接收人不存在"
        }

        if(!MsgTypeEnum.isValid(dto.getMsgType())) {
            return new Result().error(MessageUtils.message("c2c.msg.msgType.err"));//"消息类型错误"
        }

        if(receptId.longValue() == StpUtil.getLoginIdAsLong()) {
            return new Result().error(MessageUtils.message("c2c.msg.receptId.err"));//不能给自己发消息
        }

        try {
            return c2cMsgContentService.saveMsg(dto);
        } catch (Exception e) {
            log.error("c2cMsgContentService.saveMsg============"+e.getMessage(),e);
            return new Result().error(MessageUtils.message("operation.fail.please.refresh"));//操作失败，请刷新后重试
        }
    }


    @PostMapping("/chatList")
    @Operation(summary = "查询与某人的聊天记录")
    public Result<PageData<C2cMsgRelationEntity>> chatList(@RequestBody C2cMsgRelationDTO dto){
        ValidatorUtils.validateEntity(dto);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Constant.PAGE, dto.getPageNum());
        params.put(Constant.LIMIT, dto.getPageSize());
        params.put(Constant.ORDER_FIELD, "mid");
        params.put(Constant.ORDER, "desc");
        params.put("ownerUid", StpUtil.getLoginIdAsLong());
        params.put("otherUid", dto.getOtherUid());
        params.put("mid", dto.getMid());
        PageData<C2cMsgRelationEntity> page = c2cMsgRelationService.selectChatPage(params);
        page.getList().forEach(item -> item.setC2cMsg(c2cMsgContentService.getById(item.getMid())));

        //聊天未读数更新
        Long unreadC = Convert.toLong(redisUtils.hGet(CacheConstants.getChatUnreadKey(StpUtil.getLoginIdAsLong()), dto.getOtherUid().toString()),0L);
        if(unreadC!=null && unreadC.longValue()>0) {
            redisUtils.increment(CacheConstants.getChatUnreadKey(StpUtil.getLoginIdAsLong()), dto.getOtherUid().toString(), -unreadC.longValue(), -1L);
            //总未读数更新
            redisUtils.decrement(CacheConstants.getTotalUnreadKey(StpUtil.getLoginIdAsLong()), unreadC.longValue(), -1L);
        }

        return new Result<PageData<C2cMsgRelationEntity>>().ok(page);
    }


    @PostMapping("/contactList")
    @Operation(summary = "查询我的最近联系人列表")
    public Result<PageData<C2cMsgContactEntity>> contactList(@RequestBody C2cMsgContactDTO dto){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Constant.PAGE, dto.getPageNum());
        params.put(Constant.LIMIT, dto.getPageSize());
        params.put(Constant.ORDER_FIELD, "mid");
        params.put(Constant.ORDER, "desc");
        params.put("ownerUid", StpUtil.getLoginIdAsLong());
        PageData<C2cMsgContactEntity> page = c2cMsgContactService.selectContactPage(params);
        page.getList().forEach(item -> {
            item.setC2cMsg(c2cMsgContentService.getById(item.getMid()));
            item.setUnreads(Convert.toLong(redisUtils.hGet(CacheConstants.getChatUnreadKey(item.getOwnerUid()), item.getOtherUid().toString()),0L));
        });
        //总未读数
        Map data = MapUtil.of("totalUnread", Convert.toLong(redisUtils.get(CacheConstants.getTotalUnreadKey(StpUtil.getLoginIdAsLong())),0L));
        data.put("page",page);
        return new Result().ok(data);
    }



}
