package com.ym.mec.biz.service.impl;

import com.ym.mec.biz.dal.dao.StudentPaymentOrderDao;
import com.ym.mec.biz.dal.dao.SysAccountDao;
import com.ym.mec.biz.dal.entity.SysAccount;
import com.ym.mec.biz.dal.entity.SysArea;
import com.ym.mec.biz.service.SysAccountService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.date.DateUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class SysAccountServiceImpl extends BaseServiceImpl<Integer, SysAccount> implements SysAccountService {

    @Autowired
    private SysAccountDao sysAccountDao;
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;

    @Override
    public BaseDAO<Integer, SysAccount> getDAO() {
        return sysAccountDao;
    }

    @Override
    public List<SysAccount> getAccount(String company, String channel, String type, BigDecimal amount) {
        return sysAccountDao.getAccount(company, channel, type, amount);
    }

    @Override
    public SysAccount getOneAccount(String company, String channel, String type, BigDecimal amount) {
        return sysAccountDao.getOneAccount(company, channel, type, amount);
    }

    @Override
    public SysAccount getPerAccount(String channel, SysAccount account) {
        BigDecimal maxReceive = new BigDecimal("75000");
        Date nowDate = new Date();
        Date firstDayOfMonth = DateUtil.getFirstDayOfMonth(nowDate);

        BigDecimal amount = studentPaymentOrderDao.sumPerAccountAmount(account.getRoutingMerNo(),firstDayOfMonth);

        if (amount == null || amount.compareTo(maxReceive) < 0) {
            return account;
        }

        SysAccount newAccount = null;
        List<SysAccount> perAccounts = sysAccountDao.getPerAccount(channel);
        for (SysAccount perAccount : perAccounts) {
            amount = studentPaymentOrderDao.sumPerAccountAmount(perAccount.getRoutingMerNo(),firstDayOfMonth);
            if (amount == null || amount.compareTo(maxReceive) < 0) {
                newAccount = perAccount;
                break;
            }
        }
        return newAccount;
    }

}