package com.qnfhq.modules.c2c.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qnfhq.common.redis.RedisUtils;
import com.qnfhq.common.utils.Result;
import com.qnfhq.constant.CacheConstants;
import com.qnfhq.modules.c2c.dao.C2cMsgContentDao;
import com.qnfhq.modules.c2c.dto.C2cMsgContentDTO;
import com.qnfhq.modules.c2c.dto.C2cOrderMsgContentDTO;
import com.qnfhq.modules.c2c.entity.C2cMsgContentEntity;
import com.qnfhq.modules.c2c.entity.C2cPaymentVoucherEntity;
import com.qnfhq.modules.c2c.enums.MsgStatusEnum;
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.c2c.service.C2cPaymentVoucherService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 聊天消息表
 *
 * @author yelz 30262728@qq.com
 * @since 1.0.0 2025-11-25
 */
@Service
public class C2cMsgContentServiceImpl extends ServiceImpl<C2cMsgContentDao, C2cMsgContentEntity> implements C2cMsgContentService {

    @Resource
    private C2cMsgRelationService c2cMsgRelationService;
    @Resource
    private C2cMsgContactService c2cMsgContactService;
    @Resource
    private C2cPaymentVoucherService c2cPaymentVoucherService;
    @Resource
    private RedisUtils redisUtils;


