package tkio.service.impl;

import common.model.Contract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tkio.model.Account;
import tkio.repository.AccountRepository;
import tkio.service.AccountService;
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 AccountServiceImpl implements AccountService {

    @Autowired
    AccountRepository accountRepository;

    @Override
    public Account update(Contract contract) {

        //暂时 注释改代码
        if(true)    return null;


        Account account = accountRepository.findByEmail(contract.getEmail());
        String today = DateUtil.getBeforeDays(0);
        Date pubDate = DateUtil.getDate(contract.getStartDate());

        account.setPubDate(pubDate);
        account.setPastDate(contract.getEndDate());
        account.setPricelevel(contract.getPriceLevel());

        account.setModifyTime(new Date());
        account.setModifyAccount(0l);
        if(account.getStartByContract()){
            account.setNewContract(true);
            account.setModifyPricelevelTime(contract.getStartDate());

        }
        if(!(contract.getEndDate().compareTo(today) < 0)){
            account.setStatus(1);
        }
        if(contract.getProduct().contains("io")){
            account.setAllowBehavior(true);
        }else{
            account.setAllowBehavior(false);
        }
        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());
                ac.setAllowBehavior(save.getAllowBehavior());
                list.add(ac);
            }
            accountRepository.save(list);
        }
        return save;
    }

    @Override
    public Account forbiden(Contract contract) {
        // 注释功能
        if(true) return null;
        Account account = accountRepository.findByEmail(contract.getEmail());
        account.setStatus(0);
        return accountRepository.save(account);
    }
}
