package com.platform.service.impl;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.platform.dao.DataInfoDao;
import com.platform.dao.PreDataInfoDao;
import com.platform.entities.CheckoutEntity;
import com.platform.entities.DataInfoEntity;
import com.platform.entities.PreDataInfo;
import com.platform.service.CheckoutService;
import com.platform.utils.BeanCopy;
import com.platform.utils.DateForm;

public class CheckoutServiceImpl implements CheckoutService {
	
	@Resource(name = "preDataInfoDao")
	private PreDataInfoDao preDataInfoDao;
	
	@Resource(name = "dataInfoDao")
	private DataInfoDao dataInfoDao;

	@Override
	public List<PreDataInfo> findAll() throws Exception {
		List<PreDataInfo> result = preDataInfoDao.findAllCollect();
		DataInfoEntity data = new DataInfoEntity();
		 Calendar c2 = Calendar.getInstance();
		 // 时间设置为 半年前的时间
		 c2.set(Calendar.MONTH, getMonBeforeHalfYear(c2.get(Calendar.MONTH)));
		 String time = DateForm.date2StringByDay(c2.getTime());
		 data.setCollectingTime(time);
//		data.setCollectingTime(collectingTime);
		 Map<String, DataInfoEntity> dataMap = new HashMap<String, DataInfoEntity>();
		List<DataInfoEntity> datas = dataInfoDao.findByParam(data );
		for (DataInfoEntity dataInfoEntity : datas) {
			String key = dataInfoEntity.getRegionalismCode().toLowerCase()+"_"+ dataInfoEntity.getSystemCode();
			if (dataMap.keySet().contains(key)) {
				if(dataInfoEntity.getDataVersion() > dataMap.get(key).getDataVersion())
					dataMap.put(key, dataInfoEntity);
			}
			else{
				dataMap.put(key, dataInfoEntity);
			}
		}
		for (PreDataInfo pre : result) {
			String key = pre.getAreaCode().toLowerCase()+"_"+ pre.getSysCode();
			DataInfoEntity dataInfo = dataMap.get(key);
			CheckoutEntity ck = new CheckoutEntity();
			BeanCopy.copyField(pre, ck);
			String pay = dataInfo.getPayResult();
			String exec = dataInfo.getExecResult();
			ck.setPayResult(pay);
			ck.setExecResult(exec);
			ck.setCheckResult(isY(pay,exec));
		}
		return result;
	}

	@Override
	public void checkAll() {

	}
	
	private int getMonBeforeHalfYear(int num){
		num -= 6;
		if (num <= 0) {
			num = num + 12;
		}
		return num;
	}
	
	private String isY(String str1, String str2) {
		String r = "n";
		if (null !=str2 && null !=str1 && str1.equals(str2) && "y".equals(str1.toLowerCase())) {
			r = "y";
		}
		return r;
	}

}
