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

import cn.com.countrygarden.bi.main.constant.wcx.ApplicationContextRegister;
import cn.com.countrygarden.bi.main.dao.dup.ManagerDataMapper;
import cn.com.countrygarden.bi.main.dao.personnel.FenghuangCollectionrateMapper;
import cn.com.countrygarden.bi.main.dto.FenghuangCollectionrateDTO;
import cn.com.countrygarden.bi.main.dto.ManagerMapOrganTreeDTO;
import cn.com.countrygarden.bi.main.model.dup.FenghuangCollectionrate;
import cn.com.countrygarden.bi.main.model.dup.ManagerData;
import cn.com.countrygarden.bi.main.service.dup.ManagerDataService;
import cn.com.countrygarden.bi.main.util.RedisUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.salesforce.SurveyConfigService;
import io.github.biezhi.ome.OhMyEmail;
import io.github.biezhi.ome.SendMailException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static io.github.biezhi.ome.OhMyEmail.SMTP_QQ;

@Configuration
@ComponentScan("cn.com.countrygarden.bi.main.*")
@EnableScheduling
public class ManagerDataSchedule {


	public ManagerDataSchedule(){
		OhMyEmail.config(SMTP_QQ(true), "791120662@qq.com", "ifhstopkjapgbdeh");
	}

	public static final String cacheKey="biapp:manager:data:sync";

    private final Logger log = LoggerFactory.getLogger(this.getClass());

   
//    @Scheduled(cron = "0 0/1 * * * ?")
	@Scheduled(cron = "${schedule.cron.syncerptouser}")
    public void syncErpToUserTarget() {
		//先查询Redis中是否有数据 有则返回
		if (RedisUtils.exits(cacheKey)) {
			return;
		}
		try{
			RedisUtils.put(cacheKey,"1",60 * 60*2);
			log.info("同步erp用户数据定时器开启....");
			DateFormat dFormat = new SimpleDateFormat("yyyy/MM/dd");
			ManagerDataMapper managerDataMapper = ApplicationContextRegister.getApplicationContext().getBean(ManagerDataMapper.class);
			FenghuangCollectionrateMapper fenghuangCollectionrateMapper = ApplicationContextRegister.getApplicationContext().getBean(FenghuangCollectionrateMapper.class);
			SurveyConfigService surveyConfigService = ApplicationContextRegister.getApplicationContext().getBean(SurveyConfigService.class);
			ManagerDataService managerDataService=ApplicationContextRegister.getApplicationContext().getBean(ManagerDataService.class);

			List<ManagerMapOrganTreeDTO> psndocCode=managerDataMapper.psndoc();
			String im=dFormat.format(new Date());
			String time=null;
			String [] imu=im.split("/");
			Integer yes=0;
			Integer moun=0;
			if (Integer.parseInt(imu[1])==1){
				yes=Integer.parseInt(imu[0])-1;
				moun=12;
			}else {
				yes=Integer.parseInt(imu[0]);
				moun=Integer.parseInt(imu[1])-1;
			}

			if (moun<10){
				time=yes+"-"+"0"+moun.toString();
			}else {
				time=yes+"-"+moun;
			}
//			检查是否二次补偿运行
			List<ManagerMapOrganTreeDTO> replaceList = checkReplace(fenghuangCollectionrateMapper, time, psndocCode);
			if(!CollectionUtils.isEmpty(replaceList)){
				psndocCode=replaceList;
			}
			List<FenghuangCollectionrate> fDtoslist=new ArrayList<FenghuangCollectionrate>();
			List<FenghuangCollectionrate> fDtosSavelist=new ArrayList<FenghuangCollectionrate>();
			List<FenghuangCollectionrate> fDtosUpdatelist=new ArrayList<FenghuangCollectionrate>();
			List<String> errorList=new ArrayList<>();

			for (int i = 0; i < psndocCode.size(); i++) {
				Map<String, Object> dataMap = new HashMap<>();
				dataMap.put("employeeNumber", psndocCode.get(i).getCode());
				JSONObject jsonStr=null;
				try {
					jsonStr=surveyConfigService.querySfResult("apexrest/api/", "t_CollectionRate", dataMap);
				}catch (Exception e){
					try {
						jsonStr=surveyConfigService.querySfResult("apexrest/api/", "t_CollectionRate", dataMap);
					}catch (Exception ee){
						ee.printStackTrace();
						errorList.add("人员编号：["+psndocCode.get(i).getCode()+"]数据加载异常！"+ ExceptionUtils.getMessage(ee));
						System.out.println("此用户数据为空");
					}
				}
				if (jsonStr!=null) {
					System.out.println("erp用户数据有效，持久化中....");

					//if (count==0){
					FenghuangCollectionrate formatter=new FenghuangCollectionrate();
					formatter.setUserId(psndocCode.get(i).getCode());
					formatter.setUserName(jsonStr.getString("name"));
					formatter.setCollectionrate(Double.valueOf(jsonStr.getString("collectionRate")));
					formatter.setCollectionrateTime(time);
					fDtosSavelist.add(formatter);
					fDtoslist.add(formatter);
				}else {
					errorList.add("人员编号：["+psndocCode.get(i).getCode()+"]数据加载为0！");
					//if (count==0){
					FenghuangCollectionrate formatter=new FenghuangCollectionrate();
					formatter.setUserId(psndocCode.get(i).getCode());
					formatter.setUserName(psndocCode.get(i).getName());
					formatter.setCollectionrate(0.0);
					formatter.setCollectionrateTime(time);
					fDtosSavelist.add(formatter);
					fDtoslist.add(formatter);
				}
			}
//			通知管理员
			if(!CollectionUtils.isEmpty(errorList)){
				noticeAdmin(errorList);
			}
			List<FenghuangCollectionrateDTO> fDtoUpdateList=new ArrayList<FenghuangCollectionrateDTO>();
			if (fDtoslist.size()!=0&&fDtoslist!=null) {
				for (int i = 0; i < fDtoslist.size(); i++) {
					List<ManagerData> result = managerDataMapper.fincByDatelist(fDtoslist.get(i).getUserId(), fDtoslist.get(i).getCollectionrateTime());
					if (result.size() != 0 && result != null) {
						FenghuangCollectionrateDTO fDto = new FenghuangCollectionrateDTO();
						fDto.setManagerName(fDtoslist.get(i).getUserName());
						double colla = fDtoslist.get(i).getCollectionrate() * 100;
						BigDecimal bg = new BigDecimal(colla).setScale(2, RoundingMode.UP);
						fDto.setCollectionrate(bg.doubleValue());
						fDto.setManagerId(result.get(0).getId());
						log.info("erp修改....");
						fDtoUpdateList.add(fDto);

               /* }else {
                    List<FenghuangCollectionrateDTO> managerhousekeeper = fenghuangCollectionrateMapper.managerhousekeeper(fDtoslist.get(i).getUserName(),time);
                    if (managerhousekeeper.size()!=0&&managerhousekeeper!=null){
                        FenghuangCollectionrateDTO fDto = new FenghuangCollectionrateDTO();
                        fDto.setManagerName(managerhousekeeper.get(0).getUserName());
                        double colla = fDtoslist.get(i).getCollectionrate() * 100;
                        BigDecimal bg = new BigDecimal(colla).setScale(2, RoundingMode.UP);
                        fDto.setCollectionrate(bg.doubleValue());
                        fDto.setManagerId(managerhousekeeper.get(0).getId());
                        log.info("erp修改....");
						fDtoUpdateList.add(fDto);
                    }*/
					}
				}
			}

//      Service批量处理（事务）
			managerDataService.updateCacheData(fDtosSavelist,fDtosUpdatelist,fDtoUpdateList,time);
			System.out.println("管家数据缓存完成！！处理条数："+fDtoUpdateList.size());
			System.out.println("管家数据缓存完成！！处理条数："+fDtoUpdateList.size());
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			RedisUtils.del(cacheKey);
		}

    }


