package com.zfire.jiasm.syncdata.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.base.BaseService;
import com.zfire.jiasm.syncdata.constant.Constant;
import com.zfire.jiasm.syncdata.constant.GreeSynStatusEnum;
import com.zfire.jiasm.syncdata.constant.OrderTypeEnum;
import com.zfire.jiasm.syncdata.gree.GreeLogic;
import com.zfire.jiasm.syncdata.gree.helper.GreeResponseHelper;
import com.zfire.jiasm.syncdata.gree.recycle.GreeLogicT;
import com.zfire.jiasm.syncdata.helper.GreeFileResponseHelper;
import com.zfire.jiasm.syncdata.helper.GreeFileSaveHelper;
import com.zfire.jiasm.syncdata.http.PostObjectSample;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
import com.zfire.jiasm.syncdata.request.oldfornew.TradeNewForOldStockBarcodeInfoUploadBean;
import com.zfire.jiasm.syncdata.request.oldfornew.TradeNewForOldUploadAttachmentBean;
import com.zfire.jiasm.syncdata.request.oldfornew.TradeNewForOldUploadBean;
import com.zfire.jiasm.syncdata.response.ResultData;
import com.zfire.jiasm.syncdata.response.WebsitSH;
import com.zfire.jiasm.syncdata.response.WorderInfo;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.utils.oss.OSSUtil;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OldForNewUploadLogic {
	@Value("${gree.web.url}")
    private String webUrl;
	@Autowired
	private GreeLogicT greeLogic;
	@Resource
	GreeLogic greeLogico;
	@Autowired
	private OutJiasmToGreeUploadnotifylistService outJiasmToGreeUploadnotifylistService;
	@Autowired
	private OldForNewProductService oldForNewProductService;
	@Autowired
	private OrderBaseService orderBaseService;
	@Autowired
	private ItfTblTradeNewForOldStockInfoUploadTaskService itfTblTradeNewForOldStockInfoUploadTaskService;
	@Autowired
	PublicService publicService;
	@Autowired
	SysDictRefService sysDictRefService;
	@Autowired
	BaseService baseService;
	@Autowired
	ItfTblYjhxJddUploadService itfTblYjhxJddUploadService;
	@Autowired
	ItfTblYjhxJddFjUploadService itfTblYjhxJddFjUploadService;
	@Autowired
	OSSUtil ossUtil;
	@Autowired
	ItfTblTradeNewForOldRejectJddDownloadService itfTblTradeNewForOldRejectJddDownloadService;
	@Autowired
	ItfTblRecycleStockBarcodeInfoUploadService barcodeInfoUploadService;
	@Autowired
	YjhxAppraiseService yjhxAppraiseService;

	private ObjectMapper mapper;




	public OldForNewUploadLogic() {
		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);
	}


	public void collection() {
		// 只有类型为35，36的工单需要同步回总部 自建以旧换新不需要传总部
		// 提取待同步的以旧换新工单的签定单数据
		List<OutJiasmToGreeUploadnotifylist> toGreeUploadList = outJiasmToGreeUploadnotifylistService.lambdaQuery()
				.eq(OutJiasmToGreeUploadnotifylist::getTableName, OrderTypeEnum.YJHX_JDD_TABLE_NAME.getCode())
				.eq(OutJiasmToGreeUploadnotifylist::getOrderType, OrderTypeEnum.ORDER_TYPE_TRADE_IN.getCode())
				.eq(OutJiasmToGreeUploadnotifylist::getSynStatus, Constant.SynStatus.UN_SYN.getCode())
				.list();

		// 无数据不同步
		if(CollectionUtils.isNotEmpty(toGreeUploadList)) {
			LinkedHashSet<String> uploadOrderNos = new LinkedHashSet<>();

			// 提取所有工单号
			toGreeUploadList.stream().forEach(toGreeUpload->{
				uploadOrderNos.add(toGreeUpload.getOrderNo());
			});
			// 提取以旧换新工单的旧机信息
			final List<OldForNewProduct> oldForNewProductList = oldForNewProductService.lambdaQuery()
					.in(OldForNewProduct::getOrderBaseId, uploadOrderNos).list();
			Map<String, OldForNewProduct> oldForNewProductMap  = CollectionUtils.isEmpty(oldForNewProductList)
					? null : oldForNewProductList.stream().collect(Collectors.toMap(OldForNewProduct::getOrderBaseId, Function.identity()));

			// 提取已采集需上传的鉴定单数据 只取状态为已采集的
			final List<YjhxAppraise> jddList = yjhxAppraiseService.lambdaQuery()
					.in(YjhxAppraise::getOrderBaseId, uploadOrderNos)
					.eq(YjhxAppraise::getCollectionStatus, 1)
					.eq(YjhxAppraise::getUploadNotifyFlag, 1)
					.list();
			// 这里ID做为 key
			final Map<Integer, List<YjhxAppraise>> jddMap =
					(null == jddList || jddList.isEmpty()) ?
							null : jddList.stream().collect(Collectors.groupingBy(YjhxAppraise::getId));

			// 按单来处理 要有鉴定单
			for(OutJiasmToGreeUploadnotifylist toGreeUpload : toGreeUploadList) {
				// 查看该网点数据是否需要回传，不需要回传时直接修改同步状态将不再回传
				// 工单号，名表，记录ID
				if (publicService.checkWebsitSyncFlag(toGreeUpload.getOrderNo(),"out_jiasm_to_gree_uploadnotifylist",toGreeUpload.getSynReqId())){
					continue;
				}

				// 存在鉴定单数据
				if( !Objects.isNull(jddMap) && jddMap.containsKey(Integer.parseInt(toGreeUpload.getId()))) {
					// 提取工单数据 目的看工单大类数据
					OrderBase orderBase = orderBaseService.lambdaQuery()
							.eq(OrderBase::getId,toGreeUpload.getOrderNo())
							.last("limit 1")
							.one();

					for(YjhxAppraise jdd : jddList) {
						// 取工单对应的鉴定单
						if (!jdd.getOrderBaseId().equals(toGreeUpload.getOrderNo())){
							continue;
						}
						// 广佛鉴定结果 identifyResult为0（不回收）、不同步总部
						if( "0".equals(jdd.getIdentifyResult()) ) {
							continue;
						}

						// 生成格力总部图片(条码图及全景图) 图片生成失败不同步
						if (setGreeImage(orderBase, jdd)) {
							continue;
						}

						// 以旧换新鉴定单采集附件表
						List<ItfTblYjhxJddFjUpload>  yjhxJddFjUploadList = new ArrayList<>();
						ItfTblYjhxJddUpload yjhxJddUpload = new ItfTblYjhxJddUpload();
						TradeNewForOldUploadBean bean = new TradeNewForOldUploadBean();

						// 鉴定单报文这里已赋值了条码图片 OK
						BeanUtils.copyProperties(jdd, bean,new String[] {"gps", "sjcjsfen", "sjcjcshi", "sjcjxian","gpsdizi",
										"wdno", "wdmc", "azrenno","azren", "azrenyddh"});

						// 赋值旧机信息
						if (setOldForNewProduct(oldForNewProductMap, jdd, bean)) {
							continue;
						}

						// 部分参数赋值
						setParame(orderBase, jdd, bean);

						// 鉴定单上传记录表
						BeanUtils.copyProperties(bean, yjhxJddUpload, ItfTblYjhxJddUpload.class);
						yjhxJddUpload.setWorkerOrderNo(jdd.getOrderBaseId());
						yjhxJddUpload.setHxjddid(jdd.getHxjddid());

						// 附件上传记录表
						List<TradeNewForOldUploadAttachmentBean> jddfjList = new ArrayList<>();
						// 内、外机全景照处理
						if(StringUtils.isNotEmpty(jdd.getGreeImgIdAllOther())) {
							getFileAttUpload(jdd, yjhxJddFjUploadList, yjhxJddUpload, jddfjList);
						}
						bean.setJddfj(jddfjList);

						// 同步数据 + 新增一条待入库条码上传记录
						synData(jdd, yjhxJddUpload, bean);

						processSave(yjhxJddUpload, yjhxJddFjUploadList,toGreeUpload,jdd);
					}
				}else {
					// yjhx_jdd无数据不同步
					processSave(null, null,toGreeUpload,null);
				}
			}
		}
	}

	private boolean setGreeImage(OrderBase orderBase, YjhxAppraise jdd) {
		WebsitSH websitSH = publicService.ptshwdToshshwd(jdd.getWebsitId(), orderBase.getMainId());
		Boolean upflag = Boolean.FALSE;
		// 图片生成 条码图片 njtm图像#wjtm图像
		if (StringUtils.isEmpty(jdd.getTempBarcodeImg()) &&
				(StringUtils.isNotEmpty(jdd.getNjtmPicture()) ||
						StringUtils.isNotEmpty(jdd.getWjtmPicture()))){
			// 获取条码总部图
			String greeImageId = getBarcodeImage(jdd, websitSH);
			if (greeImageId == null) {
				return true;
			}
			// 修改
			jdd.setTempBarcodeImg(greeImageId);
			upflag = Boolean.TRUE;
		}

		// 全景图片  in_full_picture#out_full_picture#other_picture
		if (StringUtils.isEmpty(jdd.getGreeImgIdAllOther()) &&
				(StringUtils.isNotEmpty(jdd.getInFullPicture()) ||
						StringUtils.isNotEmpty(jdd.getOutFullPicture()) ||
						StringUtils.isNotEmpty(jdd.getOtherPicture()))){

			// 获取总部全景图
			String greeImageId = getFullImage(jdd, websitSH);
			if (greeImageId == null) {
				return true;
			}
			// 修改
			jdd.setGreeImgIdAllOther(greeImageId);
			upflag = Boolean.TRUE;
		}
		if (StringUtils.isNotEmpty(jdd.getTempBarcodeImg()) &&
				StringUtils.isNotEmpty(jdd.getGreeImgIdAllOther()) && jdd.getGetGreeImageIdStatus() !=1){
			jdd.setGetGreeImageIdStatus(1);
			upflag = Boolean.TRUE;
		}
		if (upflag){
			yjhxAppraiseService.updateById(jdd);
		}
		return false;
	}

	@Nullable
	private String getFullImage(YjhxAppraise jdd, WebsitSH websitSH) {
		String greeImageId = "";
		String greeImageIdN = "";
		String greeImageIdW = "";
		String greeImageIdO = "";

		if (StringUtils.isNotEmpty(jdd.getInFullPicture())){
			greeImageIdN = getImage(jdd.getInFullPicture(), websitSH);
			if (greeImageIdN == null) {
				return null;
			}
		}

		if (StringUtils.isNotEmpty(jdd.getOutFullPicture())){
			greeImageIdW = getImage(jdd.getOutFullPicture(), websitSH);
			if (greeImageIdW == null) {
				return null;
			}
		}

		if (StringUtils.isNotEmpty(jdd.getOtherPicture())){
			greeImageIdO = getImage(jdd.getOtherPicture(), websitSH);
			if (greeImageIdO == null) {
				return null;
			}
		}

		if (StringUtils.isNotEmpty(greeImageIdN)){
			greeImageId=greeImageIdN;
			if (StringUtils.isNotEmpty(greeImageIdW)){
				greeImageId=greeImageId+"#"+greeImageIdW;
			}
			if (StringUtils.isNotEmpty(greeImageIdO)){
				greeImageId=greeImageId+"#"+greeImageIdO;
			}
		} else {
			if (StringUtils.isNotEmpty(greeImageIdW)){
				greeImageId=greeImageIdN;
				if (StringUtils.isNotEmpty(greeImageIdO)){
					greeImageId=greeImageId+"#"+greeImageIdO;
				}
			} else {
				greeImageId=greeImageIdO;
			}
		}
		return greeImageId;
	}

	@Nullable
	private String getBarcodeImage(YjhxAppraise jdd,WebsitSH websitSH) {
		String greeImageId = "";
		String greeImageIdN = "";
		String greeImageIdW = "";

		if (StringUtils.isNotEmpty(jdd.getNjtmPicture())){
			greeImageIdN = getImage(jdd.getNjtmPicture(), websitSH);
			if (greeImageIdN == null) {
				return null;
			}
		}

		if (StringUtils.isNotEmpty(jdd.getWjtmPicture())){
			greeImageIdW = getImage(jdd.getWjtmPicture(), websitSH);
			if (greeImageIdW == null) {
				return null;
			}
		}

		if (StringUtils.isNotEmpty(greeImageIdN) && StringUtils.isNotEmpty(greeImageIdW)){
			greeImageId=greeImageIdN+"#"+greeImageIdW;
		} else if (StringUtils.isNotEmpty(greeImageIdN)){
			greeImageId=greeImageIdN;
		} else {
			greeImageId=greeImageIdW;
		}
		return greeImageId;
	}

	@Nullable
	private String getImage(String picture, WebsitSH websitSH) {
		String oldFile;
		String newFile;
		String greeImageIdN;
		oldFile = publicService.path(picture);
		File nFile = new File(oldFile);

		baseService.saveToFile(ossUtil.getUrlWw(picture), nFile);
		// 获取文件
		newFile = oldFile;
		greeImageIdN = uploadBarCodeexc(newFile, oldFile, websitSH.getWdId());
		new File(newFile).delete();
		// 生成图片失败不同步
		if (StringUtils.isEmpty(greeImageIdN)) {
			return null;
		}
		return greeImageIdN;
	}

	private void getSaveFileInfo(String id1, ResultData resultData, Map<String, String> req) {
		req.put("bizAppId","flydiy-auto-sit-default-front-greeshmerge");
		req.put("bizTable","default");
		req.put("bizType","default");
		req.put("accessType","auth");
		req.put("url", resultData.getExtData().getDir());
		// req.put("name", id1 +".jpeg");
		req.put("name", id1);
	}

	private String uploadBarCodeexc(String newFile, String oldFile,String wdno) {
		String greeImageId ="";
		try{
			// 1: 获取签名信息
			GreeFileResponseHelper response =  greeLogico.ossGetSignt(wdno,"GET");
			if (response.getStatusCode() == 200){
				ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
				resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+oldFile);
				// 2:文件上传
				PostObjectSample ossPostObject = new PostObjectSample();
				String result = ossPostObject.PostObject(newFile, resultData.getExtData());
				// 3: 保存文件
				if (org.apache.commons.lang3.StringUtils.isEmpty(result.trim())){
					Map<String,String>req = new HashMap<>();
					// 生成对象
					getSaveFileInfo(oldFile, resultData, req);
					GreeFileSaveHelper responses = greeLogico.greePostSaveFile(req);
					if (responses.getStatusCode() == 200){
						greeImageId = responses.getData().getId();
						return greeImageId;
					} else {
						// 失败
						return greeImageId;
					}
				} else {
					// 上传图片到OSS失败
					return greeImageId;
				}
			} else {
				//  获取签名信息失败
				return greeImageId;
			}
		} catch (Exception ex) {
			return greeImageId;
		}
	}

	private void synData(YjhxAppraise jdd, ItfTblYjhxJddUpload yjhxJddUpload, TradeNewForOldUploadBean bean) {
		final String url = webUrl + Constant.GreeWebPath.TBLYJHXJDD_COLLECTION;
		try {
			JSONObject response = greeLogic.postPubV3(url, mapper.readValue(mapper.writeValueAsString(bean), Map.class));
			//log.info("TradeOldForNewLogic.collection接口返回:{}",response.toJSONString());
			if( 200 == response.getInteger("status").intValue()) {
				TradeNewForOldUploadBean reponseData = this.mapper.readValue(mapper.writeValueAsString(response.get("data")), TradeNewForOldUploadBean.class) ;
				// 同步成功，同步鉴定单上传记录表数据
				yjhxJddUpload.setSynStatus(Constant.SynStatus.SYN.getCode());
				yjhxJddUpload.setSynTime(new Date());
				yjhxJddUpload.setWdno(bean.getWdno());
				yjhxJddUpload.setWdmc(bean.getWdmc());
				// 这里的ID来自于总部
				jdd.setGreeId(reponseData.getId());
				// 上传时自生成了ID，上传成后需使用总部的ID 这样再次从总部获取时，进行了修改，不会再存在两条以上的数据了
				jdd.setHxjddid(reponseData.getId());
				//鉴定结果业务表回写状态为0（无需上传）
				jdd.setUploadNotifyFlag(0);
				if( null != reponseData.getJddfj() && !reponseData.getJddfj().isEmpty()) {
					StringBuffer sb = new StringBuffer();
					reponseData.getJddfj().forEach(jddFj->{
						sb.append("#");
						sb.append(jddFj.getFjguid());
					});
					String fjguids = sb.toString();
					// 来自总部数据
					jdd.setGreeFjguid(fjguids.substring(1, fjguids.length()));
				}

				//新增一条待入库条码上传记录
				ItfTblTradeNewForOldStockInfoUploadTask tradeNewForOldStockInfoUploadTask = new ItfTblTradeNewForOldStockInfoUploadTask();
				tradeNewForOldStockInfoUploadTask.setPgguid(jdd.getPgguid());
				tradeNewForOldStockInfoUploadTask.setSynStatus(Constant.SynStatus.UN_SYN.getCode());
				tradeNewForOldStockInfoUploadTask.setSynReqTime(new Date());
				tradeNewForOldStockInfoUploadTask.setSynTimes(1);
				itfTblTradeNewForOldStockInfoUploadTaskService.save(tradeNewForOldStockInfoUploadTask);
			} else {
				// 修改鉴定单同步失败状态
				yjhxJddUpload.setSynStatus(Constant.SynStatus.FAIL.getCode());
				yjhxJddUpload.setSynErrMsg(response.getString("messageCode"));
				yjhxJddUpload.setSynTime(new Date());
			}

		} catch (Exception e) {
			yjhxJddUpload.setSynStatus(Constant.SynStatus.FAIL.getCode());
			yjhxJddUpload.setSynErrMsg(e.getMessage().length() > 100 ? e.getMessage().substring(0, 99): e.getMessage());
			log.error("collection接口报错： {}", e.getMessage());
			yjhxJddUpload.setSynTime(new Date());
		}
	}

	private void getFileAttUpload(YjhxAppraise jdd, List<ItfTblYjhxJddFjUpload> yjhxJddFjUploadList,
								  ItfTblYjhxJddUpload yjhxJddUpload, List<TradeNewForOldUploadAttachmentBean> jddfjList) {
		// 总部图片，除了tempBarcodeImg以外的所有，#号分割，in_full_picture#out_full_picture#other_picture
		String[] fullimgs = jdd.getGreeImgIdAllOther().split("#");
		List<String> greeFjguidArr = new ArrayList<>();
		// 这里为附件图片处理  格力总部附件id， #号分割，in_fjid#out_fjid#other_fjid
		// 该参数来自总部 报文同步后才有值
		if(StringUtils.isNotEmpty(jdd.getGreeFjguid())) {
			String[] greeFjguids = jdd.getGreeFjguid().split("#");
			for(String greeFjguid : greeFjguids) {
				greeFjguidArr.add(greeFjguid);
			}
		}

		//内机全景图
		getInFileAttUpload(jdd, yjhxJddFjUploadList, yjhxJddUpload, jddfjList, greeFjguidArr, fullimgs, 1, 0, "旧机内机整机", "复制内机bean异常,{}");

		//外机全景图
		getOutFileAttUpload(jdd, yjhxJddFjUploadList, yjhxJddUpload, jddfjList, greeFjguidArr, fullimgs, 2, 1, "旧机外机整机", "复制外机bean异常,{}");

		//其他图
		if(fullimgs.length > 2) {
			getOtherFileAttUpload(jdd, yjhxJddFjUploadList, yjhxJddUpload, jddfjList, greeFjguidArr, fullimgs, 3, 2, "其他", "复制其他bean异常,{}");
		}
	}

	private void getOtherFileAttUpload(YjhxAppraise jdd, List<ItfTblYjhxJddFjUpload> yjhxJddFjUploadList,
									   ItfTblYjhxJddUpload yjhxJddUpload, List<TradeNewForOldUploadAttachmentBean> jddfjList,
									   List<String> greeFjguidArr, String[] fullimgs, int i, int i2, String 其他, String s) {
		ItfTblYjhxJddFjUpload otherFileAttUpload = new ItfTblYjhxJddFjUpload();
		if (greeFjguidArr.size() >= i) {
			//其他
			otherFileAttUpload.setFjguid(greeFjguidArr.get(i2));
		}
		otherFileAttUpload.setHxjddid(jdd.getHxjddid());
		otherFileAttUpload.setFjname(其他);
		otherFileAttUpload.setFjserverpath(fullimgs[i2]);
		otherFileAttUpload.setFjindex(i2);
		otherFileAttUpload.setType(30);
		otherFileAttUpload.setWorkerOrderNo(yjhxJddUpload.getWorkerOrderNo());
		yjhxJddFjUploadList.add(otherFileAttUpload);
		try {
			jddfjList.add(mapper.readValue(mapper.writeValueAsString(otherFileAttUpload), TradeNewForOldUploadAttachmentBean.class));
		} catch (JsonProcessingException e) {
			log.error(s, e.getMessage());
		}
	}

	private void getOutFileAttUpload(YjhxAppraise jdd, List<ItfTblYjhxJddFjUpload> yjhxJddFjUploadList,
									 ItfTblYjhxJddUpload yjhxJddUpload, List<TradeNewForOldUploadAttachmentBean> jddfjList,
									 List<String> greeFjguidArr, String[] fullimgs, int i, int i2,
									 String 旧机外机整机, String s) {
		ItfTblYjhxJddFjUpload outFileAttUpload = new ItfTblYjhxJddFjUpload();
		if (greeFjguidArr.size() >= i) {
			//内机附件id
			outFileAttUpload.setFjguid(greeFjguidArr.get(i2));
		}
		outFileAttUpload.setHxjddid(jdd.getHxjddid());
		outFileAttUpload.setFjname(旧机外机整机);
		outFileAttUpload.setFjserverpath(fullimgs[i2]);
		outFileAttUpload.setFjindex(i2);
		outFileAttUpload.setType(30);
		outFileAttUpload.setWorkerOrderNo(yjhxJddUpload.getWorkerOrderNo());
		yjhxJddFjUploadList.add(outFileAttUpload);
		try {
			jddfjList.add(mapper.readValue(mapper.writeValueAsString(outFileAttUpload), TradeNewForOldUploadAttachmentBean.class));
		} catch (JsonProcessingException e) {
			log.error(s, e.getMessage());
		}
	}

	private void getInFileAttUpload(YjhxAppraise jdd, List<ItfTblYjhxJddFjUpload> yjhxJddFjUploadList, ItfTblYjhxJddUpload yjhxJddUpload,
									List<TradeNewForOldUploadAttachmentBean> jddfjList, List<String> greeFjguidArr,
									String[] fullimgs, int i, int i2, String 旧机内机整机, String s) {
		ItfTblYjhxJddFjUpload inFileAttUpload = new ItfTblYjhxJddFjUpload();
		if (greeFjguidArr.size() >= i) {
			//内机附件id
			inFileAttUpload.setFjguid(greeFjguidArr.get(i2));
		}
		inFileAttUpload.setHxjddid(jdd.getHxjddid());
		inFileAttUpload.setFjname(旧机内机整机);
		inFileAttUpload.setFjserverpath(fullimgs[i2]);
		inFileAttUpload.setFjindex(i2);
		inFileAttUpload.setType(30);
		inFileAttUpload.setWorkerOrderNo(yjhxJddUpload.getWorkerOrderNo());
		yjhxJddFjUploadList.add(inFileAttUpload);

		try {
			jddfjList.add(mapper.readValue(mapper.writeValueAsString(inFileAttUpload), TradeNewForOldUploadAttachmentBean.class));
		} catch (JsonProcessingException e) {
			log.error(s, e.getMessage());
		}
	}

	private boolean setOldForNewProduct(Map<String, OldForNewProduct> oldForNewProductMap, YjhxAppraise jdd, TradeNewForOldUploadBean bean) {
		// 看旧机信息大类决定是否需要上传
		if( !Objects.isNull(oldForNewProductMap)
				&& oldForNewProductMap.containsKey(jdd.getOrderBaseId())
				&& !Objects.isNull(oldForNewProductMap.get(jdd.getOrderBaseId()))
				) {
			// 以旧换新工单的旧机信息
			OldForNewProduct oldFornew = oldForNewProductMap.get(jdd.getOrderBaseId());
			//main_id非空和101时，才传旧机鉴定
			if( Objects.isNull(oldFornew.getMainId()) || !oldFornew.getMainId().equals("101")){
				log.info("TradeOldForNewLogic.collection接口: spid为空或非空调类，不上传旧机鉴定");
				return true;
			}
			// 旧机信息赋值 OK
			BeanUtils.copyProperties(oldFornew, bean, TradeNewForOldUploadBean.class);
			bean.setIdCardStatus(oldFornew.getIdCardStatus());
			bean.setIsSubsidy(oldFornew.getIsSubsidy());
		}
		return false;
	}

	private void setParame(OrderBase orderBase, YjhxAppraise jdd, TradeNewForOldUploadBean bean) {
		WebsitSH websitSH;
		// hxjddido 为空时说明为平台自建的鉴定数据 自生成
		if (StringUtils.isEmpty(jdd.getHxjddid())){
			jdd.setHxjddid(publicService.getUUID());
		}
		// greeid为同步成来自于于格力总部
		bean.setId(jdd.getGreeId());
		//greeId和hxjddid设置成同一个 格力部部本身是同一个值
		if(StringUtils.isNotEmpty(jdd.getGreeId())) {
			jdd.setHxjddid(jdd.getGreeId());
		}

		//鉴定结果相反，总部鉴定结果0-回收 1-不回收， 广佛鉴定结果1-回收 0-不回收
		bean.setIdentifyResult("1".equals(StringUtils.isEmpty(jdd.getIdentifyResult()) ? "" : jdd.getIdentifyResult()) ? "0" : "1");
		//1 格力 0 非格力
		bean.setBrandFlag( "格力".equals(StringUtils.isEmpty(jdd.getRealBrand()) ? "" : jdd.getRealBrand()) ? 1 : 0 );
		//0 柜机 1 挂机
		bean.setTypeFlag("柜机".equals(  StringUtils.isEmpty(jdd.getRealType()) ? "" : jdd.getRealType() ) ? 0 : 1);
		bean.setOldMachineBrand(bean.getRealBrand());
		bean.setOldMachineType(bean.getRealType());
		bean.setStat("0");
		//gps地址
		if(!StringUtils.isEmpty(jdd.getLat()) && !StringUtils.isEmpty(jdd.getLng())) {
			bean.setGps(jdd.getLat()+","+ jdd.getLng());
		}else if(StringUtils.isEmpty(jdd.getLat())) {
			log.info("TradeOldForNewLogic.collection接口: 经度为空, jdd.id={}", jdd.getId());
		}else if(StringUtils.isEmpty(jdd.getLng())) {
			log.info("TradeOldForNewLogic.collection接口: 纬度为空, jdd.id={}", jdd.getId());
		}
		// 这里的 GPS 30个字符不能超30个字符
		if (!StringUtils.isEmpty(bean.getGps())){
			if (bean.getGps().length()>30){
				bean.setGps(bean.getGps().substring(0,30));
			}
		}

		bean.setSjcjsfen(jdd.getProvince());
		bean.setSjcjcshi(jdd.getCity());
		bean.setSjcjxian(jdd.getArea());
		bean.setGpsdizi(jdd.getAddress());
		websitSH = publicService.ptshwdToshshwd(jdd.getWebsitId(), orderBase.getMainId());
		bean.setWdno(websitSH.getWdId());
		bean.setWdmc(websitSH.getWdmc());
		WorderInfo worderInfo = publicService.getWorkerInfo(jdd.getWorkerId(),
				websitSH.getWdId(), orderBase.getGroupCompanyId());
		bean.setAzren(worderInfo.getBrandWorkerNumber());
		bean.setAzrenyddh(worderInfo.getMobile());
	}

	private void updateJdd(YjhxAppraise jdd, TradeNewForOldUploadBean bean) {
		Boolean flag = Boolean.FALSE;
		// 来自报文请求后的id,
		if (StringUtils.isEmpty(jdd.getGreeId())){
			jdd.setGreeId(publicService.getUUID());
			flag=Boolean.TRUE;
		}
		bean.setId(jdd.getGreeId());
		//greeId和hxjddid设置成同一个
		if(StringUtils.isNotEmpty(jdd.getGreeId())) {
			jdd.setHxjddid(jdd.getGreeId());
		}
		if(StringUtils.isNotEmpty(jdd.getGreeImgIdAllOther())) {
			// 这里为内外机全图看有多少个图
			String[] imgs = jdd.getGreeImgIdAllOther().split("#");
			// 这里为附件图片处理  格力总部附件id， #号分割，in_fjid#out_fjid#other_fjid
			// 自生成
			if (StringUtils.isEmpty(jdd.getGreeFjguid())) {
				String uuid = "";
				for (int i = 0; i < imgs.length; i++) {
					uuid = uuid + publicService.getUUID() + "#";
				}
				// 来自于报文请求后的id
				jdd.setGreeFjguid(uuid.substring(0, uuid.length() - 1));
				flag=Boolean.TRUE;
			}
		}
		if (flag){
			yjhxAppraiseService.updateById(jdd);
		}
	}

	/**
	 * 回写状态到中间表
	 * @param yjhxJddUpload
	 * @param yjhxJddFjUploadList
	 * @param toGreeUploadnotifylist
	 * @param jdd
	 */
	@Transactional
	public void processSave(
			ItfTblYjhxJddUpload yjhxJddUpload,
			List<ItfTblYjhxJddFjUpload> yjhxJddFjUploadList,
			OutJiasmToGreeUploadnotifylist toGreeUploadnotifylist
			,YjhxAppraise jdd) {
		try {
		Integer synStatus = -1;
		String msg = "";
		//yjhxJddUpload为空，说明没有请求总部接口，toGreeUploadnotifylist请求数需要累加，超过6次不再请求
		if( null != yjhxJddUpload  ) {
			yjhxJddUpload.setCreatedBy("guangfo");
			yjhxJddUpload.setCreatedDate(new Date());
			yjhxJddUpload.setLastModifiedBy("guangfo");
			yjhxJddUpload.setLastModifiedDate(new Date());
			itfTblYjhxJddUploadService.saveOrUpdate(yjhxJddUpload);
			msg = yjhxJddUpload.getSynErrMsg();
			if( Constant.SynStatus.SYN.getCode().intValue() == yjhxJddUpload.getSynStatus()) {
				synStatus = Constant.SynStatus.SYN.getCode();
			}
			if( null != yjhxJddFjUploadList && !yjhxJddFjUploadList.isEmpty()) {
				yjhxJddFjUploadList.stream().forEach(fjUpload->{
					fjUpload.setSynStatus(yjhxJddUpload.getSynStatus());
					fjUpload.setSynErrMsg(yjhxJddUpload.getSynErrMsg());
					fjUpload.setSynTime(new Date());
					//返回状态与上一次相同，则累加，否则重新计算
					fjUpload.setSynTimes(yjhxJddUpload.getSynTimes());
					fjUpload.setCreatedBy("guangfo");
					fjUpload.setCreatedDate(new Date());
					fjUpload.setLastModifiedBy("guangfo");
					fjUpload.setLastModifiedDate(new Date());
				});
				itfTblYjhxJddFjUploadService.saveOrUpdateBatch(yjhxJddFjUploadList);
			}
		}
		
		if( null != toGreeUploadnotifylist ) {
			if(synStatus == Constant.SynStatus.SYN.getCode().intValue()) {
				toGreeUploadnotifylist.setSynStatus(synStatus);
			}else {
				if(null !=toGreeUploadnotifylist.getSynTimes() && toGreeUploadnotifylist.getSynTimes() >= 6) {
					toGreeUploadnotifylist.setSynStatus(Constant.SynStatus.FAIL.getCode());
					toGreeUploadnotifylist.setSynErrMsg(msg);
				}else {
					toGreeUploadnotifylist.setSynTimes(null == toGreeUploadnotifylist.getSynTimes() ? 1 : (toGreeUploadnotifylist.getSynTimes()+1));
				}
			}
			toGreeUploadnotifylist.setSynTime(new Date());
			outJiasmToGreeUploadnotifylistService.saveOrUpdate(toGreeUploadnotifylist);
		}
		
		if( null != jdd) {
			if( Constant.SynStatus.SYN.getCode().intValue() == synStatus) {
				//返回成功，反写业务表 部分数据来自于格力总部要反写
				yjhxAppraiseService.saveOrUpdate(jdd);
			}
		}
		}catch(Exception e) {
			log.error((Objects.isNull(e) || Objects.isNull(e.getMessage())) ?"TradeOldForNewLogic.processSave异常" : e.getMessage());
		}
	}
	
	/**
	 * 把请求失败的任务变成待处理任务
	 * @return
	 */
	public Boolean changeJddFailToUnSyn(){
		List<OutJiasmToGreeUploadnotifylist> failList = outJiasmToGreeUploadnotifylistService.lambdaQuery()
				.eq(OutJiasmToGreeUploadnotifylist::getSynStatus, Constant.SynStatus.FAIL.getCode()).list();
		if( null != failList && !failList.isEmpty()) {
			List<Boolean> resultList = new ArrayList<>();
			failList.stream().forEach(fail->{
				fail.setSynStatus(Constant.SynStatus.UN_SYN.getCode());
				fail.setSynTimes(0);
			});
			return outJiasmToGreeUploadnotifylistService.saveOrUpdateBatch(failList);
		}
		return Boolean.FALSE;
	}
	
	
	@Transactional
	public String queryRejectJdd() {
		final String url = webUrl + Constant.GreeWebPath.TBLYJHXJDD_QUERYREJECTJDD;
		try {
			JSONObject response = greeLogic.getPubV3(url, null);
			if( 200 == response.getInteger("status").intValue()) {
				List<ItfTblTradeNewForOldRejectJddDownload> newForOldList = JSONArray
						.parseArray(this.mapper.writeValueAsString(response.get("data")),
						ItfTblTradeNewForOldRejectJddDownload.class);
				if(CollectionUtils.isNotEmpty(newForOldList)) {
					Map<String,List<ItfTblTradeNewForOldRejectJddDownload>> jddsMap= new HashMap<>();
					// 提取同步无批次号的数据
					List<ItfTblTradeNewForOldRejectJddDownload> jdds = itfTblTradeNewForOldRejectJddDownloadService.lambdaQuery()
							.eq(ItfTblTradeNewForOldRejectJddDownload::getFlag,1).list();
					if (CollectionUtils.isNotEmpty(jdds)){
						jddsMap = jdds.stream().collect(Collectors.groupingBy(ItfTblTradeNewForOldRejectJddDownload::getPgguid));
					}
					for (ItfTblTradeNewForOldRejectJddDownload reject: newForOldList){
						reject.setSynReqTime(new Date());
						reject.setSynStatus(Constant.SynStatus.UN_SYN.getCode());
						reject.setSynTimes(1);
						if (StringUtils.isEmpty(reject.getDownloadTaskNo())){
							if (jddsMap.containsKey(reject.getPgguid())){
								reject.setDownloadTaskNo(jddsMap.get(reject.getPgguid()).get(0).getDownloadTaskNo());
							} else {
								reject.setDownloadTaskNo(publicService.getUUID());
								reject.setFlag(1);
							}
						}
					}
					itfTblTradeNewForOldRejectJddDownloadService.saveOrUpdateBatch(newForOldList);
				}else {
					log.info("TradeOldForNewLogic.queryRejectJdd无驳回的签定单数据");
				}
			}else {
				if(response.containsKey("messageCode") && null != response.get("messageCode")) {
					log.error("TradeOldForNewLogic.queryRejectJdd接口异常111: {}", response.getString("messageCode"));
				}else if(response.containsKey("message") && null != response.get("message")) {
					log.error("TradeOldForNewLogic.queryRejectJdd接口异常222: {}", response.getString("message"));
				}
			}
		}catch(Exception e) {
			log.error("TradeOldForNewLogic.queryRejectJdd接口异常333: {}", e.getMessage());
		}
		return "";
    }

    // 修改鉴定单状态为驳回状态+更新同步数据状态
	public String processBusiness() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// 提取待同步的被驳回的以旧换新鉴定单数据
		List<ItfTblTradeNewForOldRejectJddDownload > tradeNewForOldRejectJddDownloadList = itfTblTradeNewForOldRejectJddDownloadService.lambdaQuery()
				.eq(ItfTblTradeNewForOldRejectJddDownload::getSynStatus, Constant.SynStatus.UN_SYN.getCode())
				.orderByAsc(ItfTblTradeNewForOldRejectJddDownload::getSynReqId).list();

		if(CollectionUtils.isNotEmpty(tradeNewForOldRejectJddDownloadList)) {
			try {
				LinkedHashSet<String> pgguids = new LinkedHashSet<>();
				tradeNewForOldRejectJddDownloadList.stream().forEach(reject->{
					pgguids.add(reject.getPgguid());
				});

				List<OrderBase> orderBaseList = orderBaseService.lambdaQuery()
						.in(OrderBase::getPgguid, pgguids).list();
				final Map<String, List<OrderBase>> orderBaseMap = (null == orderBaseList || orderBaseList.isEmpty()) ?
						null :  orderBaseList.stream().collect(Collectors.groupingBy(OrderBase::getPgguid));

				LinkedHashSet<String> orderBaseIds = new LinkedHashSet<>();
				orderBaseList.stream().forEach(OrderBase->{
					orderBaseIds.add(OrderBase.getId());
				});

				// 提取以旧换新鉴定单数据
				List<YjhxAppraise> jddList = new ArrayList<>();
				List<YjhxAppraise> newAddJddList = new ArrayList<>();
				if(!orderBaseIds.isEmpty()) {
					jddList =  yjhxAppraiseService.lambdaQuery()
							.in(YjhxAppraise::getOrderBaseId, orderBaseIds).list();
				}

				final Map<String, List<YjhxAppraise>> jddMap = jddList.isEmpty() ?
						null : jddList.stream().collect(Collectors.groupingBy(YjhxAppraise::getOrderBaseId));

				for (ItfTblTradeNewForOldRejectJddDownload item:tradeNewForOldRejectJddDownloadList){
					if( null != orderBaseMap && orderBaseMap.containsKey(item.getPgguid()) &&
							null != orderBaseMap.get(item.getPgguid()) &&
							!orderBaseMap.get(item.getPgguid()).isEmpty()) {
						// 提取工单
						OrderBase orderBase = orderBaseMap.get(item.getPgguid()).get(0);
						if( null != jddMap && jddMap.containsKey(orderBase.getId())
								&& null != jddMap.get(orderBase.getId())
								&& !jddMap.get(orderBase.getId()) .isEmpty()) {
							// 提取鉴定单
							YjhxAppraise jdd = jddMap.get(orderBase.getId()) .get(0);
							// 查看最后更新日期
							if( null != jdd.getLastModifiedDate()) {
								//广佛系统最后更新时间在总部下载的时间前才可以更新
								if(jdd.getLastModifiedDate().before(item.getLastModifiedDate())) {
									// 设状态为驳回状态
									jdd.setStat("3");
									jdd.setLastModifiedDate(item.getLastModifiedDate());
									newAddJddList.add(jdd);
									item.setSynStatus(Constant.SynStatus.SYN.getCode());
									item .setSynReqTime(new Date());
								} else {
									log.info("TradeOldForNewLogic.queryRejectJdd: 广佛系统最后更新时间晚于总部下载的时间，不更驳回状态, 最近更新时间: 广佛：{},总部: {} ",
											sdf.format(jdd.getLastModifiedDate()), sdf.format(item.getLastModifiedDate()));
									item.setSynStatus(Constant.SynStatus.FAIL.getCode());
									item .setSynReqTime(new Date());
									item.setSynErrMsg("TradeOldForNewLogic.queryRejectJdd: 广佛系统最后更新时间比总部下载的时间后，不更驳回状态, 最近更新时间: 广佛："+
											sdf.format(jdd.getLastModifiedDate())+",总部:  "+
											sdf.format(item.getLastModifiedDate()));
								}
							}else {
								item.setSynStatus(Constant.SynStatus.FAIL.getCode());
								item .setSynReqTime(new Date());
								item.setSynErrMsg("jdd.getLastModifiedDate为空， pgguid="+ jdd.getPgguid());
							}

						}else {
							item.setSynStatus(Constant.SynStatus.FAIL.getCode());
							item .setSynReqTime(new Date());
							item.setSynErrMsg("YjhxJdd为空， workerOrderNo="+ orderBase.getId());
						}
					}else {
						item.setSynStatus(Constant.SynStatus.FAIL.getCode());
						item .setSynReqTime(new Date());
						item.setSynErrMsg("OrderInstall为空， pgguid="+ item.getPgguid());
					}
				}

				if(newAddJddList.size()>0) {
					yjhxAppraiseService.saveOrUpdateBatch(newAddJddList);
					newAddJddList.clear();
				}

				itfTblTradeNewForOldRejectJddDownloadService.saveOrUpdateBatch(tradeNewForOldRejectJddDownloadList);
			}catch(Exception e) {
				log.error("TradeOldForNewLogic.processBusiness处理异常: {}", e.getMessage());
			}
		}
		return "";
	}

	public void stockBarcodeInfoDonwlodToUpload() {
		// 提取待入库条码上传记录表数据
		List<ItfTblTradeNewForOldStockInfoUploadTask> tradeNewForOldStockInfoUploadTaskList = itfTblTradeNewForOldStockInfoUploadTaskService.lambdaQuery()
				.eq(ItfTblTradeNewForOldStockInfoUploadTask::getSynStatus, Constant.SynStatus.UN_SYN.getCode())
				.orderByAsc(ItfTblTradeNewForOldStockInfoUploadTask::getSynReqId).list();
		//测试，用状态为77 无数据不处理
		if( Collections.isEmpty(tradeNewForOldStockInfoUploadTaskList)) {
			return ;
		}
		List<ItfTblRecycleStockBarcodeInfoUpload> tradeNewForOldStockBarcodeInfoUploadList = new ArrayList<>();
		for(ItfTblTradeNewForOldStockInfoUploadTask item : tradeNewForOldStockInfoUploadTaskList) {
			// 相同 pgguid 上一条未同步或同步失败本记录不再同步
			if (checkUpload(item)){
				continue;
			}

			//根据pgguid获取以旧换新鉴定单数据 无鉴定数据不处理
			final List<YjhxAppraise> yjhxJddList = yjhxAppraiseService.lambdaQuery()
					.eq(YjhxAppraise::getPgguid, item.getPgguid()).list();
			if(Collections.isEmpty(yjhxJddList)) {
				item.setSynStatus(Constant.SynStatus.FAIL.getCode());
				item.setSynErrMsg("没有鉴定单数据, pgguid="+item.getPgguid());
				item.setSynTime(new Date());
				continue;
			}

			//一个pgguid只对应一条YjhxJdd数据
			YjhxAppraise yjhxJdd = yjhxJddList.get(0);
			OrderBase order = orderBaseService.lambdaQuery()
					.eq(OrderBase::getPgguid, yjhxJdd.getPgguid())
					.last("limit 1")
					.one();
			if(Objects.isNull(order)) {
				item.setSynStatus(Constant.SynStatus.FAIL.getCode());
				item.setSynErrMsg("没有工单数据, pgguid="+item.getPgguid());
				item.setSynTime(new Date());
				continue;
			}

			//查询old_for_new_product 旧机信息表，获取大类
			final List<OldForNewProduct> tradeNewForOldList = oldForNewProductService.lambdaQuery()
					.eq(OldForNewProduct::getOrderBaseId, yjhxJdd.getOrderBaseId()).list();
			OldForNewProduct product = (Collections.isEmpty(tradeNewForOldList)) ? null : tradeNewForOldList.get(0);
			//内外机条码，以#分割
			if(StringUtils.isEmpty(yjhxJdd.getTempBarcode())) {
				item.setSynStatus(Constant.SynStatus.FAIL.getCode());
				item.setSynErrMsg("没有内外机条码信息, pgguid="+item.getPgguid());
				item.setSynTime(new Date());
				continue;
			}

			WebsitSH websitSH = publicService.ptshwdToshshwd(yjhxJdd.getWebsitId(), order.getMainId());
			WorderInfo worderInfo = publicService.getWorkerInfo(order.getWorkerId(),
					websitSH.getWdId(), order.getGroupCompanyId());

			String taskNo = publicService.getUUID();
			// 生成内机条码上传数据
			if(StringUtils.isNotEmpty(yjhxJdd.getNjtm())) {
				getItfTblRecycleStockBarcodeInfoUploadNjtm(tradeNewForOldStockBarcodeInfoUploadList, yjhxJdd, order, product, websitSH, worderInfo, taskNo);
			}
			// 生成外机条码上传数据
			if(StringUtils.isNotEmpty(yjhxJdd.getWjtm())) {
				getItfTblRecycleStockBarcodeInfoUploadWjtm(tradeNewForOldStockBarcodeInfoUploadList, yjhxJdd, order, product, websitSH, worderInfo, taskNo);
			}

			item.setSynStatus(Constant.SynStatus.SYN.getCode());
			item.setSynTime(new Date());
		}

		// 修改同步待入库条码上传记录表状态
		itfTblTradeNewForOldStockInfoUploadTaskService.saveOrUpdateBatch(tradeNewForOldStockInfoUploadTaskList);
		// 生成条码信息上传表数据
		if(!Collections.isEmpty(tradeNewForOldStockBarcodeInfoUploadList)) {
			barcodeInfoUploadService.saveOrUpdateBatch(tradeNewForOldStockBarcodeInfoUploadList);
		}
	}

	private boolean checkUpload(ItfTblTradeNewForOldStockInfoUploadTask item) {
		//提取小于当前id的数据   含有上一条失败，本条不上传
		List<ItfTblTradeNewForOldStockInfoUploadTask> lastTaskList = itfTblTradeNewForOldStockInfoUploadTaskService.lambdaQuery().
				in(ItfTblTradeNewForOldStockInfoUploadTask::getSynStatus,
						new Integer[] { Constant.SynStatus.FAIL.getCode(), Constant.SynStatus.UN_SYN.getCode()}).
				lt(ItfTblTradeNewForOldStockInfoUploadTask::getSynReqId, item.getSynReqId()).
				eq(ItfTblTradeNewForOldStockInfoUploadTask::getPgguid, item.getPgguid()).
				orderByDesc(ItfTblTradeNewForOldStockInfoUploadTask::getSynReqId).list();
		if(!Collections.isEmpty(lastTaskList)) {
			ItfTblTradeNewForOldStockInfoUploadTask lastTask = lastTaskList.get(0);
			// 若上一条未同步，则本条跳过
			if( Constant.SynStatus.UN_SYN.getCode().intValue() == lastTask.getSynStatus() ) {
				return true;
			}else {
				// 若上一条失败，则本条也不允许上传
				item.setSynStatus(Constant.SynStatus.FAIL.getCode());
				item.setSynErrMsg("上一条数据没上传成功，本条数据不上传, pguuid="+ item.getPgguid());
				item.setSynTime(new Date());
				return true;
			}
		}
		return false;
	}

	private void getItfTblRecycleStockBarcodeInfoUploadWjtm(List<ItfTblRecycleStockBarcodeInfoUpload> tradeNewForOldStockBarcodeInfoUploadList,
															YjhxAppraise yjhxJdd, OrderBase order, OldForNewProduct product, WebsitSH websitSH, WorderInfo worderInfo, String taskNo) {
		ItfTblRecycleStockBarcodeInfoUpload barcodeInfoUpload = new ItfTblRecycleStockBarcodeInfoUpload();
		barcodeInfoUpload.setPgguid(yjhxJdd.getPgguid());
		barcodeInfoUpload.setUploadTaskNo(taskNo);
		barcodeInfoUpload.setJqtm(yjhxJdd.getWjtm());
		barcodeInfoUpload.setTmlx(1);
		barcodeInfoUpload.setSpid(Integer.valueOf(product.getMainId()));
		//大类名字，现在暂时只有空调，spid=101
		barcodeInfoUpload.setSpmc( (Objects.isNull(product) || Objects.isNull(product.getMainId()) ) ? null : (product.getMainId().equals("101") ? "空调" : ""));
		barcodeInfoUpload.setPinp(StringUtils.isEmpty(yjhxJdd.getRealBrand()) ?   yjhxJdd.getOldMachineBrand() : yjhxJdd.getRealBrand());
		barcodeInfoUpload.setJqlx( StringUtils.isEmpty(yjhxJdd.getRealType()) ? yjhxJdd.getOldMachineType() : yjhxJdd.getRealType());
		//匹数要传数字型，1点5匹，就填1.50 ，用数字填
		barcodeInfoUpload.setPshu( new BigDecimal(yjhxJdd.getCpps() ).floatValue() );
		barcodeInfoUpload.setWdno(websitSH.getWdId());
		barcodeInfoUpload.setDqcfid(websitSH.getWdId());
		barcodeInfoUpload.setDqcfmc(websitSH.getWdmc());
		barcodeInfoUpload.setYddh(worderInfo.getMobile());
		//工单类型:1:以旧换新;2:回收工单
		barcodeInfoUpload.setSrclx(1);
		barcodeInfoUpload.setHssj(new Date());
		barcodeInfoUpload.setHsfwwdno(websitSH.getWdId());
		barcodeInfoUpload.setHsfwwdmc(websitSH.getWdmc());
		barcodeInfoUpload.setSrcno(order.getSaleNo());
		barcodeInfoUpload.setSrcId(yjhxJdd.getPgguid());
		barcodeInfoUpload.setPgwcmxid(yjhxJdd.getHxjddid());
		barcodeInfoUpload.setState(0);
		barcodeInfoUpload.setCreatedBy(yjhxJdd.getCreatedBy());
		barcodeInfoUpload.setCreatedDate(yjhxJdd.getCreatedDate());
		barcodeInfoUpload.setLastModifiedBy(yjhxJdd.getLastModifiedBy());
		barcodeInfoUpload.setLastModifiedDate(yjhxJdd.getLastModifiedDate());
		barcodeInfoUpload.setSrcxsdh(order.getSaleNo());
		tradeNewForOldStockBarcodeInfoUploadList.add(barcodeInfoUpload);
	}

	private void getItfTblRecycleStockBarcodeInfoUploadNjtm(List<ItfTblRecycleStockBarcodeInfoUpload> tradeNewForOldStockBarcodeInfoUploadList, YjhxAppraise yjhxJdd,
															OrderBase order, OldForNewProduct product, WebsitSH websitSH, WorderInfo worderInfo, String taskNo) {
		ItfTblRecycleStockBarcodeInfoUpload barcodeInfoUpload = new ItfTblRecycleStockBarcodeInfoUpload();
		barcodeInfoUpload.setPgguid(yjhxJdd.getPgguid());
		barcodeInfoUpload.setUploadTaskNo(taskNo);
		barcodeInfoUpload.setJqtm(yjhxJdd.getNjtm());
		barcodeInfoUpload.setTmlx(0);
		barcodeInfoUpload.setSpid(Objects.isNull(product) ? null : Integer.valueOf(product.getMainId()));
		//大类名字，现在暂时只有空调，spid=101
		barcodeInfoUpload.setSpmc( (Objects.isNull(product) || Objects.isNull(product.getMainId()) ) ? null : (product.getMainId().equals("101") ? "空调" : ""));
		barcodeInfoUpload.setPinp(StringUtils.isEmpty(yjhxJdd.getRealBrand()) ?   yjhxJdd.getOldMachineBrand() : yjhxJdd.getRealBrand());
		barcodeInfoUpload.setJqlx( StringUtils.isEmpty(yjhxJdd.getRealType()) ? yjhxJdd.getOldMachineType() : yjhxJdd.getRealType());
		//匹数要传数字型，1点5匹，就填1.50 ，用数字填
		barcodeInfoUpload.setPshu( new BigDecimal(yjhxJdd.getCpps() ).floatValue() );
		barcodeInfoUpload.setWdno(websitSH.getWdId());
		barcodeInfoUpload.setDqcfid(websitSH.getWdId());
		barcodeInfoUpload.setDqcfmc(websitSH.getWdmc());
		barcodeInfoUpload.setYddh(worderInfo.getMobile());
		//工单类型:1:以旧换新;2:回收工单
		barcodeInfoUpload.setSrclx(1);
		barcodeInfoUpload.setHssj(new Date());
		barcodeInfoUpload.setHsfwwdno(websitSH.getWdId());
		barcodeInfoUpload.setHsfwwdmc(websitSH.getWdmc());
		barcodeInfoUpload.setSrcno(order.getSaleNo());
		barcodeInfoUpload.setSrcId(yjhxJdd.getPgguid());
		barcodeInfoUpload.setPgwcmxid(yjhxJdd.getHxjddid());
		barcodeInfoUpload.setState(0);
		barcodeInfoUpload.setCreatedBy(yjhxJdd.getCreatedBy());
		barcodeInfoUpload.setCreatedDate(yjhxJdd.getCreatedDate());
		barcodeInfoUpload.setLastModifiedBy(yjhxJdd.getLastModifiedBy());
		barcodeInfoUpload.setLastModifiedDate(yjhxJdd.getLastModifiedDate());
		barcodeInfoUpload.setSrcxsdh(order.getSaleNo());
		tradeNewForOldStockBarcodeInfoUploadList.add(barcodeInfoUpload);
	}

	/**
	 * 上传总部条码（需要上传了barcodeInfo主表数据，上传的stockin和stockout才有有效）
	 */
	public void stockBarcodeInfoUpload() {
		// 查看该网点数据是否需要回传，不需要回传时直接修改同步状态将不再回传
		List<ItfTblRecycleStockBarcodeInfoUpload> records = barcodeInfoUploadService.lambdaQuery()
				.eq(ItfTblRecycleStockBarcodeInfoUpload::getSynStatus, Constant.SynStatus.UN_SYN.getCode()).list();
		if(Collections.isEmpty(records)) {
			return;
		}
		for (ItfTblRecycleStockBarcodeInfoUpload item:records){
			OrderBase order = orderBaseService.lambdaQuery()
					.eq(OrderBase::getPgguid, item.getPgguid())
					.last("limit 1")
					.one();
			// 工单号，名表，记录ID
			publicService.checkWebsitSyncFlag(order.getId(),"itf_tbl_recycle_stock_barcode_info_upload",item.getSynReqId());
		}



		// 条码信息上传表中提取待同步的数据
		final List<ItfTblRecycleStockBarcodeInfoUpload> barcodeInfoUploads = barcodeInfoUploadService.lambdaQuery()
				.eq(ItfTblRecycleStockBarcodeInfoUpload::getSynStatus, Constant.SynStatus.UN_SYN.getCode()).list();
		// 无数据不处理
		if(Collections.isEmpty(barcodeInfoUploads)) {
			return;
		}

		List<ItfTblTradeNewForOldStockInfoUploadTask> stockInfoUploadTaskList = new ArrayList<>();
		// 按uploadTaskNo分组 内外机条码各一条记录
		final Map<String, List<ItfTblRecycleStockBarcodeInfoUpload>> barcodeInfoUploadsMap = Collections.isEmpty(barcodeInfoUploads) ? null :barcodeInfoUploads.stream().collect(Collectors.groupingBy(ItfTblRecycleStockBarcodeInfoUpload::getUploadTaskNo));
		// 取键值对的每个entry
		for(Map.Entry<String,List<ItfTblRecycleStockBarcodeInfoUpload>> entry : barcodeInfoUploadsMap.entrySet()){
			List<ItfTblRecycleStockBarcodeInfoUpload> barcodeInfoList = entry.getValue();
			String pgguid = barcodeInfoList.get(0).getPgguid();
			final String apiPath = Constant.GreeApiPath.TRADE_NEW_FOR_OLD_STOCK_STOCKINFOS;
			Integer synStatus = -1;
			String errMsg = "";
			List<TradeNewForOldStockBarcodeInfoUploadBean> barcodeInfoBeanList = new ArrayList<>();
			List<Map> infos = new ArrayList<>() ;




			// 组装参数 infos
			try {
				barcodeInfoBeanList = this.mapper.readValue(this.mapper.writeValueAsString(barcodeInfoList), new TypeReference<List<TradeNewForOldStockBarcodeInfoUploadBean>>() {});
				infos = this.mapper.readValue(this.mapper.writeValueAsString(barcodeInfoBeanList), new TypeReference<List<Map>>() {});
			} catch (JsonMappingException e1) {
				synStatus = Constant.SynStatus.FAIL.getCode();
				for( ItfTblRecycleStockBarcodeInfoUpload tradeNewForOldStockBarcodeInfoUpload : barcodeInfoUploads) {
					tradeNewForOldStockBarcodeInfoUpload.setSynStatus(GreeSynStatusEnum.FAIL.getCode());
					tradeNewForOldStockBarcodeInfoUpload.setSynErrMsg(e1.getMessage().length() > 100 ? e1.getMessage().substring(0, 99) : e1.getMessage());
					errMsg = tradeNewForOldStockBarcodeInfoUpload.getSynErrMsg();
					tradeNewForOldStockBarcodeInfoUpload.setSynTime(new Date());
					tradeNewForOldStockBarcodeInfoUpload.setSynTimes( Objects.isNull(tradeNewForOldStockBarcodeInfoUpload.getSynTimes()) ? 1 : tradeNewForOldStockBarcodeInfoUpload.getSynTimes() + 1 );
				}
				continue;
			} catch (JsonProcessingException e1) {
				synStatus = Constant.SynStatus.FAIL.getCode();
				for( ItfTblRecycleStockBarcodeInfoUpload tradeNewForOldStockBarcodeInfoUpload : barcodeInfoUploads) {
					tradeNewForOldStockBarcodeInfoUpload.setSynStatus(synStatus);
					tradeNewForOldStockBarcodeInfoUpload.setSynErrMsg(e1.getMessage().length() > 100 ? e1.getMessage().substring(0, 99) : e1.getMessage());
					errMsg = tradeNewForOldStockBarcodeInfoUpload.getSynErrMsg();
					tradeNewForOldStockBarcodeInfoUpload.setSynTime(new Date());
					tradeNewForOldStockBarcodeInfoUpload.setSynTimes( Objects.isNull(tradeNewForOldStockBarcodeInfoUpload.getSynTimes()) ? 1 : tradeNewForOldStockBarcodeInfoUpload.getSynTimes() + 1 );
				}
				continue;
			}
			Map<String, Object> param = new HashMap<>();
			param.put("taskNo", entry.getKey());
			param.put("infos", infos);
			// 条码数据同步
			try {
				GreeResponseHelper response = greeLogic.greePost(apiPath, param, 1);
				if(200 == response.getStatus()) {
					synStatus = Constant.SynStatus.SYN.getCode();
					for( ItfTblRecycleStockBarcodeInfoUpload tradeNewForOldStockBarcodeInfoUpload : barcodeInfoUploads) {
						tradeNewForOldStockBarcodeInfoUpload.setSynStatus(Constant.SynStatus.SYN.getCode());
						tradeNewForOldStockBarcodeInfoUpload.setSynTime(new Date());
						tradeNewForOldStockBarcodeInfoUpload.setSynTimes( Objects.isNull(tradeNewForOldStockBarcodeInfoUpload.getSynTimes()) ? 1 : tradeNewForOldStockBarcodeInfoUpload.getSynTimes() + 1 );
					}
				}else {
					synStatus = Constant.SynStatus.FAIL.getCode();
					for( ItfTblRecycleStockBarcodeInfoUpload tradeNewForOldStockBarcodeInfoUpload : barcodeInfoUploads) {
						tradeNewForOldStockBarcodeInfoUpload.setSynStatus(synStatus);
						tradeNewForOldStockBarcodeInfoUpload.setSynErrMsg(response.getMsg());
						errMsg = tradeNewForOldStockBarcodeInfoUpload.getSynErrMsg();
						tradeNewForOldStockBarcodeInfoUpload.setSynTime(new Date());
						tradeNewForOldStockBarcodeInfoUpload.setSynTimes( Objects.isNull(tradeNewForOldStockBarcodeInfoUpload.getSynTimes()) ? 1 : tradeNewForOldStockBarcodeInfoUpload.getSynTimes() + 1 );
						pgguid = tradeNewForOldStockBarcodeInfoUpload.getPgguid();
					}
				}
			}catch(Exception e) {
				e.printStackTrace();
				synStatus = Constant.SynStatus.FAIL.getCode();
				for( ItfTblRecycleStockBarcodeInfoUpload tradeNewForOldStockBarcodeInfoUpload : barcodeInfoUploads) {
					tradeNewForOldStockBarcodeInfoUpload.setSynStatus(GreeSynStatusEnum.FAIL.getCode());
					tradeNewForOldStockBarcodeInfoUpload.setSynErrMsg(e.getMessage().length() > 100 ? e.getMessage().substring(0, 99) : e.getMessage());
					errMsg = tradeNewForOldStockBarcodeInfoUpload.getSynErrMsg();
					tradeNewForOldStockBarcodeInfoUpload.setSynTime(new Date());
					tradeNewForOldStockBarcodeInfoUpload.setSynTimes( Objects.isNull(tradeNewForOldStockBarcodeInfoUpload.getSynTimes()) ? 1 : tradeNewForOldStockBarcodeInfoUpload.getSynTimes() + 1 );
				}
			}
			// 上传条码信息任务列表提取状态为0的数据理论上是取不到的，因为生成上传条码表时已更新了状态为1
			List<ItfTblTradeNewForOldStockInfoUploadTask> tradeNewForOldStockInfoUploadTaskList = itfTblTradeNewForOldStockInfoUploadTaskService.lambdaQuery()
					.eq(ItfTblTradeNewForOldStockInfoUploadTask::getPgguid, pgguid)
					.eq(ItfTblTradeNewForOldStockInfoUploadTask::getSynStatus, Constant.SynStatus.UN_SYN.getCode())
					.orderByAsc(ItfTblTradeNewForOldStockInfoUploadTask::getSynReqId).list();
			if(Collections.isEmpty(tradeNewForOldStockInfoUploadTaskList) ) {
				continue;
			}
			//按synReqId顺序更新
			ItfTblTradeNewForOldStockInfoUploadTask tradeNewForOldStockInfoUploadTask = tradeNewForOldStockInfoUploadTaskList.get(0);
			if( synStatus == Constant.SynStatus.SYN.getCode()) {
				tradeNewForOldStockInfoUploadTask.setSynStatus(synStatus);
				tradeNewForOldStockInfoUploadTask.setSynTime(new Date());
			}else {
				if( (Objects.isNull(tradeNewForOldStockInfoUploadTask.getSynTimes()) ? 0 : tradeNewForOldStockInfoUploadTask.getSynTimes()) >= 6 ) {
					tradeNewForOldStockInfoUploadTask.setSynStatus(synStatus);
					tradeNewForOldStockInfoUploadTask.setSynErrMsg(errMsg);
					tradeNewForOldStockInfoUploadTask.setSynTime(new Date());
				}else {
					//请求失败，累加请求次数
					tradeNewForOldStockInfoUploadTask.setSynTimes((Objects.isNull(tradeNewForOldStockInfoUploadTask.getSynTimes()) ? 0 : tradeNewForOldStockInfoUploadTask.getSynTimes()) + 1);
				}
			}
			stockInfoUploadTaskList.add(tradeNewForOldStockInfoUploadTask);
		}
		// 更新以旧换新条码信息上传任务表同步状态
		if(!Collections.isEmpty(stockInfoUploadTaskList)) {
			itfTblTradeNewForOldStockInfoUploadTaskService.saveOrUpdateBatch(stockInfoUploadTaskList);
		}
		// 更新条码信息上传表同步状态
		if(!Collections.isEmpty(barcodeInfoUploads)) {
			barcodeInfoUploadService.saveOrUpdateBatch(barcodeInfoUploads);
		}
	}

}
