package com.jy.business.capital.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.business.capital.dao.CapitalAccountDao;
import com.jy.business.capital.dao.CapitalTransactionsDao;
import com.jy.business.capital.model.dto.CapitalAccountDto;
import com.jy.business.capital.model.dto.CapitalAccountSelectDto;
import com.jy.business.capital.model.vo.CapitalAccountVo;
import com.jy.business.capital.service.CapitalAccountService;
import com.jy.framework.utils.AssertUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 资金账户 服务实现类
 * </p>
 *
 * @author
 * @since 2024-10-16
 */
@Service
public class CapitalAccountServiceImpl implements CapitalAccountService {

    @Resource
    private CapitalAccountDao capitalAccountDao;

    @Resource
    private CapitalTransactionsDao capitalTransactionsDao;

    @Override
    public Page<CapitalAccountVo> getPage(CapitalAccountSelectDto dto) {
        return capitalAccountDao.getPage(dto);
    }

    @Override
    public CapitalAccountVo getDetail(Long id) {
        CapitalAccountVo vo = capitalAccountDao.getDetail(id);
        AssertUtil.notNull(vo, "未知数据");
        return vo;
    }

    @Override
    public void add(CapitalAccountDto dto) {
        capitalAccountDao.save(dto);
    }

    @Override
    public void edit(CapitalAccountDto dto) {
        dto.setAmount(null);
        capitalAccountDao.updateById(dto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Long> idList) {
        // 校验资金账户是否存在资金流水
        capitalAccountDao.listByIds(idList).forEach((item) -> {
            boolean capitalAccountExists = capitalTransactionsDao.capitalAccountExists(item.getId());
            AssertUtil.eqFalse(capitalAccountExists, "资金账户【{}】存在资金流水，无法删除", item.getAccountAlias());
        });

        // 删除资金账户
        capitalAccountDao.removeBatchByIds(idList);
    }

}
