package tkio.service.impl;

import common.model.Contract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import security.annotation.Authorization;
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) {
        Account account = accountRepository.findByEmail(contract.getEmail());
        String today = DateUtil.getBeforeDays(0);
        Date pubDate = DateUtil.getDate(contract.getStartDate());

        account.setPastDate(contract.getEndDate());
        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);
        }
        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) {
        Account account = accountRepository.findByEmail(contract.getEmail());
        account.setStatus(0);
        return accountRepository.save(account);
    }
}
