package com.kym.service.impl;

import com.github.pagehelper.PageHelper;
import com.kym.common.exception.BusinessException;
import com.kym.entity.PlatformAccount;
import com.kym.entity.common.PageBean;
import com.kym.entity.queryParams.CommonQueryParam;
import com.kym.mapper.PlatformAccountMapper;
import com.kym.service.PlatformAccountService;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 平台账户服务实现
 *
 * @author skyline
 * @since 2026-05-18
 */
@Service
public class PlatformAccountServiceImpl extends MyBaseServiceImpl<PlatformAccountMapper, PlatformAccount> implements PlatformAccountService {

    @Override
    public PlatformAccount getPlatformAccount() {
        var account = lambdaQuery().last("LIMIT 1").one();
        if (account == null) {
            account = new PlatformAccount();
            account.setTotalRevenue(0);
            account.setAvailableBalance(0);
            account.setWithdrawnFrozenAmount(0);
            account.setWithdrawnAmount(0);
            save(account);
        }
        return account;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRevenue(int amount) {
        if (amount <= 0) {
            return;
        }
        boolean updated = lambdaUpdate()
                .setSql("total_revenue = total_revenue + {0}", amount)
                .setSql("available_balance = available_balance + {0}", amount)
                .eq(PlatformAccount::getId, getPlatformAccount().getId())
                .update();
        if (!updated) {
            throw new BusinessException("平台账户更新失败");
        }
    }

    @Override
    public PageBean<PlatformAccount> listPlatformAccounts(CommonQueryParam params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        var list = lambdaQuery().list();
        return new PageBean<>(list);
    }
}
