package com.ajb.car.schedule;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

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

import com.ajb.car.entity.apimessage.AgTransVehicleMsgOrigin;
import com.ajb.car.entity.quotation.AgPoQuotation;
import com.ajb.car.metadata.service.SystemConfigService;
import com.ajb.car.quotation.AgPoQuotationWebService;
import com.ajb.car.quotation.service.AgPoQuotationService;
import com.ajb.car.quotation.service.AgTransVehicleMsgOriginService;
import com.ajb.car.vo.zhima.TokenZhiMa;
import com.ajb.car.vo.zhima.policy.PolicyInfo;
import com.ajb.car.vo.zhima.policy.PolicyResponse;
import com.ajb.car.vo.zhima.quotation.QuotationDetail;
import com.ajb.car.vo.zhima.quotation.QuotationResponse;
import com.ajb.common.utils.http.HttpHelpZhiMa;

import com.alibaba.fastjson.JSON;

/**
* 定时任务
* @service和@Component有一个即可，否则自动任务不会被启动
* @EnableScheduling  是必须
*/
@Service("ScheduledTaskService")
//@EnableScheduling 
public class ScheduledTaskService {
	@Autowired
	private SystemConfigService systemConfigService;
	
	@Autowired
	AgPoQuotationWebService	agPoQuotationWebService;
	
	@Autowired
	AgPoQuotationService	agPoQuotationService;

	//Map<String , String> map = new HashMap<String , String>();
	
	private static String hostURL = "";// "https://baoxian.linkersoft.com/tbjap/";
	//获取token
	//private static String auth2ParamTest = "{\r\n\t\"unitid\": \"LKTEST\",\r\n\t\"pwd\": \"password\",\r\n\t\"secretid\": \"1aaca8b5fb364267a9d3b56474157cf6\"\r\n}\r\n";	
	private static String auth2ParamProduction1 = "";// "{\r\n\t\"unitid\": \"SHYD\",\r\n\t\"pwd\": \"shyd1234\",\r\n\t\"secretid\": \"ad9a64fb913f4affa8064f2ae51e3b91\"\r\n}\r\n";
	private static String tokenMethod = "";//"api/login";
	//private static String tokenXPath = "$.datas.session.token";
	
	//按品牌查型号
	//private static String queryUrlModelParam = "{\"keyword\":\"%s\"}";
	//private static String queryUrlModelMethod = "api/searchmodel1";
	//private static String queryUrlModelXPath = "$.datas.modelNumbers";
	
	//按型号查详细信息
	//private static String queryUrlModel2Param = "{\"modelNumber\":\"%s\"}";
	//private static String queryUrlModel2Method = "api/searchmodel2";
	//private static String queryUrlModel2XPath = "$.datas.vehiclemodels[*]";

	//报价查询
	//private static String queryUrlCarPriceParam = "{\"carNumber\": \"%s\",	\"carOwner\": \"%s\",	\"plateType\": \"02\",\"bizAttribute\": \"101\"}";
	//private static String queryUrlCarPriceMethod = "api/carpricebynumber";
	//private static String queryUrlCarPriceXPath = "$.datas.priceinfo";
	
	//private static String queryUrlGiftParam =  "{\"policycode\":\"%s\"}";
	//private static String queryURLGift = "api/loadgift";
	
	//报价单加载
	//private static String queryUrlConfirmInfoParam = "{\"policycode\":\"%s\"}";
	//private static String queryUrlConfirmInfoMethod = "api/loadconfirminfo";
	//private static String queryUrlConfirmInfoXPath = "$.datas.confirminfo";
	//报价确认
	//private static String queryUrlConfirmInfoPostMethod = "api/confirmprice";
	
	//报价列表查询
	//private static String queryQuotationURLParam = "{\"status\":\"%s\"}";
	private static String queryQuotationURLScopeParam = "";//"{\"begindate\":\"%s\",\"enddate\":\"%s\"}";
	private static String queryQuotationMethod = "";// "api/policylist?start=%s&count=%s";  
	//private static String queryQuotationXPath = "$.datas.pages.rows[*]";
	
	//获取报价单详情
	private static String queryQuotationDetailMethod = "";//"api/getconfirmpolicydetail?policycode=%s";
	
	@Autowired
	private AgTransVehicleMsgOriginService carZhiMaService;
		
