package cn.com.countrygarden.bi.main.service.dup.tool;

import cn.com.countrygarden.bi.main.model.dup.BipProcessNumber;
import cn.com.countrygarden.bi.main.model.dup.ChangeJson;
import cn.com.countrygarden.bi.main.model.dup.ContractStatistical;
import cn.com.countrygarden.bi.main.model.dup.ContractTimedExecute;
import cn.com.countrygarden.bi.main.service.dup.ContractStatisticalService;
import cn.com.countrygarden.bi.main.service.project.impl.vo.outburst.BaseData;
import cn.com.countrygarden.bi.main.service.project.impl.vo.outburst.Result;
import cn.com.countrygarden.bi.main.util.AxisUtils;
import cn.com.countrygarden.bi.main.util.DateUtil;

import com.google.gson.Gson;
import com.landray.kmss.km.review.webservice.Exception;
import com.landray.kmss.km.review.webservice.IKmReviewThirdWebserviceServiceProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.datetime.joda.LocalDateParser;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.rmi.RemoteException;
import java.time.format.DateTimeFormatter;
import java.util.*;

//import com.google.gson.Gson;

@Component
public class ContractStatisticalTimerTask {

	/** 社区创新接口url **/
	@Value("${iWebService.url}")
	private String wsUrl;
	/** 社区创新接口方法 **/
	@Value("${iWebService.method.communityReview}")
	private String wsMetodCommunityReview;
	@Value("${iWebService.method.getEmergencyReview}")
	private String getEmergencyReview;

	@Autowired
	private ContractStatisticalService contractStatisticalService;
	
	private final Logger logger = LoggerFactory.getLogger(ContractStatisticalTimerTask.class);
	
    @Scheduled(cron = "0 0 2 * * ?")//每天两点执行定时调度
    public void run(){
        System.out.println("-----开始-------执行合同调度任务！！！！！！！！！！！！！！！！！！！！------------------------------");
        // 获取ERP的所有的流程
        List<String> lists = contractStatisticalService.findAllBipNumber();
        // 定义一个Map--将对应的流程Bip编号放进map
        Map<String, String> BipMap = new HashMap<>();
        for (String str : lists) {
            BipMap.put(str, str);
        }
        ContractTimedExecute dateStart =new ContractTimedExecute();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-1);
        
        String startDate =DateUtil.simpleFormat(calendar.getTime());
        String endDate=DateUtil.simpleFormat(new Date());

        dateStart.setStartDate(startDate);
        dateStart.setEndDate(endDate);
        System.out.println("-----合同录入统计的同步时间--- "+startDate+"    ------ "+endDate);
        //ContractTimedExecute dateStart = contractStatisticalService.findDateStart();
        // 获取接口过来的数据,--对比数据
        //String a = findBip();
        String a = findBipOnlyByClient(wsUrl,wsMetodCommunityReview,null,dateStart);
        String b = findBipOnlyByClient(wsUrl,getEmergencyReview,"1495fce7bc50ea50abf35e84b1cb3758",dateStart);
        
