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

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.business.contract.dao.ContractDetailDao;
import com.jy.business.contract.dao.ContractInfoDao;
import com.jy.business.contract.model.dto.ContractInfoDto;
import com.jy.business.contract.model.dto.ContractInfoSelectDto;
import com.jy.business.contract.model.entity.ContractDetail;
import com.jy.business.contract.model.entity.ContractInfo;
import com.jy.business.contract.model.vo.ContractInfoVo;
import com.jy.business.contract.service.ContractInfoService;
import com.jy.framework.utils.AssertUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 合同 服务实现类
 * </p>
 *
 * @author
 * @since 2025-01-07
 */
@Service
public class ContractInfoServiceImpl implements ContractInfoService {

    @Resource
    private ContractInfoDao contractInfoDao;

    @Resource
    private ContractDetailDao contractDetailDao;

    @Override
    public Page<ContractInfoVo> getPage(ContractInfoSelectDto dto) {
        return contractInfoDao.getPage(dto);
    }

    @Override
    public ContractInfoVo getDetail(Long id) {
        ContractInfoVo vo = contractInfoDao.getDetail(id);
        AssertUtil.notNull(vo, "未知数据");

        List<ContractDetail> list = contractDetailDao.lambdaQuery().eq(ContractDetail::getContractId, id).list();
        vo.setList(list);

        return vo;
    }

    @Override
    public ContractInfoVo getDetailByCapitalTransactionsId(Long id) {
        ContractInfo contractInfo = contractInfoDao.lambdaQuery().eq(ContractInfo::getCapitalTransactionsId, id).one();
        AssertUtil.notNull(contractInfo, "没用找到关联合同");

        return getDetail(contractInfo.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(ContractInfoDto dto) {
        contractInfoDao.save(dto);

        List<ContractDetail> list = dto.getList();
        list.forEach(item -> item.setContractId(dto.getId()));
        contractDetailDao.saveBatch(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ContractInfoDto dto) {
        contractInfoDao.updateById(dto);

        List<ContractDetail> list = dto.getList();
        list.forEach(item -> item.setContractId(dto.getId()));
        contractDetailDao.updateLinked(list, ContractDetail::getContractId, dto.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Long> idList) {
        contractInfoDao.removeBatchByIds(idList);
        contractDetailDao.lambdaUpdate().in(ContractDetail::getContractId, idList).remove();
    }

}
