package com.ruoyi.cai.ws.handler.message;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.cai.domain.Account;
import com.ruoyi.cai.domain.Gift;
import com.ruoyi.cai.dto.app.query.GiveGiftRes;
import com.ruoyi.cai.service.AccountService;
import com.ruoyi.cai.service.GiftService;
import com.ruoyi.cai.service.UserGiftService;
import com.ruoyi.cai.ws.bean.FdCtxData;
import com.ruoyi.cai.ws.bean.Room;
import com.ruoyi.cai.ws.dto.WsRMsgGen;
import com.ruoyi.cai.ws.handler.IMessageHandler;
import com.ruoyi.cai.ws.handler.AbstractMessageHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("gift")
public class GiftMessageHandler extends AbstractMessageHandle implements IMessageHandler {
    @Autowired
    private GiftService giftService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private UserGiftService userGiftService;
    @Override
    public void processOn(Room room, FdCtxData fdCtxData, JSONObject map) {
        Long giftId = map.getLong("giftId");
        if(giftId == null){
            return;
        }
        Long giftCount = map.getLongValue("giftCount",1L);
        Gift gift = giftService.getById(giftId);
        if(gift == null){
            return;
        }
        Long giftAmount = gift.getPrice() * giftCount;
        Account account = accountService.getByUserId(fdCtxData.getUserId());
        Long userAccount = account.getIncomeCoin() + account.getCoin();
        if(userAccount < giftAmount){
            sendToCurrent(fdCtxData,WsRMsgGen.rechargeNotice("余额不足，点此充值"));
            return;
        }
        if(fdCtxData.isCaller() && (userAccount - giftAmount) < room.getRoomData().getCallPrice()){
            sendToCurrent(fdCtxData,WsRMsgGen.rechargeNotice("赠送后通话时间不足1分钟，点此充值"));
            return;
        }
        GiveGiftRes giveGiftRes = new GiveGiftRes();
        giveGiftRes.setType(3);
        giveGiftRes.setToUserId(fdCtxData.getTarUserId());
        giveGiftRes.setGiftId(giftId);
        giveGiftRes.setGiftCount(giftCount);
        boolean b = userGiftService.giveGift(giveGiftRes);
        if(!b){
            sendToCurrent(fdCtxData,WsRMsgGen.sysNotice("赠送失败，请重试"));
            return;
        }
        sendToAll(room.getRoomId(),WsRMsgGen.gift(gift,fdCtxData.getUserId(),fdCtxData.getTarUserId()));
    }
}