    /**
     *  发送普通消息
     * @param dto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveMsg(C2cMsgContentDTO dto) throws Exception{
        C2cMsgContentEntity msgEntity = new C2cMsgContentEntity();
        msgEntity.setSenderId(dto.getSenderId());
        msgEntity.setRecipientId(dto.getRecipientId());
        msgEntity.setContent(dto.getContent());
        msgEntity.setMsgType(dto.getMsgType().toLowerCase());
        msgEntity.setStatus(MsgStatusEnum.SEND.getCode());
        msgEntity.setSendTime(new Date());
        if(save(msgEntity)) {
            // 保存消息关系
            c2cMsgRelationService.saveMsgRelation(msgEntity);

            // 保存最近联系人
            c2cMsgContactService.saveByMsgContact(msgEntity);

            //总未读数更新 2001534_UNREAD_T
            redisUtils.increment(CacheConstants.getTotalUnreadKey(msgEntity.getRecipientId()), 1L,-1L);
            //聊天用户未读数更新
            redisUtils.increment(CacheConstants.getChatUnreadKey(msgEntity.getRecipientId()), msgEntity.getSenderId().toString(), 1L, -1L);
        }
        return new Result().ok(msgEntity);
    }


    /**
     * 保存c2c订单消息
     * @param dto
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public Result saveC2cOrderMsg(C2cMsgContentDTO dto) throws Exception{
        C2cMsgContentEntity msgEntity = new C2cMsgContentEntity();
        msgEntity.setSenderId(dto.getSenderId());
        msgEntity.setRecipientId(dto.getRecipientId());
        msgEntity.setContent(dto.getContent());
        msgEntity.setMsgType(MsgTypeEnum.C2CORDER.name().toLowerCase());
        msgEntity.setStatus(MsgStatusEnum.SEND.getCode());
        msgEntity.setSendTime(new Date());
        if(save(msgEntity)) {
            // 存收件人的收件箱
            c2cMsgRelationService.saveRecipientMsg(msgEntity);

            // 保存收件人的最近联系人
            c2cMsgContactService.saveReceiptUserMsgContact(msgEntity);

            //总未读数更新 2001534_UNREAD_T
            redisUtils.increment(CacheConstants.getTotalUnreadKey(msgEntity.getRecipientId()), 1L,-1L);
            //聊天用户未读数更新
            redisUtils.increment(CacheConstants.getChatUnreadKey(msgEntity.getRecipientId()), msgEntity.getSenderId().toString(), 1L, -1L);
        }
        return new Result().ok(msgEntity);
    }

    @Override
    public void sendOrderCreateMsg(Long buyId, Long sellId, Long orderId,String orderNo) {
        // 买家收到消息
        C2cMsgContentDTO dto = new C2cMsgContentDTO();
        dto.setSenderId(sellId);
        dto.setRecipientId(buyId);
        C2cOrderMsgContentDTO msgContent = new C2cOrderMsgContentDTO();
        msgContent.setTitle("您有一笔待支付的订单，请及时支付");
        msgContent.setDescription("");
        msgContent.setOrderId(orderId);
        msgContent.setOrderNo(orderNo);
        msgContent.setLinkName("去付款");
        msgContent.setLinkCode("Pay");
        dto.setContent(JSON.toJSONString(msgContent));
        try {
            saveC2cOrderMsg(dto);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        // 卖家收到消息
        C2cMsgContentDTO sellDto = new C2cMsgContentDTO();
        sellDto.setSenderId(buyId);
        sellDto.setRecipientId(sellId);
        C2cOrderMsgContentDTO sellMsgContent = new C2cOrderMsgContentDTO();
        sellMsgContent.setTitle("您有一笔出售订单，等待对方支付");
        sellMsgContent.setDescription("买家正在向您转账，请注意查收");
        sellMsgContent.setOrderId(orderId);
        sellMsgContent.setOrderNo(orderNo);
        sellMsgContent.setLinkName("");
        sellMsgContent.setLinkCode("");
        sellDto.setContent(JSON.toJSONString(sellMsgContent));
        try {
            saveC2cOrderMsg(sellDto);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public void sendOrderCancelMsg(Long buyId, Long sellId, Long orderId,String orderNo) {
        // 买家收到消息
        C2cMsgContentDTO dto = new C2cMsgContentDTO();
        dto.setSenderId(sellId);
        dto.setRecipientId(buyId);
        C2cOrderMsgContentDTO msgContent = new C2cOrderMsgContentDTO();
        msgContent.setTitle(new StringBuilder("订单(").append(orderNo).append(")已取消").toString());
        msgContent.setDescription("如已付款，请联系对方要求退款，或联系客服求助");
        msgContent.setOrderId(orderId);
        msgContent.setOrderNo(orderNo);
        msgContent.setLinkName("获得帮助");
        msgContent.setLinkCode("Help");
        dto.setContent(JSON.toJSONString(msgContent));
        try {
            saveC2cOrderMsg(dto);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        // 卖家收到消息
        C2cMsgContentDTO sellDto = new C2cMsgContentDTO();
        sellDto.setSenderId(buyId);
        sellDto.setRecipientId(sellId);
        C2cOrderMsgContentDTO sellMsgContent = new C2cOrderMsgContentDTO();
        sellMsgContent.setTitle("您有一笔出售订单，等待对方支付");
        sellMsgContent.setDescription("买家正在向您转账，请注意查收");
        sellMsgContent.setOrderId(orderId);
        sellMsgContent.setOrderNo(orderNo);
        sellMsgContent.setLinkName("");
        sellMsgContent.setLinkCode("");
        sellDto.setContent(JSON.toJSONString(sellMsgContent));
        try {
            saveC2cOrderMsg(sellDto);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public void sendOrderPayMsg(Long buyId, Long sellId, Long orderId,String orderNo) {
        // 买家收到消息
        C2cMsgContentDTO dto = new C2cMsgContentDTO();
        dto.setSenderId(sellId);
        dto.setRecipientId(buyId);
        C2cOrderMsgContentDTO msgContent = new C2cOrderMsgContentDTO();
        msgContent.setTitle("已付款，等待卖家确认收款");
        msgContent.setDescription("");
        msgContent.setOrderId(orderId);
        msgContent.setOrderNo(orderNo);
        msgContent.setLinkName("查看详情");
        msgContent.setLinkCode("OrderDetail");
        dto.setContent(JSON.toJSONString(msgContent));
        try {
            saveC2cOrderMsg(dto);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        // 卖家收到消息
        C2cMsgContentDTO sellDto = new C2cMsgContentDTO();
        sellDto.setSenderId(buyId);
        sellDto.setRecipientId(sellId);
        C2cOrderMsgContentDTO sellMsgContent = new C2cOrderMsgContentDTO();
        sellMsgContent.setTitle("买家已付款，请确认收款");
        sellMsgContent.setDescription("");
        sellMsgContent.setOrderId(orderId);
        sellMsgContent.setOrderNo(orderNo);
        sellMsgContent.setLinkName("确认");
        sellMsgContent.setLinkCode("verifyReceipt");
        sellDto.setContent(JSON.toJSONString(sellMsgContent));
        try {
            saveC2cOrderMsg(sellDto);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        //发送付款凭证
        sendPayVoucherMsg(buyId, sellId, orderId, orderNo);

    }

    //发送付款凭证
    private void sendPayVoucherMsg(Long buyId, Long sellId, Long orderId,String orderNo) {
        List<C2cPaymentVoucherEntity> list = c2cPaymentVoucherService.selectList(orderId);
        if(list!=null && list.size()>0) {
            C2cMsgContentDTO payVDto = new C2cMsgContentDTO();
            payVDto.setSenderId(buyId);
            payVDto.setRecipientId(sellId);
            payVDto.setContent("请查看支付凭证");
            payVDto.setMsgType(MsgTypeEnum.TEXT.name());
            try {
                saveMsg(payVDto);
            } catch (Exception e) {
                log.error(e.getMessage());
            }

            for(C2cPaymentVoucherEntity pv:list) {
                C2cMsgContentDTO payVImageDto = new C2cMsgContentDTO();
                payVImageDto.setSenderId(buyId);
                payVImageDto.setRecipientId(sellId);
                payVImageDto.setContent(pv.getImg());
                payVImageDto.setMsgType(MsgTypeEnum.IMAGE.name());
                try {
                    saveMsg(payVImageDto);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    @Override
    public void sendOrderCompleteMsg(Long buyId, Long sellId, Long orderId,String orderNo) {
        // 买家收到消息
        C2cMsgContentDTO dto = new C2cMsgContentDTO();
        dto.setSenderId(sellId);
        dto.setRecipientId(buyId);
        C2cOrderMsgContentDTO msgContent = new C2cOrderMsgContentDTO();
        msgContent.setTitle("卖家已确认收款，交易完成");
        msgContent.setDescription("资产已经存入您的资金账户");
        msgContent.setOrderId(orderId);
        msgContent.setOrderNo(orderNo);
        msgContent.setLinkName("查看资产");
        msgContent.setLinkCode("UserAsset");
        dto.setContent(JSON.toJSONString(msgContent));
        try {
            saveC2cOrderMsg(dto);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        // 卖家收到消息
        C2cMsgContentDTO sellDto = new C2cMsgContentDTO();
        sellDto.setSenderId(buyId);
        sellDto.setRecipientId(sellId);
        C2cOrderMsgContentDTO sellMsgContent = new C2cOrderMsgContentDTO();
        sellMsgContent.setTitle("交易完成");
        sellMsgContent.setDescription(new StringBuilder("订单(").append(orderNo).append(")已完成交易").toString());
        sellMsgContent.setOrderId(orderId);
        sellMsgContent.setOrderNo(orderNo);
        sellMsgContent.setLinkName("");
        sellMsgContent.setLinkCode("");
        sellDto.setContent(JSON.toJSONString(sellMsgContent));
        try {
            saveC2cOrderMsg(sellDto);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

}