	//@Scheduled(cron = "0/2 * * * * *")
	public QuotationResponse synchQuotaion(Date begin,Date end) throws InterruptedException {		
		auth2ParamProduction1 = systemConfigService.getSingleConfigValue("LinkerSoftAPITokenAuth2Param");
		hostURL = systemConfigService.getSingleConfigValue("LinkerSoftAPIHostURL");
		tokenMethod = systemConfigService.getSingleConfigValue("LinkerSoftAPITokenMethod");
		
		queryQuotationMethod = systemConfigService.getSingleConfigValue("LinkerSoftAPIQueryQuotationMethod");
		queryQuotationURLScopeParam = systemConfigService.getSingleConfigValue("LinkerSoftAPIQueryQuotationURLScopeParam");
		
		queryQuotationDetailMethod = systemConfigService.getSingleConfigValue("LinkerSoftAPIQueryQuotationDetailMethod");
		
		TokenZhiMa tokenEntity = getToken(hostURL + tokenMethod,auth2ParamProduction1);
		
		//写原始消息入表
		AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();				
		agtransvehiclemsgorigin = initOriginMessage(hostURL,tokenMethod,auth2ParamProduction1,"Post",JSON.toJSONString(tokenEntity));
		carZhiMaService.save(agtransvehiclemsgorigin);
		
		String token = tokenEntity.getDatas().getTokenInfo().getToken();		
		System.out.println("token:" + token);
	
		String startTime = dateToString(begin);
		String endTime = dateToString(end);

		return testPolicyList(startTime,endTime,token);
	}
	public static String dateToString(Date time){
	    SimpleDateFormat formatter;
	    formatter = new SimpleDateFormat ("yyyy-MM-dd");
	    String ctime = formatter.format(time);

	    return ctime;
	}
	private QuotationResponse testPolicyList(String startTime,String endTime,String token)
	{
		QuotationResponse quotationResponse;
		quotationResponse = new QuotationResponse();
		QuotationResponse quotationResponsePage = new QuotationResponse();
		Integer start = 0;
		Integer total = 0;
		Integer size = 15;
		
		//询价单列表,按状态,1,2,3
		PolicyResponse policyList = null;
		policyList = queryList(startTime,endTime,start,token);

		total = Integer.parseInt(policyList.getDatas().getPolicyPage().getTotal());
		System.out.println("Total:" + total);
		quotationResponse.setTotal(total);
		while(start < total)
		{
			quotationResponsePage = new QuotationResponse();
			//分页，开始行，页行数queryQuotationURLParam
			System.out.println("start:" + start);
			policyList = queryList(startTime,endTime,start,token);
			
			quotationResponsePage = displayList(policyList.getDatas().getPolicyPage().getRows(),token);	
			
			quotationResponse.setTotalPremium(quotationResponse.getTotalPremium().add(quotationResponsePage.getTotalPremium()));
			quotationResponse.setBzPremium(quotationResponse.getBzPremium().add(quotationResponsePage.getBzPremium()));
			quotationResponse.setTcPremium(quotationResponse.getTcPremium().add(quotationResponsePage.getTcPremium()));
			quotationResponse.setTsltax(quotationResponse.getTsltax().add(quotationResponsePage.getTsltax()));
			quotationResponse.setAllCharge(quotationResponse.getAllCharge().add(quotationResponsePage.getAllCharge()));

			if (start > 0 && (start + size > total))
			{
				break;
			}else
			{
				start = start + size;
			}
		}
		
		return quotationResponse;
	}
	
	private PolicyResponse queryList(String startTime,String endTime,Integer start,String token)
	{
		String queryQuotationMethodStep = String.format(queryQuotationMethod, start.toString(),"15");
		queryQuotationURLScopeParam = String.format(queryQuotationURLScopeParam, startTime,endTime);
			
		PolicyResponse policyList = postQuotationList(hostURL + queryQuotationMethodStep,queryQuotationURLScopeParam,token);
		//写原始消息入表
		AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();				
		agtransvehiclemsgorigin = initOriginMessage(hostURL,queryQuotationMethodStep,queryQuotationURLScopeParam,"Post",JSON.toJSONString(policyList));
		carZhiMaService.save(agtransvehiclemsgorigin);
		
		return policyList;		
	}
	
