package com.ruoyi.cai.ws.service;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.cai.domain.Account;
import com.ruoyi.cai.service.AccountService;
import com.ruoyi.cai.trd.ImDataRes;
import com.ruoyi.cai.trd.ImMsgGen;
import com.ruoyi.yunxin.Yunxin;
import com.ruoyi.cai.ws.bean.Room;
import com.ruoyi.cai.ws.bean.RoomData;
import com.ruoyi.cai.ws.bean.UserData;
import com.ruoyi.cai.ws.cache.OnlineDataCache;
import com.ruoyi.cai.ws.cache.RoomDataCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SettleService {

    @Autowired
    private RoomService roomService;
    @Autowired
    private RoomDataCache roomDataCache;
    @Autowired
    private AccountService accountService;
    @Autowired
    private OnlineDataCache onlineDataCache;
    @Autowired
    private Yunxin yunxin;

    public void processOn(Room room){
        try {
            deal(room);
        }finally {

        }
    }

    private void deal(Room room){
        if(room.isCanCall() || room.isSettle()){
            return;
        }
        if(!room.isReleaseRes()){
            roomService.releaseRes(Long.valueOf(room.getRoomId()));
            return;
        }
        // 结算
        if(!settle(room)){
            return;
        }
        // 移除在线房间状态
        onlineDataCache.remove(room.getRoomId());
        // 更新支付金额信息
        Map<String,Object> map = new HashMap<>();
        map.put("payCoin", ""); // 实际支付的金额
        map.put("payIncome", "");
        map.put("settleTime", DateUtil.currentSeconds());
        roomDataCache.hMSet(Long.valueOf(room.getRoomId()),map);
        // 主叫方通话市场通知
        Long callTime = roomService.getCallTime(room);
        Long receiverUserId = room.getReceiverUserData().getId();
        Long callUserId = room.getCallUserData().getId();
        if(callTime > 0){
            ImDataRes imDataRes = ImMsgGen.callNotice(4, receiverUserId, callUserId, callTime);
            yunxin.sendTo(room.getCallUserData().getId(),room.getReceiverUserData().getId(),imDataRes);
        }
        // 收入通知
        if(room != null){ // TODO修改数据

        }
        // 邀请人收入通知
        // 排行榜通知
    }

    /**
     * 结算
     */
    private boolean settle(Room room){
        Long roomId = room.getRoomId();
        // 未通话，无需结算
        if(room.getRoomData().getBeginTime() == null){
            roomDataCache.hMSet(roomId,"settleTime", DateUtil.currentSeconds());
            return false;
        }
        // 开始结算
        // 呼叫方扣费
        this.computeCallerPay(room);
        // 结束结算
        return true;
    }

    private void computeCallerPay(Room room) {
        RoomData roomData = room.getRoomData();
        UserData callUserData = room.getCallUserData();
        Long callPrice = roomData.getCallPrice();
        Long callTime = roomService.getCallTime(room);
        // 本次支付金额
        Long totalAmount = callPrice * (callTime / 60);
        // 补差价
        Long diff = totalAmount - roomData.getPayCoin() + roomData.getPayIncome();

        Account callAccount = accountService.getByUserId(callUserData.getId());
        Long userAmount = callAccount.getCoin() + callAccount.getIncomeCoin();
        if(diff > 0){
            // 账户上面有余额
            if(userAmount > 0){
                diff = (userAmount > diff) ? diff : userAmount;
                log.info("roomid {} 已支付 {}  仍需要补差价：{}", roomData.getRoomId(),roomData.getPayCoin() + roomData.getPayIncome(),diff);
                // TODO 对账户进行统一扣费

            }else{
                log.info("房间需要补差价，但用户余额不足 roomid {} 已支付 {}  仍需要补差价：{}", roomData.getRoomId(),roomData.getPayCoin() + roomData.getPayIncome(),diff);
            }
        }else{
            // 退钱逻辑
            diff = Math.abs(diff);
            // TODO 对账户进行统一退钱逻辑
        }
    }
}
