package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.OaJournalAccountBo;
import com.ruoyi.oa.domain.vo.OaJournalAccountVo;
import com.ruoyi.oa.domain.OaJournalAccount;
import com.ruoyi.oa.mapper.OaJournalAccountMapper;
import com.ruoyi.oa.service.IOaJournalAccountService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 日记账（绑定封账批次，未封账数据batch_id为NULL）Service业务层处理
 *
 * @author Joshi
 * @date 2025-09-09
 */
@RequiredArgsConstructor
@Service
public class OaJournalAccountServiceImpl implements IOaJournalAccountService {

    private final OaJournalAccountMapper baseMapper;

    /**
     * 查询日记账（绑定封账批次，未封账数据batch_id为NULL）
     */
    @Override
    public OaJournalAccountVo queryById(Long journalId){
        return baseMapper.selectVoById(journalId);
    }

    /**
     * 查询日记账（绑定封账批次，未封账数据batch_id为NULL）列表
     */
    @Override
    public TableDataInfo<OaJournalAccountVo> queryPageList(OaJournalAccountBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OaJournalAccount> lqw = buildQueryWrapper(bo);
        Page<OaJournalAccountVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询日记账（绑定封账批次，未封账数据batch_id为NULL）列表
     */
    @Override
    public List<OaJournalAccountVo> queryList(OaJournalAccountBo bo) {
        LambdaQueryWrapper<OaJournalAccount> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OaJournalAccount> buildQueryWrapper(OaJournalAccountBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OaJournalAccount> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAccountId() != null, OaJournalAccount::getAccountId, bo.getAccountId());
        lqw.eq(bo.getRecordDate() != null, OaJournalAccount::getRecordDate, bo.getRecordDate());
        lqw.eq(StringUtils.isNotBlank(bo.getOppositeSubject()), OaJournalAccount::getOppositeSubject, bo.getOppositeSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getSummary()), OaJournalAccount::getSummary, bo.getSummary());
        lqw.eq(bo.getIncomeAmount() != null, OaJournalAccount::getIncomeAmount, bo.getIncomeAmount());
        lqw.eq(bo.getExpendAmount() != null, OaJournalAccount::getExpendAmount, bo.getExpendAmount());
        lqw.eq(bo.getBalance() != null, OaJournalAccount::getBalance, bo.getBalance());
        lqw.eq(bo.getBatchId() != null, OaJournalAccount::getBatchId, bo.getBatchId());
        return lqw;
    }

    /**
     * 新增日记账（绑定封账批次，未封账数据batch_id为NULL）
     */
    @Override
    public Boolean insertByBo(OaJournalAccountBo bo) {
        OaJournalAccount add = BeanUtil.toBean(bo, OaJournalAccount.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setJournalId(add.getJournalId());
        }
        return flag;
    }

    /**
     * 修改日记账（绑定封账批次，未封账数据batch_id为NULL）
     */
    @Override
    public Boolean updateByBo(OaJournalAccountBo bo) {
        OaJournalAccount update = BeanUtil.toBean(bo, OaJournalAccount.class);
        validEntityBeforeSave(update);
        // 如果BatchId不为空，说明该批次数据已被封账，不能修改
        OaJournalAccount oaJournalAccount = baseMapper.selectById(update.getJournalId());
        if (oaJournalAccount.getBatchId()!=null) {
            throw new ServiceException("该批次数据已被封账，不能进行修改操作");
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OaJournalAccount entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除日记账（绑定封账批次，未封账数据batch_id为NULL）
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        //如果journalId不为空，说明该批次数据已被封账，不能删除
        // 查询要删除的记录中是否有已封账的数据（batch_id不为null的记录）
        List<OaJournalAccount> journalAccounts = baseMapper.selectList(
                new LambdaQueryWrapper<OaJournalAccount>()
                        .in(OaJournalAccount::getJournalId, ids)
                        .isNotNull(OaJournalAccount::getBatchId)
        );

        // 如果存在已封账的数据，则不能删除
        if (!journalAccounts.isEmpty()) {
            throw new ServiceException("选中的数据中包含已封账记录，不能进行删除操作");
        }
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional
    public int batchUpdate(OaJournalAccountBo bo) {
        // 参数校验
        if (bo.getJournalIds() == null || bo.getJournalIds().isEmpty()) {
            return 0;
        }

        if (bo.getBatchId() == null) {
            throw new ServiceException("批次ID不能为空");
        }

        int count = 0;
        // 循环遍历list数组然后修改batchId
        for (Long journalId : bo.getJournalIds()) {
            // 检查记录是否存在且未封账
            OaJournalAccount existing = baseMapper.selectById(journalId);
            if (existing == null) {
                throw new ServiceException("记录不存在，ID: " + journalId);
            }

            if (existing.getBatchId() != null) {
                throw new ServiceException("记录已封账，不能重复封账，ID: " + journalId);
            }

            OaJournalAccount oaJournalAccount = new OaJournalAccount();
            oaJournalAccount.setJournalId(journalId);
            oaJournalAccount.setBatchId(bo.getBatchId());
            count += baseMapper.updateById(oaJournalAccount);
        }
        return count;
    }

}