	private QuotationResponse displayList(List<PolicyInfo> list,String token)
	{	
		QuotationResponse quotationResponse = new QuotationResponse();
		String policyCode = null;
		Date quotationDate = null;
		BigDecimal totalPremium = new BigDecimal(0);
		BigDecimal bzPremium = new BigDecimal(0);
		BigDecimal tcPremium = new BigDecimal(0);
		BigDecimal vsltax = new BigDecimal(0);
		BigDecimal allCharge = new BigDecimal(0);
		for(int i = 0; i < list.size();i++)
		{
			policyCode = list.get(i).getPolicycode();
			quotationDate = list.get(i).getCreateDate();
			System.out.print(""+ list.get(i).getCarNumber());
			
			totalPremium = totalPremium.add(BigDecimal.valueOf(list.get(i).getTotalPremium()));
			bzPremium = bzPremium.add(BigDecimal.valueOf(list.get(i).getBzPremium()));
			tcPremium = tcPremium.add(BigDecimal.valueOf(list.get(i).getTcPremium()));
			vsltax = vsltax.add(BigDecimal.valueOf(list.get(i).getVsltax()));
			allCharge = allCharge.add(BigDecimal.valueOf(list.get(i).getAllCharge()));
			
			System.out.print("getTotalPremium," + list.get(i).getTotalPremium());
			System.out.print("getBzPremium," + list.get(i).getBzPremium());
			System.out.print("getTcPremium," + list.get(i).getTcPremium());
			System.out.print("getVsltax," + list.get(i).getVsltax());
			System.out.println("getAllCharge," + list.get(i).getAllCharge());

			//检查是否已经存在
			AgPoQuotation one = agPoQuotationService.findByQuoteNo(policyCode);
			if (one==null)
			{
				String queryQuotationDetailMethodNew = String.format(queryQuotationDetailMethod, policyCode);
				QuotationDetail postConfirm = getComfirmationDetail(hostURL + queryQuotationDetailMethodNew,null,token);
				
			    //写车辆信息,报价信息，coverages入表
				//agPoQuotationWebService.saveAgPoQuotation(postConfirm.getDatas().getPriceinfo());
				agPoQuotationWebService.saveAgPoQuotationAndConfirm(quotationDate,postConfirm.getDatas().getPriceinfo(),postConfirm.getDatas().getConfirmInfo());
				//写确认信息入表confirmInfo
				//agPoQuotationWebService.saveAgPoQuotationConfirm(postConfirm.getDatas().getConfirmInfo());
						
				//写原始消息入表
				AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();				
				agtransvehiclemsgorigin = initOriginMessage(hostURL,queryQuotationDetailMethodNew,"","Post",JSON.toJSONString(postConfirm));
				carZhiMaService.save(agtransvehiclemsgorigin);
				
				/*System.out.print("" + postConfirm.getDatas().getPriceinfo().getVehInfo().getRegistrationNumber());
				System.out.print("getTotalPremium," + postConfirm.getDatas().getPriceinfo().getTotalPremium());
				System.out.print("getBzPremium," + postConfirm.getDatas().getPriceinfo().getBzPremium());
				System.out.print("getTcPremium," + postConfirm.getDatas().getPriceinfo().getTcPremium());
				System.out.print("getAllCharge," + postConfirm.getDatas().getPriceinfo().getAllCharge());
				System.out.println("getVsltax," + postConfirm.getDatas().getPriceinfo().getVsltax());
				System.out.print("getAllCharge," + postConfirm.getDatas().getPriceinfo().getAllCharge());	
				
				System.out.print("," + dateToString(list.get(i).getCreateDate()));
				System.out.println("");*/
			}
		}
		quotationResponse.setTotalPremium(totalPremium);
		quotationResponse.setBzPremium(bzPremium);
		quotationResponse.setTcPremium(tcPremium);
		quotationResponse.setTsltax(vsltax);
		quotationResponse.setAllCharge(allCharge);
		return quotationResponse;
	}
	
	public PolicyResponse postQuotationList(String urlQuery,String queryURLParams, String token)
	{
		PolicyResponse list = null;

		list = HttpHelpZhiMa.postUrlMap2JavaBean(urlQuery,queryURLParams,token,PolicyResponse.class);
		
		return list;
	}
	
	public static QuotationDetail getComfirmationDetail(String urlQuery,String queryParams, String token)
	{
		QuotationDetail confirm = null;

		confirm = HttpHelpZhiMa.getUrlMap2JavaBean(urlQuery,token,QuotationDetail.class);

		return confirm;
	}
	private static AgTransVehicleMsgOrigin initOriginMessage(final String requestHost,final String requestMethod,final String requestParams,final String requestType,final String responseMessage)
	{
		AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();
		
		agtransvehiclemsgorigin.setQuoteProviderId(2L);
		agtransvehiclemsgorigin.setQuoteProviderType("V");
		agtransvehiclemsgorigin.setQuoteProvider("芝麻");
		agtransvehiclemsgorigin.setRequestHost(requestHost);
		agtransvehiclemsgorigin.setRequestParams(requestParams);
		agtransvehiclemsgorigin.setRequestMethod(requestMethod);
		agtransvehiclemsgorigin.setRequestType(requestType);
		agtransvehiclemsgorigin.setRequestDate(new Date());
		agtransvehiclemsgorigin.setUserId(36);
		agtransvehiclemsgorigin.setUserName("simon");
		agtransvehiclemsgorigin.setResponseMessage(responseMessage);
		
		return agtransvehiclemsgorigin;
	}
	public static TokenZhiMa getToken(String urlQuery,String queryParams)
	{
		TokenZhiMa returnToken = (TokenZhiMa)HttpHelpZhiMa.getToken(urlQuery,queryParams);
		return returnToken;
	}
} 