package cn.com.qmth.stmms.biz.subjectheader.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.qmth.stmms.biz.distributpaper.dao.FormallyLibraryDao;
import cn.com.qmth.stmms.biz.distributpaper.dao.TryLibraryDao;
import cn.com.qmth.stmms.biz.distributpaper.model.FormallyLibrary;
import cn.com.qmth.stmms.biz.distributpaper.model.TryLibrary;
import cn.com.qmth.stmms.biz.subjectheader.dao.RandomHistoryDao;
import cn.com.qmth.stmms.biz.subjectheader.dao.RandomLibraryDao;
import cn.com.qmth.stmms.biz.subjectheader.model.RandomHistory;
import cn.com.qmth.stmms.biz.subjectheader.model.RandomLibrary;
import cn.com.qmth.stmms.biz.subjectheader.service.RandomHistoryService;
import cn.com.qmth.stmms.biz.subjectheader.service.RandomLibraryService;
import cn.com.qmth.stmms.common.enums.LibraryStatus;

@Service
public class RandomHistoryServiceImpl implements RandomHistoryService {

    @Autowired
    private RandomHistoryDao randomHistoryDao;

    @Autowired
    private RandomLibraryDao randomLibraryDao;

    @Autowired
    private RandomLibraryService randomLibraryService;

    @Autowired
    private TryLibraryDao tryLibraryDao;

    @Autowired
    private FormallyLibraryDao formallyLibraryDao;

    @Transactional
    public RandomHistory save(RandomHistory randomHistory) {
        return randomHistoryDao.save(randomHistory);
    }

    public RandomHistory findById(Integer id) {
        return randomHistoryDao.findOne(id);
    }

    @Transactional
    public void deleteById(Integer id) {
        randomHistoryDao.delete(id);
    }

    @Transactional
    public void delete(RandomHistory randomHistory) {
        randomHistoryDao.delete(randomHistory);
    }

    @Override
    @Transactional
    public void saveRandom(RandomHistory randomHistory) {
        RandomLibrary library = randomLibraryDao.findOne(randomHistory.getLibraryId());
        if (library.getType().getValue() == 1) {
            TryLibrary tryLibrary = tryLibraryDao.findOne(library.getLibraryId());
            tryLibrary.setStatus(LibraryStatus.EXCEPTION);
            tryLibraryDao.save(tryLibrary);
        }

        if (library.getType().getValue() == 2) {
            FormallyLibrary formallyLibrary = formallyLibraryDao.findOne(library.getLibraryId());
            formallyLibrary.setStatus(LibraryStatus.EXCEPTION);
            formallyLibraryDao.save(formallyLibrary);
        }

        library.setStatus(LibraryStatus.MARKED);
        randomLibraryDao.save(library);

        long spent = new Date().getTime() - randomHistory.getSpent();
        randomHistory.setSpent(spent);
        randomHistory.setStatus(LibraryStatus.MARKED);
        randomHistory.setSubmitTime(new Date());
        randomHistoryDao.save(randomHistory);

    }
}
