package com.zfire.jiasm.syncdata.gree.recycle;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zfire.jiasm.syncdata.constant.Constant;
import com.zfire.jiasm.syncdata.constant.GreeSynStatusEnum;
import com.zfire.jiasm.syncdata.gree.helper.GreeResponseHelper;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
import com.zfire.jiasm.syncdata.service.PublicService;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RecycleAssignLogic {
	@Autowired
	GreeLogicT greeLogic;
	@Autowired
	ItfTblRecycleAssignDownloadService recycleAssignService;
	@Autowired
	ItfTblRecycleAssignFkmxDownloadService recycleAssignFkmxDownloadService;
	@Autowired
	ItfTblRecycleAssignMxDownloadService recycleAssignMxDownloadService;
	@Autowired
	ItfTblRecycleAssignBatchDownloadRecService recycleAssignBatchDownloadRecService;
	@Autowired
	OrderRecycleUploadEventService orderRecycleUploadEventService;
	@Autowired
	ItfTblRecycleAssignFkmxUploadService recycleAssignFkmxUploadService;
	@Autowired
	ItfTblHsptJjcjUploadService hsptJjcjUploadService;
	@Autowired
	ItfTblHsptJjcjFjUploadService hsptJjcjFjUploadService;
	@Autowired
	ItfTblHsptJjcjTmmxUploadService hsptJjcjTmmxUploadService;
	@Autowired
	ItfTblRecycleHsptJjcjDownloadService recycleHsptJjcjDownloadService;
	@Autowired
	ItfTblRecycleHsptJjcjFjDownloadService recycleHsptJjcjFjDownloadService;
	@Autowired
	ItfTblRecycleHsptJjcjTmmxDownloadService recycleHsptJjcjTmmxDownloadService;
	@Autowired
	OrderRecycleAssignFkmxService orderRecycleAssignFkmxService;
	@Autowired
	OrderRecycleAssignService orderRecycleAssignService;
	@Autowired
	OrderRecycleAssignCollectionService orderRecycleAssignCollectionService;
	@Autowired
	AreaService areaService;
	@Autowired
	WebsitService websitService;
	@Autowired
	private OrderBaseService orderBaseService;
	@Autowired
	PublicService publicService;
	
	private ObjectMapper mapper;
	@Autowired
	public RecycleAssignLogic() {
		this.mapper = new ObjectMapper();
		SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		this.mapper.setDateFormat(smt);
		this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
	
	private static String genWorkerNo() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSSSS");
		int r = (int)(Math.random()*999);
		String result = "11"+sdf.format(new Date())+"000".substring(0, "000".length() - String.valueOf(r).length())+String.valueOf(r);
	    return result;
	}
	
	public List<RecycleAssignDownloadBean> assign(RecycleAssignParamBean param) throws Exception{
		List<ItfTblRecycleAssignBatchDownloadRec> nnList = new ArrayList<>();
		List<ItfTblRecycleAssignBatchDownloadRec> zeroList = new ArrayList<>();
		Map<String, List<ItfTblRecycleAssignBatchDownloadRec>> nnMap = new HashMap<>();
		Map<String, List<ItfTblRecycleAssignBatchDownloadRec>> zeroMap = new HashMap<>();
		Map<Integer, List<ItfTblRecycleAssignBatchDownloadRec>> recMap = new HashMap<>();
		List<ItfTblRecycleAssignBatchDownloadRec> recList = new ArrayList<>();

		final String apiPath = Constant.GreeApiPath.RECYCLE_ASSIGN;
		Map<String,Object> map = new HashMap<>();
		map.put("page", param.getPage());
		map.put("pageSize", param.getPageSize());
		map.put("type", param.getType());
		//回收工单请求
		String dataStr = greeLogic.post(apiPath, map, 1);
		// 工单主表，一条反馈明细，多条产品明细
		// 工单信息pgid|pgguid、反馈信息pgguid、回收的产品pgguid
		List<RecycleAssignDownloadBean> responseBeanList = mapper.readValue(dataStr, new TypeReference<List<RecycleAssignDownloadBean>>() {} );

		if(CollectionUtils.isNotEmpty(responseBeanList)) {
			// 提取工单主键
			LinkedHashSet<String> pguuidLhs = new LinkedHashSet<>(); 
			responseBeanList.forEach(o->pguuidLhs.add(o.getPgguid()));
			List<RecycleAssignDownloadEntity> newTaskEntities = new ArrayList<>();

			if(!pguuidLhs.isEmpty()) {
				// 每次请求使用相同的批次号
				String batchNo = publicService.getUUID();

				// 下载记录表中查看是否存在与本次下载相同的工单 0及99的
				// 这里的99 为与总部进行确认失败的工单
				recList = recycleAssignBatchDownloadRecService.lambdaQuery()
						.in(ItfTblRecycleAssignBatchDownloadRec::getPgguid, pguuidLhs)
						.in(ItfTblRecycleAssignBatchDownloadRec::getGreeStatSynStatus, 0, Constant.SynStatus.FAIL.getCode()).list();
				// 已下载记录表中存在数据时分组
				if(CollectionUtils.isNotEmpty(recList)) {
					// 按状态分组0-99
					recMap = recList.stream().collect(Collectors.groupingBy(ItfTblRecycleAssignBatchDownloadRec::getGreeStatSynStatus));
					// 已下载未处理的-0
					zeroList = recMap.get(0);
					// 状态为0的任务按工单主键分组
					zeroMap = (null != zeroList && !zeroList.isEmpty()) ? (zeroList.stream().collect(Collectors.groupingBy(ItfTblRecycleAssignBatchDownloadRec::getPgguid))) : null;
					nnList = recMap.get(Constant.SynStatus.FAIL.getCode());
					// 状态为99的任务按工单主键分组
					nnMap = (null != nnList && !nnList.isEmpty()) ? (nnList.stream().collect(Collectors.groupingBy(ItfTblRecycleAssignBatchDownloadRec::getPgguid))) : null;
				}

				// 回收工数据处理
				for (RecycleAssignDownloadBean o:responseBeanList){
					try{
						// 已存在为0的任务不做任何处理 说明本次下载了上次同样的数据
						if (zeroMap !=null && zeroMap.containsKey(o.getPgguid())){
							continue;
						}

						// 工单主表，一条反馈明细，多条产品明细
						// 状态为99的单独处理 超10次重新下载
						if (nnMap !=null && nnMap.containsKey(o.getPgguid())){
							// 待与总部确认下载完成的工单不处理
							if (nnMap.get(o.getPgguid()).get(0).getSynTimes()<10){
								continue;
							}
							process(nnMap, newTaskEntities, o);
						} else {
							// 获取新增的
							getAdd(newTaskEntities, o);
						}

						// 回收工单落表 所有表任务号与批次号同下载记录表 单独的任务号，本次拉取的数据相同的批次号
						if( null != newTaskEntities && !newTaskEntities.isEmpty()) {
							batchAddDownloadTask(newTaskEntities,batchNo);
						}
					} catch (Exception ex) {
						ex.printStackTrace();
						log.info("回收工单落本地表失败：{}",o.getPgguid());
					}
				}
			}
		}
		return responseBeanList;
	}

	private void getAdd(List<RecycleAssignDownloadEntity> newTaskEntities, RecycleAssignDownloadBean o) {
		try {
			// 报文中提取实体表对像数据 主表，反馈表，回收产品明细表
			// 工单主表，一条反馈明细，多条产品明细
			RecycleAssignDownloadEntity entity = copyBean2Entity(o);
			ItfTblRecycleAssignBatchDownloadRec rec = new ItfTblRecycleAssignBatchDownloadRec();
			rec.setPgguid(o.getPgguid());
			rec.setSynTimes(1);
			rec.setGreeStatSynStatus(0);
			rec.setCreatedDate(new Date());
			rec.setLastModifiedDate(new Date());
			entity.setRec(rec);
			newTaskEntities.add(entity);
		} catch (JsonProcessingException e) {
			log.error("RecycleAssignDownload bean复制到RecycleAssignDownloadEntity异常:{}", e.getMessage());
		}
	}

	private void process(Map<String, List<ItfTblRecycleAssignBatchDownloadRec>> nnMap, List<RecycleAssignDownloadEntity> newTaskEntities,
						 RecycleAssignDownloadBean o) {
		ItfTblRecycleAssignBatchDownloadRec rec = nnMap.get(o.getPgguid()).get(0);
		// 超10次的重新同步
		try {
			RecycleAssignDownloadEntity entity = copyBean2Entity(o);
			rec.setSynTimes(0);
			rec.setGreeStatSynStatus(0);
			rec.setLastModifiedDate(new Date());
			entity.setRec(rec);
			newTaskEntities.add(entity);
		} catch (JsonProcessingException e) {
			log.error("RecycleAssignDownload bean复制到RecycleAssignDownloadEntity异常:{}", e.getMessage());
		}
	}

	/**
	 * 批量添加回收工单任务
	 * 每个工单单独的且相同的任务号，批次号同一次下载的相同
	 * @param newTaskEntities
	 */
	@Transactional
	public void batchAddDownloadTask(List<RecycleAssignDownloadEntity> newTaskEntities,String batchNo) {
		List<ItfTblRecycleAssignBatchDownloadRec> recList = new ArrayList<>();

		if(CollectionUtils.isNotEmpty(newTaskEntities)) {
			List<ItfTblRecycleAssignDownload> tblRecycleAssignEntity = new ArrayList<>();
			List<ItfTblRecycleAssignFkmxDownload> lastStep = new ArrayList<>();
			List<ItfTblRecycleAssignMxDownload> hscpmx = new ArrayList<>();
			newTaskEntities.forEach(o->{
				// 下载记录表 单独的任务号，相同的批次号
				ItfTblRecycleAssignBatchDownloadRec rec = o.getRec();
				rec.setDownloadTaskNo(publicService.getUUID());
				rec.setDownloadBatchNo(batchNo);
				rec.setSynReqTime(new Date());
				rec.setCreatedDate(new Date());
				rec.setLastModifiedDate(new Date());
				recList.add(rec);
				//把基础信息的状态更新到所有的明细内
				if(!Objects.isNull(o.getTblRecycleAssignEntity())) {
					// 回收工单主表 任务号与批次号同下载记录表
					tblRecycleAssignEntity.add(o.getTblRecycleAssignEntity().setSynStatus(rec.getSynStatus()).
							setSynErrMsg(rec.getSynErrMsg()).setDownloadBatchNo(
							rec.getDownloadBatchNo()).setDownloadTaskNo(rec.getDownloadTaskNo())
							.setCreatedDate(new Date()).setLastModifiedDate(new Date()));
				}
				if( !Objects.isNull( o.getLastStep())) {
					// 反馈明细表 任务号与批次号同下载记录表
					lastStep.add(o.getLastStep().setSynStatus(rec.getSynStatus()).
							setSynErrMsg(rec.getSynErrMsg()).setDownloadBatchNo(rec.getDownloadBatchNo()).
							setDownloadTaskNo(rec.getDownloadTaskNo()));
				}
				if(null != o.getHscpmx() && !o.getHscpmx().isEmpty()) {
					// 回收产品明细表 任务号与批次号同下载记录表
					o.getHscpmx().forEach(i->{
						i.setSynStatus(
								o.getTblRecycleAssignEntity().getSynStatus()).setSynErrMsg(
										o.getTblRecycleAssignEntity().getSynErrMsg()).setDownloadBatchNo(rec.getDownloadBatchNo()).
						setDownloadTaskNo(rec.getDownloadTaskNo())
						.setCreatedDate(new Date()).setLastModifiedDate(new Date());
						hscpmx.add(i);
					});
				}
			});
			// 插入下载主表
			if( null != tblRecycleAssignEntity  && !tblRecycleAssignEntity.isEmpty()) {
				recycleAssignService.saveOrUpdateBatch(tblRecycleAssignEntity);
			}
			// 插入下载反馈表
			if(null != lastStep && !lastStep.isEmpty()) {
				recycleAssignFkmxDownloadService.saveOrUpdateBatch(lastStep);
			}
			// 插入回收明细表
			if(null != hscpmx && !hscpmx.isEmpty()) {
				recycleAssignMxDownloadService.saveOrUpdateBatch(hscpmx);
			}
			// 插入下载记录表
			if(null != recList && !recList.isEmpty()) {
				recycleAssignBatchDownloadRecService.saveOrUpdateBatch(recList);
			}
			newTaskEntities.clear();
		}
		
	}
	
	/**
	 * 复制回收工单bean到entity
	 * @param bean
	 * @return
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 */
	private RecycleAssignDownloadEntity copyBean2Entity(RecycleAssignDownloadBean bean) throws JsonMappingException, JsonProcessingException {
		RecycleAssignDownloadEntity entity = new RecycleAssignDownloadEntity();
		List<ItfTblRecycleAssignMxDownload>  mxList = new ArrayList<>();

		// 工单主表，一条反馈明细，多条产品明细
		// 提取回收工单主表数据
		entity.setTblRecycleAssignEntity(mapper.readValue(mapper.writeValueAsString(bean), ItfTblRecycleAssignDownload.class));
		// 提取回收工单反馈数据
		entity.setLastStep(mapper.readValue(mapper.writeValueAsString(bean.getLastStep()), ItfTblRecycleAssignFkmxDownload.class));

		bean.getHscpmx().forEach(o-> {
				try {
					// 提取回收产品明细数据
					ItfTblRecycleAssignMxDownload mxEntity = mapper.readValue(mapper.writeValueAsString(o), ItfTblRecycleAssignMxDownload.class);
					mxList.add(mxEntity);
				} catch (JsonProcessingException e) {
					log.error("转换RecycleAssignMxDownload bean 到 RecycleAssignMxDownload 异常：{}", e.getOriginalMessage());
				}
			}
		);
		entity.setHscpmx(mxList);
		return entity;
	}
	
	
	private List<RecycleAssignDownloadBean> copyEntities2Bean(List<ItfTblRecycleAssignBatchDownloadRec> recList){
		if(CollectionUtils.isNotEmpty(recList)) {
			List<RecycleAssignDownloadBean> resultList = new ArrayList<>();
			LinkedHashSet<String> taskNos = new LinkedHashSet<>();
			recList.forEach(o->{
				taskNos.add(o.getDownloadTaskNo());
			});
			
			//装载list
			// 回收工单主表 并按任务号分组
			List<ItfTblRecycleAssignDownload> raList = recycleAssignService.lambdaQuery()
					.in(ItfTblRecycleAssignDownload::getDownloadTaskNo, taskNos).list();
			Map<String, List<ItfTblRecycleAssignDownload>> raMap = raList.stream()
					.collect(Collectors.groupingBy(ItfTblRecycleAssignDownload::getDownloadTaskNo));
			// 回收工单过程反馈表 并按任务号分组
			List<ItfTblRecycleAssignFkmxDownload> fkmxList = recycleAssignFkmxDownloadService.lambdaQuery()
					.in(ItfTblRecycleAssignFkmxDownload::getDownloadTaskNo, taskNos).list();
			Map<String, List<ItfTblRecycleAssignFkmxDownload>> fkmxMap = fkmxList.stream()
					.collect(Collectors.groupingBy(ItfTblRecycleAssignFkmxDownload::getDownloadTaskNo));
			// 回收工单产品明细表 并按任务号分组
			List<ItfTblRecycleAssignMxDownload> mxList = recycleAssignMxDownloadService.lambdaQuery()
					.in(ItfTblRecycleAssignMxDownload::getDownloadTaskNo, taskNos).list();
			Map<String, List<ItfTblRecycleAssignMxDownload>> mxMap = mxList.stream()
					.collect(Collectors.groupingBy(ItfTblRecycleAssignMxDownload::getDownloadTaskNo));

			recList.forEach(o->{
				RecycleAssignDownloadBean bean = new RecycleAssignDownloadBean();
				// 回收工单主表
				if(Objects.isNull(raMap)
						|| !raMap.containsKey(o.getDownloadTaskNo())
						||Collections.isEmpty(raMap.get(o.getDownloadTaskNo()))){
					log.error("找不到任务号: downloadTaskNo={}", o.getDownloadTaskNo());
				}else {
					try {
						bean = mapper.readValue(mapper.writeValueAsString(raMap.get(o.getDownloadTaskNo()).get(0)), RecycleAssignDownloadBean.class);
						bean.setBatchNo(o.getDownloadBatchNo());
						bean.setTaskNo(o.getDownloadTaskNo());
						bean.setPgguid(o.getPgguid());
					} catch (JsonProcessingException e) {
						log.error("转换RecycleAssignDownloadEntity 到 RecycleAssignDownload bean 异常：{}", e.getOriginalMessage());
					}
				}
				// 回收工单过程反馈表
				if(!Objects.isNull(fkmxMap) && fkmxMap.containsKey(o.getDownloadTaskNo())
						&& !Collections.isEmpty(fkmxMap.get(o.getDownloadTaskNo()))
						) {
					try {
						bean.setLastStep(mapper.readValue(mapper.writeValueAsString(fkmxMap.get(o.getDownloadTaskNo()).get(0)), RecycleAssignFkmxDownloadBean.class));
					} catch (Exception e) {
						log.error("转换RecycleAssignFkmxDownloadEntity 到 RecycleAssignFkmxDownload bean 异常：{}", e.getMessage());
					}
				}
				// 回收明细表
				if(!Objects.isNull(mxMap)  && mxMap.containsKey(o.getDownloadTaskNo())
						&& Collections.isEmpty(mxMap.get(o.getDownloadTaskNo()))
						) {
					List<RecycleAssignMxDownloadBean> hscpmx = new ArrayList<>();
					mxMap.get(o.getDownloadTaskNo()).forEach(i->{
						try {
							hscpmx.add(mapper.readValue(mapper.writeValueAsString(i), RecycleAssignMxDownloadBean.class));
						} catch (JsonProcessingException e) {
							log.error("转换RecycleAssignMxDownloadEntities 到 RecycleAssignMxDownload bean 异常：{}", e.getOriginalMessage());
						}
					});
					bean.setHscpmx(hscpmx);
				}
				resultList.add(bean);
			});
			return resultList;
		}
		return null;
	}
	
	/**
	 * 查询greeStatSynStatus状态为0即未同步的数据，装载到RecycleAssignDownloadBean里
	 * @return
	 * @throws Exception
	 */
	private List<RecycleAssignDownloadBean> queryUnSynList() {
		return copyEntities2Bean(recycleAssignBatchDownloadRecService.lambdaQuery()
				.eq(ItfTblRecycleAssignBatchDownloadRec::getSynStatus, 66)
				.in(ItfTblRecycleAssignBatchDownloadRec::getGreeStatSynStatus, 0,99)
				.lt(ItfTblRecycleAssignBatchDownloadRec::getSynTimes, 10)
				.list());
	}

	

	private void errorUpdateGreeStatSynStatus(RecycleAssignDownloadBean bean, GreeResponseHelper response) {
		// 记录表
		ItfTblRecycleAssignBatchDownloadRec rec = recycleAssignBatchDownloadRecService.lambdaQuery()
				.eq(ItfTblRecycleAssignBatchDownloadRec::getDownloadTaskNo, bean.getTaskNo()).one();
		// 主表
		ItfTblRecycleAssignDownload ra = recycleAssignService.lambdaQuery()
				.eq(ItfTblRecycleAssignDownload::getDownloadTaskNo, bean.getTaskNo()).one();
		// 明细表
		List<ItfTblRecycleAssignMxDownload> mxList = recycleAssignMxDownloadService.lambdaQuery()
				.eq(ItfTblRecycleAssignMxDownload::getDownloadTaskNo, bean.getTaskNo()).list();
		// 记录表更新状态为已同步
		rec.setGreeStatSynStatus(GreeSynStatusEnum.FAIL.getCode());
		rec.setGreeStatSynTime(new Date());
		rec.setSynTimes(rec.getSynTimes()+1);
		// rec.setSynStatus(GreeSynStatusEnum.FAIL.getCode());
		rec.setSynReqTime(new Date());
		rec.setLastModifiedDate(new Date());
		rec.setGreeStatSynErrMsg(response.getMsg());
		recycleAssignBatchDownloadRecService.saveOrUpdate(rec);

		// 主表为成功
		ra.setGreeStatSynStatus(GreeSynStatusEnum.FAIL.getCode());
		ra.setGreeStatSynTime(new Date());
		ra.setSynReqTime(new Date());
		ra.setLastModifiedDate(new Date());
		ra.setSynErrMsg(response.getMsg());
		recycleAssignService.saveOrUpdate(ra);
		/*// 明细表为失败
		mxList.stream().forEach(o->{
			o.setGreeStatSynStatus(GreeSynStatusEnum.FAIL.getCode());
			o.setGreeStatSynTime(new Date());
			o.setLastModifiedDate(new Date());
			o.setSynErrMsg(response.getMsg());
		});
		if (mxList !=null && mxList.size()>0){
			recycleAssignMxDownloadService.saveOrUpdateBatch(mxList);
			mxList.clear();
		}*/
	}

	private void updateGreeStatSynStatus(GreeResponseHelper response) throws JsonProcessingException {
		RecycleAssignDownloadBean resultBean =  mapper.readValue(response.getData().toString(), RecycleAssignDownloadBean.class);
		// 记录表
		ItfTblRecycleAssignBatchDownloadRec rec = recycleAssignBatchDownloadRecService.lambdaQuery()
				.eq(ItfTblRecycleAssignBatchDownloadRec::getDownloadTaskNo, resultBean.getTaskNo()).one();
		// 回收工单主表
		ItfTblRecycleAssignDownload ra = recycleAssignService.lambdaQuery()
				.eq(ItfTblRecycleAssignDownload::getDownloadTaskNo, resultBean.getTaskNo()).one();
		// 回收明细表
		List<ItfTblRecycleAssignMxDownload> mxList = recycleAssignMxDownloadService.lambdaQuery()
				.eq(ItfTblRecycleAssignMxDownload::getDownloadTaskNo, resultBean.getTaskNo()).list();

		// 记录表更新状态为已同步
		rec.setGreeStatSynStatus(GreeSynStatusEnum.SYN.getCode());
		rec.setGreeStatSynTime(new Date());
		rec.setSynReqTime(new Date());
		rec.setLastModifiedDate(new Date());
		recycleAssignBatchDownloadRecService.saveOrUpdate(rec);
		// 主表
		ra.setGreeStatSynStatus(GreeSynStatusEnum.SYN.getCode());
		ra.setGreeStatSynTime(new Date());
		ra.setSynReqTime(new Date());
		ra.setLastModifiedDate(new Date());
		recycleAssignService.saveOrUpdate(ra);

		/*mxList.stream().forEach(o->{
			o.setGreeStatSynStatus(GreeSynStatusEnum.SYN.getCode());
			o.setGreeStatSynTime(new Date());
			o.setSynReqTime(new Date());
			o.setLastModifiedDate(new Date());
		});
		if (mxList!=null && mxList.size()>0){
			recycleAssignMxDownloadService.saveOrUpdateBatch(mxList);
			mxList.clear();
		}*/
	}



	
	public void processBusiness() {
 		//查找未同步到广佛系统且已经和总部同步的数据
 		//这里需要增加一个中间状态(反馈明细和采集明细是否已经同步)，代表工单信息已同步，但反馈明细或采集信息还没同步的，这里因为反馈和采集信息量过大，不能同一个接口传回来，所以分开
 		//44代表已同步反馈明细，66代表已经同步采集信息
		// 提取下载成功的记录数据
		List<ItfTblRecycleAssignBatchDownloadRec> recList = recycleAssignBatchDownloadRecService.lambdaQuery()
				.eq(ItfTblRecycleAssignBatchDownloadRec::getSynStatus, Constant.SynStatus.SYN_ACQUISITION.getCode())
				.eq(ItfTblRecycleAssignBatchDownloadRec::getGreeStatSynStatus,Constant.GreeSynStatus.SYN.getCode())
				.orderByAsc(ItfTblRecycleAssignBatchDownloadRec::getSynReqId)
				.list();
		if(Collections.isEmpty(recList)) {
			return;
		}
		for( ItfTblRecycleAssignBatchDownloadRec rec : recList ) {
			/*// 提取同步失败的或是还未从总部获取其他信息的记录数据-最近的一次
			List<ItfTblRecycleAssignBatchDownloadRec> lastTaskList = recycleAssignBatchDownloadRecService.lambdaQuery()
					.in(ItfTblRecycleAssignBatchDownloadRec::getSynStatus,
							new Integer[] { Constant.SynStatus.FAIL.getCode(),
									Constant.SynStatus.UN_SYN.getCode() })
					.lt(ItfTblRecycleAssignBatchDownloadRec::getSynReqId, rec.getSynReqId())
					.eq(ItfTblRecycleAssignBatchDownloadRec::getPgguid, rec.getPgguid())
					.orderByDesc(ItfTblRecycleAssignBatchDownloadRec::getSynReqId).list();

			if (!Collections.isEmpty(lastTaskList)) {
				ItfTblRecycleAssignBatchDownloadRec lastTask = lastTaskList.get(0);
				if (Constant.SynStatus.UN_SYN.getCode().intValue() == lastTask.getSynStatus()) {// 若上一条未同步，则本条跳过
					continue;
				} else {// 若上一条失败，则本条也不允许上传
					rec.setSynStatus(Constant.SynStatus.FAIL.getCode());
					rec.setSynErrMsg("上一条数据没上传成功，本条数据不上传, id=" + rec.getSynReqId());
					rec.setSynTime(new Date());
					continue;
				}
			}*/
			// 这里先不做处理
			// processBusiness(rec);
		}
	}

	/**
	 * 增删改网点关联数据
	 * @param type 类型：
	 * @param wdno 网点编号 
	 * @param recycleAssign 回收工单主表实体
	 * @param websit 网点实体
	 */
	/*@Transactional
	public void addOrUpdateOrderWebsitItem(Integer type, String wdno, OrderRecycleAssign recycleAssign, Websit websit){
		if(StringUtils.isNullOrEmpty(wdno)) {
			return;
		}
		//新增或修改的网点关联数据
		List<OrderWebsitItem> orderWebsitItemList = new ArrayList<>();
		//删除的网点关联数据
		List<Integer> delOrderWebsitItemIdsList = new ArrayList<>();
		//查询原来的维修网点编号
		final List<OrderWebsitItem> oldWebsitItemList = orderWebsitItemService.lambdaQuery()
				.eq(OrderWebsitItem::getOrderWebsitItemOrderId, recycleAssign.getId())
				.eq(OrderWebsitItem::getOrderWebsitItemOrderType, "order_recycle_assign")
				.eq(OrderWebsitItem::getOrderWebsitItemOrderWebsitType, type)
				.list();
		final Map<Integer, List<OrderWebsitItem>> oldWebsitItemMap = (Collections.isEmpty(oldWebsitItemList)) 
				? null : oldWebsitItemList.stream().collect(Collectors.groupingBy(OrderWebsitItem::getOrderWebsitItemOrderId));
		if(!StringUtil.isNullOrEmpty(wdno) ) {
			if(!Collections.isEmpty(oldWebsitItemList)) {//旧数据不为空, 则对比更新
				for( OrderWebsitItem oldWebsitItem : oldWebsitItemList) {
					oldWebsitItem.setOrderWebsitItemWebsitNumber(wdno);
					oldWebsitItem.setOrderWebsitItemWebsitBelongCompanyId(websit.getBelongCompanyId());
					oldWebsitItem.setOrderWebsitItemWebsitBelongCompany(websit.getBelongCompany());
					oldWebsitItem.setOrderWebsitItemWebsitId(websit.getId());
					orderWebsitItemList.add(oldWebsitItem);
				}
			}else {//旧数据为空，直接添加
				OrderWebsitItem orderWebsitItem = new OrderWebsitItem();
				orderWebsitItem.setOrderWebsitItemOrderId(recycleAssign.getId());
				orderWebsitItem.setOrderWebsitItemOrderWebsitType(type);
				orderWebsitItem.setOrderWebsitItemPgId(recycleAssign.getPgid());
				orderWebsitItem.setOrderWebsitItemOrderType("order_recycle_assign");
				orderWebsitItem.setOrderWebsitItemWorkerOrderNo(recycleAssign.getWorkerOrderNo());
				orderWebsitItem.setOrderWebsitItemWebsitNumber(wdno);
				orderWebsitItem.setOrderWebsitItemWebsitBelongCompanyId(websit.getBelongCompanyId());
				orderWebsitItem.setOrderWebsitItemWebsitBelongCompany(websit.getBelongCompany());
				orderWebsitItem.setOrderWebsitItemWebsitId(websit.getId());
				orderWebsitItemList.add(orderWebsitItem);
			}
		}else {//创建网点编号为空，删除原数据
			for( OrderWebsitItem oldWebsitItem : oldWebsitItemList) {
				delOrderWebsitItemIdsList.add(oldWebsitItem.getOrderWebsitItemId());
			}
		}
		if(!Collections.isEmpty(orderWebsitItemList)) {
			orderWebsitItemService.saveOrUpdateBatch(orderWebsitItemList);
		}
		if(!Collections.isEmpty(delOrderWebsitItemIdsList)) {
			orderWebsitItemService.removeByIds(delOrderWebsitItemIdsList);
		}
	}
	*/
	/**
	 * 批量处理同步状态
	 * @param rec
	 */
	/*
	public void batchProcessSynStatus(
			ItfTblRecycleAssignBatchDownloadRec rec,
			Integer synStatus,
			String msg
			) {
		if(Objects.isNull(rec)) {
			return ;
		}
		ItfTblRecycleAssignDownload recycleAssignDownload = recycleAssignService.lambdaQuery().eq(ItfTblRecycleAssignDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).one();
		List<ItfTblRecycleAssignFkmxDownload> recycleAssignFkmxDownloadList = recycleAssignFkmxDownloadService.lambdaQuery().eq(ItfTblRecycleAssignFkmxDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
		List<ItfTblRecycleAssignMxDownload> recycleAssignMxDownloadList = recycleAssignMxDownloadService.lambdaQuery().eq(ItfTblRecycleAssignMxDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
		List<ItfTblRecycleHsptJjcjDownload> recycleHsptJjcjDownloadList= recycleHsptJjcjDownloadService.lambdaQuery()
				.eq(ItfTblRecycleHsptJjcjDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
		List<ItfTblRecycleHsptJjcjFjDownload> recycleHsptJjcjFjDownloadList = recycleHsptJjcjFjDownloadService.lambdaQuery()
				.eq(ItfTblRecycleHsptJjcjFjDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
		List<ItfTblRecycleHsptJjcjTmmxDownload> recycleHsptJjcjTmmxDownloadList = recycleHsptJjcjTmmxDownloadService.lambdaQuery()
				.eq(ItfTblRecycleHsptJjcjTmmxDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
		if(!Objects.isNull(recycleAssignDownload)) {
			recycleAssignDownload.setSynStatus(rec.getSynStatus());
			recycleAssignDownload.setSynErrMsg(rec.getSynErrMsg());
			recycleAssignService.saveOrUpdate(recycleAssignDownload);
		}
		if(!Collections.isEmpty(recycleAssignFkmxDownloadList)) {
			for(ItfTblRecycleHsptJjcjFjDownload recycleAssignFkmxDownload : recycleAssignFkmxDownloadList) {
				recycleAssignFkmxDownload.setSynStatus(synStatus);
				recycleAssignFkmxDownload.setSynErrMsg(msg);
			}
			recycleAssignFkmxDownloadService.saveOrUpdateBatch(recycleAssignFkmxDownloadList);
		}
		if(!Collections.isEmpty(recycleAssignMxDownloadList)) {
			for(ItfTblRecycleAssignMxDownload recycleAssignMxDownload : recycleAssignMxDownloadList) {
				recycleAssignMxDownload.setSynStatus(synStatus);
				recycleAssignMxDownload.setSynErrMsg(msg);
			}
			recycleAssignMxDownloadService.saveOrUpdateBatch(recycleAssignMxDownloadList);
		}
		if(!Collections.isEmpty(recycleHsptJjcjDownloadList)) {
			for(ItfTblRecycleHsptJjcjDownload recycleHsptJjcjDownload : recycleHsptJjcjDownloadList) {
				recycleHsptJjcjDownload.setSynStatus(synStatus);
				recycleHsptJjcjDownload.setSynErrMsg(msg);
			}
			recycleHsptJjcjDownloadService.saveOrUpdateBatch(recycleHsptJjcjDownloadList);
		}
		if(!Collections.isEmpty(recycleHsptJjcjFjDownloadList)) {
			for(ItfTblRecycleHsptJjcjFjDownload recycleHsptJjcjFjDownload : recycleHsptJjcjFjDownloadList) {
				recycleHsptJjcjFjDownload.setSynStatus(synStatus);
				recycleHsptJjcjFjDownload.setSynErrMsg(msg);
			}
			recycleHsptJjcjFjDownloadService.saveOrUpdateBatch(recycleHsptJjcjFjDownloadList);
		}
		
		if(!Collections.isEmpty(recycleHsptJjcjTmmxDownloadList)) {
			for(ItfTblRecycleHsptJjcjTmmxDownload recycleHsptJjcjTmmxDownload : recycleHsptJjcjTmmxDownloadList) {
				recycleHsptJjcjTmmxDownload.setSynStatus(synStatus);
				recycleHsptJjcjTmmxDownload.setSynErrMsg(msg);
			}
			recycleHsptJjcjTmmxDownloadService.saveOrUpdateBatch(recycleHsptJjcjTmmxDownloadList);
		}
		return ;
	}
	*/
	
	/**
	 * 更新接口表数据到业务表
	 * @return
	 */

	/*
	@Transactional(rollbackFor = Exception.class)
	public void processBusiness(ItfTblRecycleAssignBatchDownloadRec rec) {
		if(Objects.isNull(rec)) {
			return ;
		}
		int synStatus = 1;
		String msg = "";
		try {
			// 主表
			ItfTblRecycleAssignDownload tblRecycleAssignEntity = recycleAssignService.lambdaQuery()
					.eq(ItfTblRecycleAssignDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).one();

			// 集团id 单独处理 brand_id 师傅信息

			// orderBase.setProductBrandId("A");
			// orderBase.setProductBrandName("格力(机型品牌)");









			// 反馈明细表
			List<ItfTblRecycleAssignFkmxDownload> lastStep = recycleAssignFkmxDownloadService.lambdaQuery()
					.eq(ItfTblRecycleAssignFkmxDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
			// 回收明细表
			List<ItfTblRecycleAssignMxDownload> hscpmx = recycleAssignMxDownloadService.lambdaQuery()
					.eq(ItfTblRecycleAssignMxDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
			//采集表
			List<ItfTblRecycleHsptJjcjDownload> jjcjList= recycleHsptJjcjDownloadService.lambdaQuery()
					.eq(ItfTblRecycleHsptJjcjDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
			// 采集附件表
			List<ItfTblRecycleHsptJjcjFjDownload> fjList = recycleHsptJjcjFjDownloadService.lambdaQuery()
					.eq(ItfTblRecycleHsptJjcjFjDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
			// 采集条码表
			List<ItfTblRecycleHsptJjcjTmmxDownload> tmmxList = recycleHsptJjcjTmmxDownloadService.lambdaQuery()
					.eq(ItfTblRecycleHsptJjcjTmmxDownload::getDownloadTaskNo, rec.getDownloadTaskNo()).list();
			
			if(Objects.isNull(tblRecycleAssignEntity)) {
				rec.setSynStatus(Constant.SynStatus.FAIL.getCode());
				rec.setSynErrMsg("下载主表为空, taskNO = {}" + rec.getDownloadTaskNo());
				rec.setSynTime(new Date());
				recycleAssignBatchDownloadRecService.saveOrUpdate(rec);
				return;
			}
			
			LinkedHashSet<String> webSitNums = new LinkedHashSet<>();
			//用省，市，区获取省，市，区id
			List<Area> provinceList = areaService.lambdaQuery().eq(Area::getArea, tblRecycleAssignEntity.getSfen()).eq(Area::getLevel, 1).eq(Area::getStatus, 1).list();
			List<Area> cityList = areaService.lambdaQuery().eq(Area::getName, tblRecycleAssignEntity.getCshi()).eq(Area::getLevel, 2).eq(Area::getStatus, 1).list();
			List<Area> areaList = areaService.lambdaQuery().eq(Area::getName, tblRecycleAssignEntity.getXian()).eq(Area::getLevel, 3).eq(Area::getStatus, 1).list();
			List<Area> streetList = areaService.lambdaQuery().eq(Area::getName, tblRecycleAssignEntity.getXzhen()).eq(Area::getLevel, 4).eq(Area::getStatus, 1).list();
			//维修网点（接收网点编号）新map， pgguid主键对应
			Map<Integer, Object> newWxWebsiteItemMap = new HashMap<>();
			//派工下级网点编号新map， pgguid主键对应
			Map<Integer, Object> newXjWebsiteItemMap = new HashMap<>();
			// 看工单主表是否已存在
			OrderRecycleAssign recycleAssign = orderRecycleAssignService.lambdaQuery()
					.eq(OrderRecycleAssign::getPgguid, tblRecycleAssignEntity.getPgguid()).one();
			if( !Objects.isNull(recycleAssign)) {
				// 更新
				BeanUtils.copyProperties(tblRecycleAssignEntity, recycleAssign, new String[] {"id","createTime","updateTime","deletetime"});
			}else {
				// 创建
				recycleAssign = mapper.readValue(mapper.writeValueAsString(tblRecycleAssignEntity), OrderRecycleAssign.class);



				recycleAssign.setCreateTime(new Date());
				//第一次下单状态为保存
				recycleAssign.setAppointState(0);
				recycleAssign.setLastAppointState(0);
				recycleAssign.setWorkerOrderNo(genWorkerNo());
			}
			recycleAssign.setUpdateTime(new Date());
			//设置经纬度
			recycleAssign.setLat(new BigDecimal(tblRecycleAssignEntity.getLatitude()));
			recycleAssign.setLng(new BigDecimal(tblRecycleAssignEntity.getLongitude()));
			if(provinceList.stream().filter(province->province.getName().equals(tblRecycleAssignEntity.getSfen())).findAny().isPresent()) {//广佛和总部省份对照
				recycleAssign.setProvinceId(provinceList.stream().filter(province->province.getName().equals(tblRecycleAssignEntity.getSfen())).collect(Collectors.toList()).get(0).getId());
			}
			if(cityList.stream().filter(city->city.getName().equals(tblRecycleAssignEntity.getCshi())).findAny().isPresent()) {//广佛和总部市对照
				recycleAssign.setCityId(cityList.stream().filter(city->city.getName().equals(tblRecycleAssignEntity.getCshi())).collect(Collectors.toList()).get(0).getId());
			}
			if(areaList.stream().filter(area->area.getName().equals(tblRecycleAssignEntity.getXian())).findAny().isPresent()) {//广佛和总部区对照
				recycleAssign.setAreaId(areaList.stream().filter(area->area.getName().equals(tblRecycleAssignEntity.getXian())).collect(Collectors.toList()).get(0).getId());
			}
			if(streetList.stream().filter(street->street.getName().equals(tblRecycleAssignEntity.getXzhen())).findAny().isPresent()) {//广佛和总部街道对照
				recycleAssign.setStreetId(streetList.stream().filter(street->street.getName().equals(tblRecycleAssignEntity.getXzhen())).collect(Collectors.toList()).get(0).getId());
			}
			recycleAssign.setOrderState(RecycleOrderStateEnum.findCode(tblRecycleAssignEntity.getStat()));
			recycleAssign.setLastOrderState(RecycleOrderStateEnum.findCode(tblRecycleAssignEntity.getQystat()));
			
			if( !StringUtil.isNullOrEmpty(recycleAssign.getCjwdno()) ) {//创建网点编号
				webSitNums.add(recycleAssign.getCjwdno());
			}
			//维修网点（接收网点编号）
			newWxWebsiteItemMap.put(recycleAssign.getId(),recycleAssign.getWxwdno() );
			if( !StringUtil.isNullOrEmpty(recycleAssign.getWxwdno()) ) {
				webSitNums.add(recycleAssign.getWxwdno());
			}
			//派工下级网点编号
			newXjWebsiteItemMap.put(recycleAssign.getId(),recycleAssign.getXjwdno() );
			if( !StringUtil.isNullOrEmpty(recycleAssign.getXjwdno()) ) {
				webSitNums.add(recycleAssign.getXjwdno());
			}
			if( lastStep.stream().filter(last->last.getDownloadTaskNo().equals(tblRecycleAssignEntity.getDownloadTaskNo())).findAny().isPresent() ) {
				RecycleAssignFkmxDownload fkmx = lastStep.stream().filter(last->last.getDownloadTaskNo().equals(tblRecycleAssignEntity.getDownloadTaskNo())).collect(Collectors.toList()).get(0);
				if(!StringUtil.isNullOrEmpty( fkmx.getFknr())  
						&&  (fkmx.getFknr().indexOf("派下级网点") > -1
								||fkmx.getFknr().indexOf("改派网点") > -1)
						&& fkmx.getFknr().indexOf("S21") > -1) {
					recycleAssign.setAppointDatetime( fkmx.getFksj() );
				}
			}
			
			orderRecycleAssignService.saveOrUpdate(recycleAssign);
			//插入和更新扩展表
			OrderRecycleAssignExpand expand = orderRecycleAssignExpandService.lambdaQuery().eq(OrderRecycleAssignExpand::getOrderId, recycleAssign.getId()).one();
			if(Objects.isNull(expand)) {
				expand = new OrderRecycleAssignExpand();
				expand.setOrderId(recycleAssign.getId());
				expand.setCreatetime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));  
			}
			expand.setFirstReserveWay(2);
			expand.setFirstReserveBegin(tblRecycleAssignEntity.getYhyykssj());
			expand.setFirstReserveEnd(tblRecycleAssignEntity.getYhyyjssj());
			expand.setFirstAppointDatetime(tblRecycleAssignEntity.getYhyykssj());
			expand.setUpdatetime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
			
			if(!Collections.isEmpty(lastStep)) {
				RecycleAssignFkmxDownload fkmx = lastStep.get(0);
				if(!StringUtil.isNullOrEmpty( fkmx.getFknr())  
						&& "指派工程师".equals(fkmx.getFklb()) ) {
//						firstAppointmentDateMap.put(o.getId(), fkmx.getFksj());
					expand.setFirstAppointDatetime(fkmx.getFksj());
				}
			}
			
			orderRecycleAssignExpandService.saveOrUpdate(expand);
			//反馈明细
			List<OrderRecycleAssignFkmx> fkmxEntitiesList = orderRecycleAssignFkmxService.lambdaQuery()
					.eq(OrderRecycleAssignFkmx::getOrderId, recycleAssign.getId()).list();
			//明细
			List<OrderRecycleAssignMx> mxEntitiesList = orderRecycleAssignMxService.lambdaQuery()
					.eq(OrderRecycleAssignMx::getOrderId, recycleAssign.getId()).list();
			//采集明细
			List<OrderRecycleAssignCollection> collectionEntitiesList = orderRecycleAssignCollectionService.lambdaQuery()
					.eq(OrderRecycleAssignCollection::getOrderId, recycleAssign.getId()).list();
			List<OrderRecycleAssignWorker> newWorkList = new ArrayList<>();
			
			//查询网点元数据，不过滤state为0的
			final List<Websit> websitList = websitService.lambdaQuery().in(Websit::getWebsitNumber, webSitNums).list();
			final Map<String, List<Websit>> websitMap = websitList.stream().collect(Collectors.groupingBy(Websit::getWebsitNumber));
			
			if( !Objects.isNull(websitMap) ) {
				//创建网点编号
				if( websitMap.containsKey(recycleAssign.getCjwdno()) 
						&& !Collections.isEmpty(websitMap.get(recycleAssign.getCjwdno()))){
					addOrUpdateOrderWebsitItem(RecycleOrderWebsitItemOrderWebsitTypeEnum.CREATE.getCode()
						, recycleAssign.getCjwdno()
						, recycleAssign, websitMap.get(recycleAssign.getCjwdno()).get(0));
				}
				
				//维修网点编号
				if( websitMap.containsKey(recycleAssign.getWxwdno()) 
						&& !Collections.isEmpty(websitMap.get(recycleAssign.getWxwdno()))){
					addOrUpdateOrderWebsitItem(RecycleOrderWebsitItemOrderWebsitTypeEnum.RECEIVE.getCode()
						, recycleAssign.getWxwdno()
						, recycleAssign, websitMap.get(recycleAssign.getWxwdno()).get(0));
				}
				
				if( websitMap.containsKey(recycleAssign.getXjwdno()) 
						&& !Collections.isEmpty(websitMap.get(recycleAssign.getXjwdno()))){
				//派送到下级网点编号
					addOrUpdateOrderWebsitItem(RecycleOrderWebsitItemOrderWebsitTypeEnum.SERVICE.getCode()
						, recycleAssign.getXjwdno()
						, recycleAssign, websitMap.get(recycleAssign.getXjwdno()).get(0));
				}
			}
			
			
			//新增师傅
			if(!Objects.isNull(tblRecycleAssignEntity.getWxrenid()) ) {
				Integer wxrenid = Integer.valueOf(tblRecycleAssignEntity.getWxrenid().toString()) ;
				
				List<WebsitWorker> websitWorkerList =  websitWorkerService.lambdaQuery().eq(WebsitWorker::getWorkerId, recycleAssign.getWxrenid()).list();
				//师傅map，方便查找
				List<OrderRecycleAssignWorker> workerList = orderRecycleAssignWorkerService.lambdaQuery().eq(OrderRecycleAssignWorker::getOrderId, recycleAssign.getId())
						.eq(OrderRecycleAssignWorker::getWebsitWorkerType, 1).list();
				if (!Collections.isEmpty(websitWorkerList) &&
						Collections.isEmpty(workerList)
							) {//维修人员
					OrderRecycleAssignWorker worker = new OrderRecycleAssignWorker();
					Date date = new Date();
					worker.setCreatetime(Integer.valueOf(String.valueOf(date.getTime()/1000)));  
					worker.setUpdatetime(Integer.valueOf(String.valueOf(date.getTime()/1000)));
					worker.setOrderId(recycleAssign.getId());
					worker.setWebsitWorkerId(wxrenid);
					worker.setWebsitWorkerType(1);
					newWorkList.add(worker);
				}
			}
			
			if(!Collections.isEmpty(lastStep)) {
				List<OrderRecycleAssignFkmx> fkmxList = new ArrayList<>();
				for( RecycleAssignFkmxDownload o : lastStep ) {
					if(!Collections.isEmpty(fkmxEntitiesList) 
							) {//找不到才新增数据
						boolean isFkmxExsits = true;
						for(OrderRecycleAssignFkmx fkmx : fkmxEntitiesList) {
							if( (StringUtils.isNullOrEmpty(fkmx.getFkid()) ? "" : fkmx.getFkid()).equals(o.getFkid()) ) {
								isFkmxExsits = false;
								break;
							}
						}
						if( !isFkmxExsits ) {
							OrderRecycleAssignFkmx fkmx = mapper.readValue(mapper.writeValueAsString(o), OrderRecycleAssignFkmx.class);
							fkmx.setCreateTime(new Date());
							fkmx.setUpdateTime(new Date());
							fkmx.setOrderId(recycleAssign.getId());
							fkmxList.add(fkmx);
						}
					}else {
						OrderRecycleAssignFkmx fkmx = mapper.readValue(mapper.writeValueAsString(o), OrderRecycleAssignFkmx.class);
						fkmx.setCreateTime(new Date());
						fkmx.setOrderId(recycleAssign.getId());
						fkmxList.add(fkmx);
					}
				}
				if(!fkmxList.isEmpty()) {
					orderRecycleAssignFkmxService.saveOrUpdateBatch(fkmxList);
				}
			}
			
			if(!Collections.isEmpty(hscpmx)) {
				List<OrderRecycleAssignMx> mxList = new ArrayList<>();
				for( RecycleAssignMxDownload o : hscpmx ) {
					if( !Collections.isEmpty(mxEntitiesList) 
							) {//找不到才新增数据
						boolean isMxExsists = true;
						for(OrderRecycleAssignMx mx : mxEntitiesList) {
							if((StringUtils.isNullOrEmpty(mx.getPgmxid()) ? "" : mx.getPgmxid()).equals(o.getPgmxid())) {
								isMxExsists = false;
								break;
							}
						}
						if(!isMxExsists) {
							OrderRecycleAssignMx mx = mapper.readValue(mapper.writeValueAsString(o), OrderRecycleAssignMx.class);
							mx.setCreateTime(new Date());
							mx.setUpdateTime(new Date());
							mx.setOrderId(recycleAssign.getId());
							mxList.add(mx);
						}
						
					}else {
						OrderRecycleAssignMx mx = mapper.readValue(mapper.writeValueAsString(o), OrderRecycleAssignMx.class);
						mx.setCreateTime(new Date());
						mx.setOrderId(recycleAssign.getId());
						mxList.add(mx);
					}
				}
				if(null !=mxList && !mxList.isEmpty()) {
					orderRecycleAssignMxService.saveOrUpdateBatch(mxList);
				}
				
			}
			
			//采集信息插入业务表
			if(!Collections.isEmpty(jjcjList)) {
				//采集表依赖与产品明细表，查找不到产品明细表则不插入
				if(!Collections.isEmpty(mxEntitiesList)) {
					//先循环一次获取师傅账号
					LinkedHashSet<String> workerNos = new LinkedHashSet<>();
					jjcjList.stream().forEach(o->{
						workerNos.add(o.getCreatedBy());
					});
					//师傅账号找不到，记录到中间表
					final List<WebsitWorker> websitWorkerByNosList = (workerNos.isEmpty()) ? null : (websitWorkerService.lambdaQuery().in(WebsitWorker::getNumber, workerNos)).list();
					final Map<String, List<WebsitWorker>> websitWorkerByNosMap = Collections.isEmpty(websitWorkerByNosList) ?  
							null : (websitWorkerByNosList.stream().collect(Collectors.groupingBy(WebsitWorker::getNumber)));
					Map<String, List<OrderRecycleAssignMx>> mxMap = Collections.isEmpty(mxEntitiesList) ? null : mxEntitiesList.stream().collect(Collectors.groupingBy(OrderRecycleAssignMx::getPgmxid));
					List<OrderRecycleAssignCollection> collectionList = new ArrayList<>();
					for( RecycleHsptJjcjDownload o : jjcjList ) {
						if(!Objects.isNull(mxMap) && mxMap.containsKey(o.getPgmxid()) 
								&&!Collections.isEmpty(mxMap)){
							//有该师傅账号，才添加数据
							if(!Objects.isNull(websitWorkerByNosMap )
									&& websitWorkerByNosMap.containsKey(o.getCreatedBy())
									&& !Collections.isEmpty(websitWorkerByNosMap.get(o.getCreatedBy()))) {
								if(!collectionEntitiesList.stream().filter(i->i.getPgwcmxid().equals(o.getPgwcmxid())).findAny().isPresent()) {//找不到才新增数据
									OrderRecycleAssignCollection collectionEntity = mapper.readValue(mapper.writeValueAsString(o), OrderRecycleAssignCollection.class);
									collectionEntity.setCreateTime(new Date());
									collectionEntity.setUpdateTime(new Date());
									collectionEntity.setOrderId(recycleAssign.getId());
									collectionEntity.setMxId(mxMap.get(o.getPgmxid()).get(0).getId());
									collectionEntity.setDismantle(o.getSfcj());
									collectionEntity.setIdentificationResult(o.getJdjg());
									collectionEntity.setMachineDefectData(o.getJjqsqk());
									collectionEntity.setMachineLmx(o.getPshu());
									if(null !=tmmxList && !tmmxList.isEmpty() && tmmxList.stream().filter(tmmx->tmmx.getDownloadTaskNo().equals(o.getDownloadTaskNo()))
											.filter(tmmx->tmmx.getTmlx()==0).findAny().isPresent()) {//有内机条码
										collectionEntity.setOutTempCode(tmmxList.stream().filter(tmmx->tmmx.getDownloadTaskNo().equals(o.getDownloadTaskNo()))
												.filter(tmmx->tmmx.getTmlx()==0).collect(Collectors.toList()).get(0).getJqtm());
									}
									if(null !=tmmxList && !tmmxList.isEmpty() && tmmxList.stream().filter(tmmx->tmmx.getDownloadTaskNo().equals(o.getDownloadTaskNo()))
											.filter(tmmx->tmmx.getTmlx()==1).findAny().isPresent()) {//有外机条码
										collectionEntity.setInsideTempCode(tmmxList.stream().filter(tmmx->tmmx.getDownloadTaskNo().equals(o.getDownloadTaskNo()))
												.filter(tmmx->tmmx.getTmlx()==1).collect(Collectors.toList()).get(0).getJqtm());
									}
									//状态设置为“已采集”
									collectionEntity.setStatus(1);
									collectionList.add(collectionEntity);
								}
							}else {
								o.setSynStatus(Constant.SynStatus.FAIL.getCode());
								o.setSynErrMsg("找不到师傅账号，添加采集信息失败: pgguid="+o.getPgguid()+", mxid="+o.getPgmxid()+", pgwcmxid="+o.getPgwcmxid()+", 师傅账号="+o.getCreatedBy());
							}
						}else {
							synStatus = Constant.SynStatus.FAIL.getCode();
							msg = "找不到产品明细信息，添加采集信息失败: pgguid="+o.getPgguid()+", mxid="+o.getPgmxid()+", pgwcmxid="+o.getPgwcmxid();
						}
					}
					if(!collectionList.isEmpty()) {
						orderRecycleAssignCollectionService.saveOrUpdateBatch(collectionList);
					}
				}
			}
			
		}catch(Exception e) {
			synStatus = Constant.SynStatus.FAIL.getCode();
			msg = (Objects.isNull(e) || Objects.isNull( e.getMessage())) ? "" : e.getMessage().length() > 100 ? e.getMessage().substring(0, 99) : e.getMessage();
		}
		
		
		//更新任务表
		if( Constant.SynStatus.SYN.getCode().intValue() == synStatus  ) {
			rec.setSynStatus(Constant.SynStatus.SYN.getCode());
			rec.setSynTime(new Date());
		}else {
			rec.setSynTimes(Objects.isNull(rec.getSynTimes()) ? 1 : rec.getSynTimes()+1);
			//请求次数达到6次，不再请求
			if(!Objects.isNull(rec.getSynTimes() ) && rec.getSynTimes() >= 6) {
				rec.setSynStatus(Constant.SynStatus.FAIL.getCode());
				rec.setSynErrMsg(msg);
				rec.setSynTime(new Date());
			}
		}
		recycleAssignBatchDownloadRecService.saveOrUpdate(rec);
		//批量处理下载数据状态
		batchProcessSynStatus(rec, synStatus, msg);
	}
*/

	public void syncDataCheck() {
		// 回收工单同步记录表提取待同步的过程反馈数据数据
		List<OrderRecycleUploadEvent> eventList = orderRecycleUploadEventService.lambdaQuery()
				.eq(OrderRecycleUploadEvent::getTableName, Constant.RecycleOrderType.RECYCLE_ASSIGN_FKMX)
				.eq(OrderRecycleUploadEvent::getSynStatus, Constant.SynStatus.UN_SYN.getCode()).list();
		if(CollectionUtils.isNotEmpty(eventList)) {
			for (OrderRecycleUploadEvent item:eventList){
				OrderBase order = orderBaseService.lambdaQuery()
						.eq(OrderBase::getPgguid, item.getOrderNo())
						.last("limit 1")
						.one();
				// 工单号，名表，记录ID
				publicService.checkWebsitSyncFlag(order.getId(),"order_recycle_upload_event",item.getSynReqId());
			}
		}

	}



	/**
	 * 状态上传接口
	 */
	@Transactional(rollbackFor = Exception.class)
	public void statusUpload() {
		// 查看该网点数据是否需要回传，不需要回传时直接修改同步状态将不再回传
		syncDataCheck();

		// 回收工单同步记录表提取待同步的过程反馈数据数据
		List<OrderRecycleUploadEvent> eventList = orderRecycleUploadEventService.lambdaQuery()
				.eq(OrderRecycleUploadEvent::getTableName, Constant.RecycleOrderType.RECYCLE_ASSIGN_FKMX)
				.eq(OrderRecycleUploadEvent::getSynStatus, Constant.SynStatus.UN_SYN.getCode()).list();

		if(CollectionUtils.isNotEmpty(eventList)) {
			final Map<String, List<OrderRecycleUploadEvent>> eventIdMap = eventList.stream()
					.collect(Collectors.groupingBy(OrderRecycleUploadEvent::getId));
			// 提取本次同步的过程反馈明细表对应的id
			LinkedHashSet<String> ids = new LinkedHashSet<>();
			eventList.stream().forEach(event->{
				ids.add(event.getId());
			});

			if(!ids.isEmpty()) {
				// 反馈明细表内根据id提取对应的反馈明细数据
				List<OrderRecycleAssignFkmx> feedbackList = orderRecycleAssignFkmxService.lambdaQuery()
						.in(OrderRecycleAssignFkmx::getId, ids).list();
				if(CollectionUtils.isNotEmpty(feedbackList)) {
					LinkedHashSet<Integer> orderIds = new LinkedHashSet<>();
					// 提取回收单id
					feedbackList.stream().forEach(feedback->{
						orderIds.add(feedback.getOrderId());
					});
					// 提取对应的回收工单主表数据
					List<OrderRecycleAssign> orderRecycleAssignList = orderRecycleAssignService.lambdaQuery()
							.in(OrderRecycleAssign::getId, orderIds).list();
					String batchNo = publicService.getUUID();
					// 逐条处理反馈明细表数据同步
					feedbackList.stream().forEach(feedback->{
						try {
							Boolean flag = Boolean.FALSE;
							String xjwdno = "";
							String xjwdmc = "";

							// 反馈明细数据
							OrderRecycleUploadEvent event =  eventIdMap.get(feedback.getId()).get(0);
							// 组装请求参数
							RecycleAssignFeedbackUploadBean feedbackUploadBean = mapper.readValue(mapper.writeValueAsString(feedback), RecycleAssignFeedbackUploadBean.class);
							feedbackUploadBean.setBatchNo(batchNo);
							feedbackUploadBean.setTaskNo(publicService.getUUID());
							feedbackUploadBean.setStat(orderRecycleAssignList.stream().filter(orderRecycleAssign->orderRecycleAssign.getId().intValue() == feedback.getOrderId().intValue()).collect(Collectors.toList()).get(0).getStat());
							feedbackUploadBean.setPgid(orderRecycleAssignList.stream().filter(orderRecycleAssign->orderRecycleAssign.getId().intValue() == feedback.getOrderId().intValue()).collect(Collectors.toList()).get(0).getPgid());

							if (feedback.getFklb().equals("改派网点") ||
									feedback.getFklb().equals("指派网点") ||
									feedback.getFklb().equals("自动派工")){
								flag = Boolean.TRUE;
								xjwdno = orderRecycleAssignList.stream().filter(orderRecycleAssign->orderRecycleAssign.getId().intValue() == feedback.getOrderId().intValue()).collect(Collectors.toList()).get(0).getXjwdno();
								xjwdmc = orderRecycleAssignList.stream().filter(orderRecycleAssign->orderRecycleAssign.getId().intValue() == feedback.getOrderId().intValue()).collect(Collectors.toList()).get(0).getXjwdmc();
							}

							GreeResponseHelper response = status(feedbackUploadBean,event,flag, xjwdno, xjwdmc);

						} catch (JsonProcessingException e) {
							log.error("statusUpload: 复制OrderRecycleAssignFkmx到RecycleAssignFeedbackUploadBean异常: {}", e.getMessage());
						}
					});
				}
			}
		}
	}

	@Transactional
	public GreeResponseHelper status(RecycleAssignFeedbackUploadBean feedbackUploadBean, OrderRecycleUploadEvent event,
									 Boolean flag, String xjwdno, String xjwdmc){
		if(null != feedbackUploadBean) {
			final String apiPath = Constant.GreeApiPath.RECYCLE_STATUS;
			ItfTblRecycleAssignFkmxUpload feedbackUpload = new ItfTblRecycleAssignFkmxUpload();
			try {
				feedbackUpload = mapper.readValue(mapper.writeValueAsString(feedbackUploadBean), ItfTblRecycleAssignFkmxUpload.class);
				Map<String,Object> map = mapper.readValue(mapper.writeValueAsString(feedbackUpload), Map.class);
				if (flag){
					map.put("xjwdno",xjwdno);
					map.put("xjwdmc",xjwdmc);
				}

				feedbackUpload.setSynStatus(Constant.SynStatus.SYN.getCode());
				feedbackUpload.setSynTime(new Date());
				feedbackUpload.setCreatedDate(new Date());
				feedbackUpload.setLastModifiedDate(new Date());
				feedbackUpload.setUploadBatchNo(feedbackUploadBean.getBatchNo());
				feedbackUpload.setUploadTaskNo(publicService.getUUID());
				feedbackUpload.setPgguid(feedbackUploadBean.getPgguid());
				//回收工单请求
				GreeResponseHelper response = greeLogic.greePost(apiPath, map, 1);
				if( 200 == response.getStatus()) {
					feedbackUpload.setGreeStatSynStatus(Constant.SynStatus.SYN.getCode());
					feedbackUpload.setGreeStatSynTime(new Date());
					event.setSynStatus(Constant.SynStatus.SYN.getCode());
					event.setSynTime(new Date());
				}else {
					feedbackUpload.setGreeStatSynStatus(Constant.SynStatus.FAIL.getCode());
					feedbackUpload.setGreeStatSynErrMsg(response.getMsg());
					feedbackUpload.setGreeStatSynTime(new Date());
					event.setSynStatus(Constant.SynStatus.FAIL.getCode());
					event.setSynErrMsg(response.getMsg());
					event.setSynTime(new Date());
				}
				recycleAssignFkmxUploadService.saveOrUpdate(feedbackUpload);
				orderRecycleUploadEventService.saveOrUpdate(event);
				return response;
			}catch(Exception e) {
				feedbackUpload.setGreeStatSynStatus(Constant.SynStatus.FAIL.getCode());
				feedbackUpload.setGreeStatSynTime(new Date());
				event.setSynStatus(Constant.SynStatus.FAIL.getCode());
				event.setSynTime(new Date());
				recycleAssignFkmxUploadService.saveOrUpdate(feedbackUpload);
				orderRecycleUploadEventService.saveOrUpdate(event);
			}
			
		}
		return null;
	}

}
