package com.ssj.service.sys.fx.service.impl;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;

import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.fx.domain.MerchantBackup;
import com.ssj.dao.sys.fx.dao.MerchantBackupDao;
import com.ssj.dao.sys.fx.dao.MerchantDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.persistence.DynamicSpecifications;
import com.ssj.framework.core.persistence.SearchFilter;
import com.ssj.service.sys.fx.service.MerchantBackupService;


@Service
public class MerchantBackupServiceImpl extends BaseServiceImpl<MerchantBackup, String> implements MerchantBackupService {
	
	private  Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private MerchantBackupDao dao;
	
	@Autowired
	private MerchantDao merchantDao;

    @Override
    public PagingAndSortingRepository<MerchantBackup, String> getDao() {
        return dao;
    }

	@Override
	public Page<MerchantBackup> findMerchantBackupByPage(Map<String, Object> params,Pageable sp) {
		Map<String, SearchFilter> filters = SearchFilter.parse(params);
		Specification<MerchantBackup> specification = DynamicSpecifications.bySearchFilter(filters.values(), MerchantBackup.class);
		return dao.findAll(specification, sp);
	}
    
	@Override
	public void runMerchantBackup() {
		logger.info("备份保存上个月的商户数据，任务开始...");
		List<MerchantBackup> merchantBackups=new ArrayList<MerchantBackup>();
		List<Merchant> merchants=merchantDao.findAll();
		for (Merchant merchant : merchants) {
			try {
				MerchantBackup merchantBackup=new MerchantBackup();
				BeanUtils.copyProperties(merchant, merchantBackup);
				merchantBackup.setId(null);
				merchantBackup.setMerchantId(merchant.getId());
				merchantBackup.setBackupMonth(DateHelper.formatDateByFormat(DateHelper.getLastMonthFirstDay(new Date()), "yyyy-MM").replace("/", ""));
				merchantBackups.add(merchantBackup);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		this.save(merchantBackups);
		logger.info("备份保存上个月的商户数据，任务结束。.");
	}
    
    
    
    


}


