package com.cku.oa.timedtask.service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.alibaba.fastjson.JSONObject;
import com.cku.oa.sync.dao.VoucherSyncLogDao;
import com.cku.oa.sync.entity.VoucherSyncLog;
import com.ufida.api.request.VoucherAddRequest;
import com.ufida.api.response.UfidaSyncResponse;
import com.ufida.api.service.UfidaVoucherSyncService;
import com.ufida.api.service.VoucherQueryService;

@Service
@Transactional(readOnly = true)
public class UfidaVoucherSyncTask extends JobActingService    {

	private final static Logger LOGGER = LoggerFactory.getLogger(UfidaVoucherSyncTask.class);
	
	private final static SimpleDateFormat SDF_YMD = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private static final Integer VOUCHER_TYPE_CZ = 1;//充值
	
	private static final Integer VOUCHER_TYPE_DD = 2;//订单
	
	private static final Integer VOUCHER_TYPE_TK = 3;//退款
	
	private static final Integer VOUCHER_TYPE_ZZ = 4;//转账

	@Autowired
	private VoucherQueryService voucherQueryService;
	
	@Autowired
	private UfidaVoucherSyncService syncService;
	
	@Autowired
	private VoucherSyncLogDao voucherSyncLogDao;

	@Override
	@Transactional(readOnly = false)
	int doJob() {
		LOGGER.info("========================同步凭证信息--开始============================");
		int count = 0;
		Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        Date startDate = calendar.getTime();
        
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        Date endDate = calendar.getTime();
        
        LOGGER.info("========================统计日期--开始时间：{}结束时间：{}============================",SDF_YMD.format(startDate),SDF_YMD.format(endDate));
        
		try {
			LOGGER.info("========================充值凭证--start============================");
	        this.syncRechargeVoucherData(startDate, endDate);
	        LOGGER.info("========================充值凭证--end============================");
			count++;
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			LOGGER.info("========================订单凭证--start============================");
	        this.syncFinishedOrderVoucherData(startDate, endDate);
	        LOGGER.info("========================订单凭证--end============================");
	        count++;
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			LOGGER.info("========================退款凭证--start============================");
	        this.syncRefundOrderVoucherData(startDate, endDate);
	        LOGGER.info("========================退款凭证--end============================");
	        count++;
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			LOGGER.info("========================转账凭证--start============================");
	        this.syncTransferVoucherData(startDate, endDate);
	        LOGGER.info("========================转账凭证--end============================");
	        count++;
		} catch (Exception e) {
			e.printStackTrace();
		}
		LOGGER.info("========================同步凭证信息--结束============================");
		return count;
	}

	@Override
	@Transactional(readOnly = false)
	public int executeOnce() {
		SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
		return this.doJob();
	}

	private void syncRechargeVoucherData(Date startDate,Date endDate) throws Exception {
        VoucherSyncLog logEntity = new VoucherSyncLog(VOUCHER_TYPE_CZ, new Timestamp(startDate.getTime()), new Timestamp(endDate.getTime()),
				new Timestamp(System.currentTimeMillis()),false,"");
    	VoucherAddRequest request = voucherQueryService.findRechargeVoucherData(startDate,endDate);
    	LOGGER.info("========================充值凭证信息--{}============================",request==null?"":JSONObject.toJSONString(request));
    	if(request != null) {
    		UfidaSyncResponse response = syncService.syncVoucher(request);
    		logEntity.setSyncStatus(response.success());
    		logEntity.setSyncFailReason(response.getMessage());
    	}
		voucherSyncLogDao.insert(logEntity);
	}

	private void syncFinishedOrderVoucherData(Date startDate,Date endDate) throws Exception {
        VoucherSyncLog logEntity = new VoucherSyncLog(VOUCHER_TYPE_DD, new Timestamp(startDate.getTime()), new Timestamp(endDate.getTime()),
				new Timestamp(System.currentTimeMillis()),false,"");
    	VoucherAddRequest request = voucherQueryService.findFinishedOrderVoucherData(startDate,endDate);
    	LOGGER.info("========================订单凭证信息--{}============================",request==null?"":JSONObject.toJSONString(request));
    	if(request != null) {
    		UfidaSyncResponse response = syncService.syncVoucher(request);
    		logEntity.setSyncStatus(response.success());
    		logEntity.setSyncFailReason(response.getMessage());
    	}
    	voucherSyncLogDao.insert(logEntity);
	}

    private void syncRefundOrderVoucherData(Date startDate,Date endDate) throws Exception {
        VoucherSyncLog logEntity = new VoucherSyncLog(VOUCHER_TYPE_TK, new Timestamp(startDate.getTime()), new Timestamp(endDate.getTime()),
				new Timestamp(System.currentTimeMillis()),false,"");
    	VoucherAddRequest request = voucherQueryService.findRefundOrderVoucherData(startDate,endDate);
    	LOGGER.info("========================退款凭证信息--{}============================",request==null?"":JSONObject.toJSONString(request));
    	if(request != null) {
    		UfidaSyncResponse response = syncService.syncVoucher(request);
    		logEntity.setSyncStatus(response.success());
    		logEntity.setSyncFailReason(response.getMessage());
    	}
    	voucherSyncLogDao.insert(logEntity);
	}

    private void syncTransferVoucherData(Date startDate,Date endDate) throws Exception {
        VoucherSyncLog logEntity = new VoucherSyncLog(VOUCHER_TYPE_ZZ, new Timestamp(startDate.getTime()), new Timestamp(endDate.getTime()),
				new Timestamp(System.currentTimeMillis()),false,"");
    	VoucherAddRequest request = voucherQueryService.findTransferVoucherData(startDate,endDate);
    	LOGGER.info("========================转账凭证信息--{}============================",request==null?"":JSONObject.toJSONString(request));
    	if(request != null) {
    		UfidaSyncResponse response = syncService.syncVoucher(request);
    		logEntity.setSyncStatus(response.success());
    		logEntity.setSyncFailReason(response.getMessage());
    	}
    	voucherSyncLogDao.insert(logEntity);
	}

	 

}