	/**
	 * 检查是否补偿运行，如果是则值同步异常数据
	 * @param fenghuangCollectionrateMapper
	 * @param date
	 * @param psndocCode
	 * @return
	 */
	private List<ManagerMapOrganTreeDTO> checkReplace(FenghuangCollectionrateMapper fenghuangCollectionrateMapper, String date, List<ManagerMapOrganTreeDTO> psndocCode) {
		List<String> fDtosSavelist=fenghuangCollectionrateMapper.selectErrorRate(date);
		if(CollectionUtils.isEmpty(fDtosSavelist)){
			return null;
		}
		List<ManagerMapOrganTreeDTO> error=new ArrayList<>();
//		只保存为零的数据进行补偿操作
		for (int i = 0; i < psndocCode.size(); i++) {
			if(fDtosSavelist.contains(psndocCode.get(i).getCode())){
				error.add(psndocCode.get(i));
			}
		}
		return error;
	}


	/**
	 * 通知管理员
	 * @param retryQueue
	 */
	private void noticeAdmin(List<String> retryQueue) {
		System.out.println("通知系统管理员！！");
		try {
			OhMyEmail.subject("DUP管家收缴率同步失败！")
					.from("791120662@qq.com")
					.to("791120662@qq.com")
					.html("当前数据：<p>"+ JSON.toJSONString(retryQueue)+"</p>")
					.send();
		}catch (Exception e){
			e.printStackTrace();
			try {
				OhMyEmail.subject("DUP管家收缴率同步失败！")
                        .from("791120662@qq.com")
                        .to("791120662@qq.com")
                        .html("当前数据：<p>"+ JSON.toJSONString(retryQueue)+"</p>")
                        .send();
			} catch (SendMailException e1) {
				e1.printStackTrace();
			}
		}
	}


}