        if(!StringUtils.hasText(a)) {
            //系统报错,或者是其他原因,则退出查询,
            logger.error("获取不到外部接口的数据" );
            return;
        }
        System.out.println("---a--- "+a);
        // G js =new JSONObject();
        Gson gson = new Gson();
        ChangeJson schangJson = gson.fromJson(a, ChangeJson.class);
        List<BipProcessNumber> list = getMergeData(b,schangJson);
        List<ContractStatistical> contractStatisticalLists = new ArrayList<ContractStatistical>();
        for (BipProcessNumber t : list) {
            if (!BipMap.containsKey(t.getFdNumber())) {
                // 录入到Dup数据库
                ContractStatistical contractStatistical = new ContractStatistical();
                contractStatistical.setCommName(t.getDocSubject());
                contractStatistical.setBipNum(t.getFdNumber());
                contractStatistical.setOrganName(t.getFdDepartment());
                contractStatistical.setBusinessType(t.getBusinessType());
                contractStatistical.setFinalJudgmentDate(t.getFinalJudgmentDate());
                // 根据区域+项目名获取对应的项目id与区域代码
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("CommName", t.getDocSubject());
                map.put("OrganName", t.getFdDepartment());
                // 根据项目名称查询对应的项目id
                Map<String, Object> maps = contractStatisticalService.findCommidAndOrganCode(map);
                contractStatistical.setNoImport("未录入");
                contractStatistical.setUpdateDate(new Date());
                if (maps != null) {
                    contractStatistical.setCommId((int) map.get("CommID"));
                    contractStatistical.setOrganCode((String) map.get("OrganCode"));
                }
                // 查询当前数据库(Dup)的数据,如果存在当前条的数据则不能新增
                @SuppressWarnings("unchecked")
                List<ContractStatistical> list1 = (List<ContractStatistical>) contractStatisticalService
                        .ContractStatisticalSelect1(new ContractStatistical()).getData();
                int number = 0;
                for (ContractStatistical contractStatistical2 : list1) {
                    if ( contractStatistical2.getBipNum().equals(t.getFdNumber())) {
                        number++;
                    } 
                }
                if (number != 0) {
                    continue;
                }else {
                contractStatisticalLists.add(contractStatistical);
                }
            }
        }
        if(contractStatisticalLists.size()!=0) {
            logger.info("---合同录入统计--准备插入----");
            contractStatisticalService.inserContranctStatical(contractStatisticalLists);
        }
        System.out.println("----结束--------执行合同调度任务！！！！！！！！！！！！！！！！！！！！------------------------------");
    }
	
	
    public void run(String beginDate,String finishDate){
        System.out.println("-----开始-------执行合同调度任务！！！！！！！！！！！！！！！！！！！！------------------------------");
        // 获取ERP的所有的流程
        List<String> lists = contractStatisticalService.findAllBipNumber();
        // 定义一个Map--将对应的流程Bip编号放进map
        Map<String, String> BipMap = new HashMap<>();
        for (String str : lists) {
            BipMap.put(str, str);
        }
        ContractTimedExecute dateStart =new ContractTimedExecute();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-1);
        
        String startDate =DateUtil.simpleFormat(calendar.getTime());
        String endDate=DateUtil.simpleFormat(new Date());
        if(beginDate!=null){
            startDate=beginDate;
        }
        
        if(finishDate!=null){
            endDate= finishDate;
        }
        
        dateStart.setStartDate(startDate);
        dateStart.setEndDate(endDate);
        System.out.println("-----合同录入统计的同步时间--- "+startDate+"    ------ "+endDate);
        //ContractTimedExecute dateStart = contractStatisticalService.findDateStart();
        // 获取接口过来的数据,--对比数据
        //String a = findBip();
        String a = findBipOnlyByClient(wsUrl,wsMetodCommunityReview,null,dateStart);
        String b = findBipOnlyByClient(wsUrl,getEmergencyReview,"1495fce7bc50ea50abf35e84b1cb3758",dateStart);
        
        if(!StringUtils.hasText(a)) {
            //系统报错,或者是其他原因,则退出查询,
            logger.error("获取不到外部接口的数据" );
            return;
        }
        System.out.println("---a--- "+a);
        // G js =new JSONObject();
        Gson gson = new Gson();
        ChangeJson schangJson = gson.fromJson(a, ChangeJson.class);
        List<BipProcessNumber> list = getMergeData(b,schangJson);
        List<ContractStatistical> contractStatisticalLists = new ArrayList<ContractStatistical>();
        for (BipProcessNumber t : list) {
            if (!BipMap.containsKey(t.getFdNumber())) {
                // 录入到Dup数据库
                ContractStatistical contractStatistical = new ContractStatistical();
                contractStatistical.setCommName(t.getDocSubject());
                contractStatistical.setBipNum(t.getFdNumber());
                contractStatistical.setOrganName(t.getFdDepartment());
                contractStatistical.setBusinessType(t.getBusinessType());
                contractStatistical.setFinalJudgmentDate(t.getFinalJudgmentDate());
                // 根据区域+项目名获取对应的项目id与区域代码
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("CommName", t.getDocSubject());
                map.put("OrganName", t.getFdDepartment());
                // 根据项目名称查询对应的项目id
                Map<String, Object> maps = contractStatisticalService.findCommidAndOrganCode(map);
                contractStatistical.setNoImport("未录入");
                contractStatistical.setUpdateDate(new Date());
                if (maps != null) {
                    contractStatistical.setCommId((int) map.get("CommID"));
                    contractStatistical.setOrganCode((String) map.get("OrganCode"));
                }
                // 查询当前数据库(Dup)的数据,如果存在当前条的数据则不能新增
                @SuppressWarnings("unchecked")
                List<ContractStatistical> list1 = (List<ContractStatistical>) contractStatisticalService
                        .ContractStatisticalSelect1(new ContractStatistical()).getData();
                int number = 0;
                for (ContractStatistical contractStatistical2 : list1) {
                    if ( contractStatistical2.getBipNum().equals(t.getFdNumber())) {
                        number++;
                    } 
                }
                if (number != 0) {
                    continue;
                }else {
                contractStatisticalLists.add(contractStatistical);
                }
            }
        }
        if(contractStatisticalLists.size()!=0) {
            System.out.println("---合同录入统计--准备插入----");
            contractStatisticalService.inserContranctStatical(contractStatisticalLists);
        }
        System.out.println("----结束--------执行合同调度任务！！！！！！！！！！！！！！！！！！！！------------------------------");
    }

	/**
	 * 获取外部接口的数据
	 * 
	 * @return
	 * @throws Exception
	 * @throws RemoteException
	 */
	public String findBip()  {
		//查询调度时间.如果调度时间不存在则获取当前时间
		//contractStatisticalService.findDate();
		ContractTimedExecute dateStart=contractStatisticalService.findDateStart();
		IKmReviewThirdWebserviceServiceProxy lin = new IKmReviewThirdWebserviceServiceProxy();
		String a;
		try {
			a = lin.getCommunityReview(dateStart.getStartDate(), dateStart.getEndDate());
			return a.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("无法读取外部接口数据：" + e.getMessage());
			e.printStackTrace();
		} catch (RemoteException e) {
			logger.error("无法读取外部接口数据：" + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 获取外部接口的数据
	 *
	 * @return 接口返回的字符串格式数据
	 * @throws Exception
	 * @throws RemoteException
	 */
	public String findBipOnlyByClient(String url,String metod,String arg,ContractTimedExecute dateStart) {
		//查询调度时间.如果调度时间不存在则获取当前时间
		//contractStatisticalService.findDate();
		Object[] args = new Object[3];
		args[0] = dateStart.getStartDate();
		args[1] = dateStart.getEndDate();
		if(arg!=null){
		    args[2] =arg ;
		}
		return AxisUtils.callService(url, metod, args);
	}
	
	public List<BipProcessNumber> getMergeData(String b,ChangeJson c){
	    if(!StringUtils.hasText(b)){
	        return c.getData();
	    }
        System.out.println("----合同录入统计--定时调度流程信息----: "+b);
        Gson g = new Gson();
        Result r = g.fromJson(b, Result.class);
        List<BaseData> data= r.data;
        int i=0;
        for(BaseData baseData:data){
            for (BipProcessNumber bipProcessNumber : c.getData()) {
                if(baseData.fdNumber.equals(bipProcessNumber.getFdNumber())){
                    logger.info("---合同录入统计--有值---- "+i++);
                    bipProcessNumber.setBusinessType(baseData.modelData.fd_362a5a4023741a);  
                    bipProcessNumber.setFinalJudgmentDate(baseData.applNote.get(baseData.applNote.size()-1).fdCreateTime);
                }
            }
            
        }
        return c.getData();
	}
}
