package userio.service.impl;

import common.model.Contract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tkio.repository.AccountRepository;
import tkio.service.AccountService;
import userio.model.Account;
import userio.repository.IOAccountRepository;
import userio.service.AccountIOService;
import util.DateUtil;
import util.ValidateUtil;

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

/**
 * Created by mxq on 2018/1/23.
 */
@Service
public class AccountIOServiceImpl implements AccountIOService {

    @Autowired
    IOAccountRepository accountRepository;
    @Override
    public Account update(Contract contract) {
        Account account = accountRepository.findByEmail(contract.getEmail());
        String today = DateUtil.getBeforeDays(0);
        Date pubDate = DateUtil.getDate(contract.getStartDate());

        account.setPastDate(contract.getEndDate());
        account.setNewContract(true);
        account.setPubDate(pubDate);
        account.setModifyPricelevelTime(contract.getStartDate());
        account.setModifyTime(new Date());
        account.setModifyAccount(0l);
        account.setPricelevel(contract.getPriceLevel());
        if(!(contract.getEndDate().compareTo(today) < 0)){
            account.setStatus(1);
        }
        Account save = accountRepository.save(account);

        //修改子账号
        List<Account> accountList = accountRepository.findByRootParent(account.getId());
        if (ValidateUtil.isValid(accountList)){
            List<Account> list = new ArrayList<>();
            for(Account ac : accountList){
                ac.setPastDate(contract.getEndDate());
                ac.setPubDate(pubDate);
                ac.setModifyPricelevelTime(contract.getStartDate());
                ac.setPricelevel(contract.getPriceLevel());
                list.add(ac);
            }
            accountRepository.save(list);
        }
        return save;
    }

    @Override
    public Account forbiden(Contract contract) {
        Account account = accountRepository.findByEmail(contract.getEmail());
        account.setStatus(0);
        return accountRepository.save(account);
    }
}
