package com.ruoyi.web.arap.service.impl;

import com.ruoyi.web.arap.domain.vo.ArapDeductItemVo;
import com.ruoyi.web.arap.mapper.ArapDeductMapper;
import com.ruoyi.web.arap.service.IArapDeductService;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ArapDeductServiceImpl implements IArapDeductService {

    @Autowired
    private ArapDeductMapper arapDeductMapper;

    @Override
    public List<ArapDeductItemVo> listByDate(String orgId, Date bizDate) {
        return arapDeductMapper.selectDeductList(orgId, bizDate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchDeduct(String orgId, String operator, List<ArapDeductItemVo> rows) {
        return doBatchSet(orgId, operator, rows, "1");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchUndeduct(String orgId, String operator, List<ArapDeductItemVo> rows) {
        return doBatchSet(orgId, operator, rows, "0");
    }

    private int doBatchSet(String orgId, String operator, List<ArapDeductItemVo> rows, String value) {
        if (rows == null || rows.isEmpty()) {
            throw new ServiceException("提交失败，至少选择一条数据");
        }
        int n = 0;
        for (ArapDeductItemVo row : rows) {
            if (row == null || row.getDocId() == null || row.getDocType() == null) {
                continue;
            }
            if ("收款单".equals(row.getDocType())) {
                n += arapDeductMapper.updateRecvDeducted(row.getDocId(), orgId, value, operator);
            } else if ("退款单".equals(row.getDocType())) {
                n += arapDeductMapper.updateRefundDeducted(row.getDocId(), orgId, value, operator);
            }
        }
        return n;
    }
}

