package com.hzya.frame.grpU8.nxproof.glPzml.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.basedao.service.impl.BaseService;
import com.hzya.frame.grpU8.nxproof.gbizbsyrec.dao.IGbiZbsyrecDao;
import com.hzya.frame.grpU8.nxproof.gbizbsyrec.entity.GbiZbsyrecEntity;
import com.hzya.frame.grpU8.nxproof.gbizbxmb.dao.IGbiZbxmbDao;
import com.hzya.frame.grpU8.nxproof.gbizbxmb.entity.GbiZbxmbEntity;
import com.hzya.frame.grpU8.nxproof.glPzml.dao.ISenderGlPzmlDao;
import com.hzya.frame.grpU8.nxproof.glPzml.entity.SenderGlPzmlEntity;
import com.hzya.frame.grpU8.nxproof.glPzml.service.ISenderGlPzmlService;
import com.hzya.frame.grpU8.nxproof.glPznr.dao.ISenderGlPznrDao;
import com.hzya.frame.grpU8.nxproof.glPznr.entity.SenderGlPznrEntity;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.apache.commons.collections.CollectionUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

import static org.aspectj.runtime.internal.Conversions.doubleValue;

/**
 * (GlPzml)表服务实现类
 *
 * @author makejava
 * @since 2024-06-20 10:02:06
 */
@Service(value = "SenderGlPzmlServiceImpl")
public class SenderGlPzmlServiceImpl extends BaseService<SenderGlPzmlEntity, String> implements ISenderGlPzmlService {

	private static String URLTest="http://39.106.158.149/";//测试环境
	private static String URL="http://192.168.42.22/";//正式环境

	private ISenderGlPzmlDao senderGlPzmlDao;

	@Autowired
	private IGbiZbxmbDao  gbiZbxmbDao;

	@Autowired
	public void setSenderGlPzmlDao(ISenderGlPzmlDao dao) {
		this.senderGlPzmlDao = dao;
		this.dao = dao;
	}

	@Autowired
	private ISenderGlPznrDao senderGlPznrDao;


	//凭证同步
	@Override
	public void glPzmlSynchronization(JSONObject json) {
		SenderGlPzmlEntity senderGlPzmlEntity = json.toJavaObject(SenderGlPzmlEntity.class);
		String result=null;
		try {
			//如果没有传入年度，则查询当年得，避免数据查询太大
			if (senderGlPzmlEntity.getKjqj() == null) {
				senderGlPzmlEntity.setKjqj(DateUtil.format(new Date(),"yyyy"));
				//senderGlPzmlEntity.setKjqj("202105");
			}
			JSONObject jsonObjectStr=new JSONObject();
			/*try {
				//同步南浔区人民医院001凭证信息
				senderGlPzmlEntity.setZth("001");
				senderGlPzmlEntity.setGsdm("0101010101");
				logger.info("===========开始查询南浔区人民医院凭证目录信息=============");
				jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
				result=sendPzmlToHealthBureau(jsonObjectStr);
				logger.info("南浔区人民医院GRPU8凭证同步结果为:{}",result);
			}catch (Exception e){
				logger.info("南浔区人民医院GRPU8凭证同步失败:{}",e.getMessage());
				e.printStackTrace();
			}*/
			try {
				//同步南浔区练市人民医院003凭证信息
				senderGlPzmlEntity.setZth("003");
				senderGlPzmlEntity.setGsdm("0101010103");
				logger.info("===========开始查询南浔区练市人民医院凭证目录信息=============");
				jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
				result=sendPzmlToHealthBureau(jsonObjectStr);
				logger.info("南浔区练市人民医院GRPU8凭证同步结果为:{}",result);
			}catch (Exception e){
				logger.info("南浔区练市人民医院GRPU8凭证同步失败:{}",e.getMessage());
				e.printStackTrace();
			}
			/*try {
				//同步练市镇中心卫生院005凭证信息
				senderGlPzmlEntity.setZth("005");
				senderGlPzmlEntity.setGsdm("0101010202");
				logger.info("===========开始查询南浔区练市镇中心卫生院凭证目录信息=============");
				jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
				result=sendPzmlToHealthBureau(jsonObjectStr);
				logger.info("南浔区练市镇中心卫生院GRPU8凭证同步结果为:{}",result);
			}catch (Exception e){
				logger.info("南浔区练市镇中心卫生院GRPU8凭证同步失败:{}",e.getMessage());
				e.printStackTrace();
			}*/
			/*try {
				//同步善琏镇卫生院007凭证信息
				senderGlPzmlEntity.setZth("007");
				senderGlPzmlEntity.setGsdm("0101010204");
				logger.info("===========开始查询南浔区善琏镇卫生院凭证目录信息=============");
				jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
				result=sendPzmlToHealthBureau(jsonObjectStr);
				logger.info("南浔区善琏镇卫生院GRPU8凭证同步结果为:{}",result);
			}catch (Exception e){
				logger.info("南浔区善琏镇卫生院GRPU8凭证同步失败:{}",e.getMessage());
				e.printStackTrace();
			}*/
			/*//同步双林镇中心卫生院004凭证信息
			senderGlPzmlEntity.setZth("004");
			senderGlPzmlEntity.setGsdm("0101010201");
			jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
			result=sendPzmlToHealthBureau(jsonObjectStr);
			logger.info("双林镇中心卫生院GRPU8凭证同步结果为:{}",result);
			//同步菱湖镇中心卫生院009凭证信息
			senderGlPzmlEntity.setZth("009");
			senderGlPzmlEntity.setGsdm("0101020201");
			jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
			result=sendPzmlToHealthBureau(jsonObjectStr);
			logger.info("菱湖镇中心卫生院GRPU8凭证同步结果为:{}",result);
			//同步和孚镇卫生院010凭证信息
			senderGlPzmlEntity.setZth("010");
			senderGlPzmlEntity.setGsdm("0101020202");
			jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
			result=sendPzmlToHealthBureau(jsonObjectStr);
			logger.info("和孚镇卫生院GRPU8凭证同步结果为:{}",result);
			//同步千金镇卫生院011凭证信息
			senderGlPzmlEntity.setZth("011");
			senderGlPzmlEntity.setGsdm("0101020203");
			jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
			result=sendPzmlToHealthBureau(jsonObjectStr);
			logger.info("千金镇卫生院GRPU8凭证同步结果为:{}",result);
			//同步石崇镇卫生院012凭证信息
			senderGlPzmlEntity.setZth("012");
			senderGlPzmlEntity.setGsdm("0101020204");
			jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
			result=sendPzmlToHealthBureau(jsonObjectStr);
			logger.info("石崇镇卫生院GRPU8凭证同步结果为:{}");
			//同步南浔镇中心卫生院014凭证信息
			senderGlPzmlEntity.setZth("014");
			senderGlPzmlEntity.setGsdm("010202");
			jsonObjectStr.put("jsonStr",senderGlPzmlEntity);
			result=sendPzmlToHealthBureau(jsonObjectStr);
			logger.info("南浔镇中心卫生院GRPU8凭证同步结果为:{}",result);*/
		} catch (Exception e) {
			logger.info("GRPU8凭证同步失败:{}", e.getMessage());
			e.printStackTrace();
		}
	}

   private String sendPzmlToHealthBureau(JSONObject jsonObjectStr){
		JsonResultEntity jsonResultEntity = queryEntityPage(jsonObjectStr);
		if (jsonResultEntity.getAttribute() == null) {
			logger.info("GRPU8没有需要同步得凭证目录信息信息");
			return "GRPU8没有需要同步的凭证目录信息";
		}
		JSONArray jsonArray = (JSONArray) JSON.toJSON(jsonResultEntity.getAttribute());
	   if (CollectionUtils.isEmpty(jsonArray)) {
			logger.info("GRPU8没有需要同步得凭证目录信息信息");
			return "GRPU8没有需要同步的凭证目录信息";
		} else {
			for (Object o : jsonArray) {
				JSONObject jsonObjectPz = (JSONObject) JSON.toJSON(o);
				//获取凭证目录信息
				JSONObject jsonObjectPzml = jsonObjectPz.getJSONObject("gl_pzml");
				JSONArray jsonArrayPznr = jsonObjectPz.getJSONArray("gl_pznr");
				SenderGlPzmlEntity receiverGlPzmlEntity = new SenderGlPzmlEntity();
				receiverGlPzmlEntity.setIdpzh(jsonObjectPzml.getString("idpzh"));
				receiverGlPzmlEntity.setZth(jsonObjectPzml.getString("zth"));
				JSONObject jsonObjectReceiver = new JSONObject();
				jsonObjectReceiver.put("jsonStr", receiverGlPzmlEntity);
				//根据发送方的idpzh查询接收方中是否存在数据
				JsonResultEntity jsonResultEntityReceiver = queryEntityPageHealthBureau(jsonObjectReceiver);
				JsonResultEntity jsonResultEntityRec=null;
				//如果从接收方查询出的凭证没有，则新增，如果有，则更新凭证目录，之后再比较明细，如果接收方明细不存在，则新增明细，否则更新明细
				if (jsonResultEntityReceiver.getAttribute() == null && jsonResultEntityReceiver.isFlag()) {
					JSONObject jsonReceiverSave = new JSONObject();
					jsonReceiverSave.put("main", jsonObjectPzml);
					jsonReceiverSave.put("details", jsonArrayPznr);
					jsonReceiverSave.put("kjqj", jsonObjectPzml.getString("kjqj"));
					jsonReceiverSave.put("gsdm", jsonObjectPzml.getString("gsdm"));
					jsonReceiverSave.put("zth", jsonObjectPzml.getString("zth"));
					jsonReceiverSave.put("pzh", jsonObjectPzml.getString("pzh"));
					JSONObject jsonObjectPznrStr = new JSONObject();
					jsonObjectPznrStr.put("jsonStr", jsonReceiverSave);
					jsonResultEntityRec= saveEntityHealthBureau(jsonObjectPznrStr);
					if(jsonResultEntityRec.isFlag()){
						JSONObject json = (JSONObject) JSONObject.toJSON(jsonResultEntityRec.getAttribute());
						logger.info("账套号:{}的GROU8得凭证同步保存卫生局的返回结果为:{}", jsonObjectPzml.getString("zth"),json.toJSONString());
					}
				  /* if(jsonResultEntityReceiverSave.getStatus().equals("200")&&jsonResultEntityReceiverSave.getAttribute()!=null){
					   //保存日志
					   saveEntity(jsonObjectPznrStr);
				   }*/
				} else {
					JSONArray jsonArrayResult = (JSONArray) JSON.toJSON(jsonResultEntityReceiver.getAttribute());
					//有值 将发送方的数据更新到接收方 更新凭证目录，更新凭证内容
					for (Object object : jsonArrayResult) {
						JSONObject jsonObjectReceiverPz = (JSONObject) JSON.toJSON(object);
						//获取凭证目录信息
						JSONObject jsonObjectReceiverPzml = jsonObjectReceiverPz.getJSONObject("main");
						//JSONArray jsonArrayReceiverPznr = jsonObjectReceiverPz.getJSONArray("details");
						if (jsonObjectPzml.getString("idpzh").equals(jsonObjectReceiverPzml.getString("idpzh"))) {
							JSONObject jsonReceiverUpdate = new JSONObject();
							jsonReceiverUpdate.put("main", jsonObjectPzml);
							jsonReceiverUpdate.put("details", jsonArrayPznr);
							jsonReceiverUpdate.put("kjqj", jsonObjectPzml.getString("kjqj"));
							jsonReceiverUpdate.put("gsdm", jsonObjectPzml.getString("gsdm"));
							jsonReceiverUpdate.put("zth", jsonObjectPzml.getString("zth"));
							jsonReceiverUpdate.put("pzh", jsonObjectPzml.getString("pzh"));
							JSONObject jsonObjectPznrStr = new JSONObject();
							jsonObjectPznrStr.put("jsonStr", jsonReceiverUpdate);
							jsonResultEntityRec=updateEntityHealthBureau(jsonObjectPznrStr);
							if (jsonResultEntityRec.isFlag()){
								JSONObject json = (JSONObject) JSONObject.toJSON(jsonResultEntityRec.getAttribute());
								logger.info("账套号:{}的GROU8得凭证同步更新卫生局的返回结果为:{}", jsonObjectPzml.getString("zth"),json.toJSONString());
							}
						   /* if(jsonResultEntityReceiverUpdate.getStatus().equals("200")&&jsonResultEntityReceiverUpdate.getAttribute()!=null){
							   //更新日志
							   updateEntity(jsonObjectPznrStr);
						   }*/
						}
					}
				}
			}
			return "同步GROU8凭证成功";
		}
   }


	//查询凭证
	@Override
	public JsonResultEntity queryEntityPage(JSONObject json) {
		JSONObject jsonObject = json.getJSONObject("jsonStr");
		SenderGlPzmlEntity senderGlPzmlEntity = jsonObject.toJavaObject(SenderGlPzmlEntity.class);
		//如果没有传入年度，则查询当年得，避免数据查询太大
		if (senderGlPzmlEntity.getKjqj() == null) {
			senderGlPzmlEntity.setKjqj(DateUtil.format(new Date(),"yyyy"));
		}
		if(StrUtil.isEmpty(senderGlPzmlEntity.getZth())){
			logger.info("======传递的账套号为:{}=========",senderGlPzmlEntity.getZth());
			return BaseResult.getFailureMessageEntity("请传递账套号");
		}
		List<JSONObject> list=new ArrayList<>();
		List<SenderGlPzmlEntity> senderGlPzmlEntities=new ArrayList<>();
		try {
			/*switch (senderGlPzmlEntity.getZth()){
				case "003"://练市人民医院
					senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
					break;
				case "004"://双林镇中心卫生院
					senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
					break;
				case "005"://练市镇中心卫生院
					senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
					break;
				case "007"://善琏镇卫生院
					senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
					break;
				case "009":
					senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
					break;
				case "010":
					senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
					break;
				case "011":
					senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
					break;
				case "012":
					senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
					break;
				case "001"://南浔区人民医院
					senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
					break;
				default:
					break;
			}*/
			senderGlPzmlEntities=senderGlPzmlDao.querySenderGlPzmlEntity(senderGlPzmlEntity);
			if (CollectionUtils.isEmpty(senderGlPzmlEntities)) {
				logger.info("{}账套GRPU8没有凭证目录信息",senderGlPzmlEntity.getZth());
				return BaseResult.getSuccessMessageEntity("GRPU8没有凭证目录信息",null);
			} else {
				for (SenderGlPzmlEntity pzmlEntity : senderGlPzmlEntities) {
					JSONObject jsonObjectPz=new JSONObject();
					jsonObjectPz.put("gl_pzml",pzmlEntity);
					//根据凭证号，会计期间，账套号查询凭证内容信息
					SenderGlPznrEntity senderGlPznrEntity = new SenderGlPznrEntity();
					senderGlPznrEntity.setKjqj(pzmlEntity.getKjqj());
					senderGlPznrEntity.setZth(pzmlEntity.getZth());
					senderGlPznrEntity.setPzh(pzmlEntity.getPzh());
					senderGlPznrEntity.setGsdm(pzmlEntity.getGsdm());
					senderGlPznrEntity.setIdpzh(pzmlEntity.getIdpzh());
					senderGlPznrEntity.setDataSourceCode(senderGlPzmlEntity.getDataSourceCode());
					List<SenderGlPznrEntity> senderGlPznrEntities=new ArrayList<>();
					/*switch (senderGlPzmlEntity.getZth()){
						case "003"://练市人民医院
							senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
							break;
						case "004"://双林镇中心卫生院
							senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
							break;
						case "005"://练市镇中心卫生院
							senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
							break;
						case "007"://善琏镇卫生院
							senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
							break;
						case "009":
							senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
							break;
						case "010":
							senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
							break;
						case "011":
							senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
							break;
						case "012":
							senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
							break;
						case "001"://南浔区人民医院
							senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
							break;
						default:
							break;
					}*/
					senderGlPznrEntities= senderGlPznrDao.querySenderGlPznrEntity(senderGlPznrEntity);
					jsonObjectPz.put("gl_pznr",senderGlPznrEntities);
					list.add(jsonObjectPz);
				}
				return BaseResult.getSuccessMessageEntity("查询凭证成功",list);
			}
		} catch (Exception e) {
			logger.info("{}账套查询GROU8凭证信息失败:{}", senderGlPzmlEntity.getZth(),e.getMessage());
			return BaseResult.getFailureMessageEntity("查询GROU8凭证信息失败");
		}
	}

	//保存凭证到凭证日志表中 发送方
	@Override
	public JsonResultEntity saveEntity(JSONObject json) {
		JSONObject jsonObject = json.getJSONObject("jsonStr");
		JSONObject jsonObjectMain = jsonObject.getJSONObject("main");//或者凭证目录
		JSONArray jsonArray = jsonObject.getJSONArray("details");
		if (StrUtil.isEmpty(jsonObject.getString("kjqj"))) {
			throw new RuntimeException("会计期间为空");
		}
		if (StrUtil.isEmpty(jsonObject.getString("gsdm"))) {
			throw new RuntimeException("公司代码为空");
		}
		if (StrUtil.isEmpty(jsonObject.getString("zth"))) {
			throw new RuntimeException("账套编号为空");
		}
		if (StrUtil.isEmpty(jsonObject.getString("pzh"))) {
			throw new RuntimeException("凭证号为空");
		}
		//生成idpzh
		String idpzh = jsonObjectMain.getString("idpzh")==null?String.valueOf(UUID.randomUUID()):jsonObjectMain.getString("idpzh");
		jsonObjectMain.put("kjqj",jsonObject.getString("kjqj"));
		jsonObjectMain.put("idpzh",idpzh);
		jsonObjectMain.put("gsdm",jsonObject.getString("gsdm"));
		jsonObjectMain.put("zth",jsonObject.getString("zth"));
		jsonObjectMain.put("pzh",jsonObject.getString("pzh"));
		SenderGlPzmlEntity senderGlPzmlEntity = jsonObjectMain.toJavaObject(SenderGlPzmlEntity.class);
		try {
             logger.info("===========开始保存凭证日志，idpzh:{},pzh:{}=========",senderGlPzmlEntity.getIdpzh(),senderGlPzmlEntity.getPzh());
			SenderGlPzmlEntity glPzmlEntity = senderGlPzmlDao.saveSenderGlPzmlEntity(senderGlPzmlEntity);
			List<JSONObject> list=new ArrayList<JSONObject>();
			JSONObject jsonObjectSend=new JSONObject();
			jsonObjectSend.put("pzml",glPzmlEntity);
			List<SenderGlPznrEntity> listPznr=new ArrayList<>();
			//遍历数组，得到凭证内容
			if(jsonArray.size()>0&&jsonArray!=null){
				for (Object o : jsonArray) {
					SenderGlPznrEntity glPznrEntity=(SenderGlPznrEntity)o;
					glPznrEntity.setKjqj(jsonObject.getString("kjqj"));
					glPznrEntity.setGsdm(jsonObject.getString("gsdm"));
					glPznrEntity.setZth(jsonObject.getString("zth"));
					glPznrEntity.setPzh(jsonObject.getString("pzh"));
					glPznrEntity.setIdpznr(glPznrEntity.getIdpznr() == null ? String.valueOf(UUID.randomUUID()) : glPznrEntity.getIdpznr() );
					SenderGlPznrEntity senderGlPznrEntity = senderGlPznrDao.saveSenderGlPznrEntity(glPznrEntity);
					listPznr.add(senderGlPznrEntity);
				}
			}
			jsonObjectSend.put("pznr",listPznr);
			list.add(jsonObjectSend);
			return BaseResult.getSuccessMessageEntity("保存凭证日志成功",list);
		}catch (Exception e){
			logger.info("保存GRPU8凭证日志失败:{}", e.getMessage());
			return BaseResult.getFailureMessageEntity("凭证日志保存失败");
		}
	}

	//更新凭证到凭证日志表中 发送方
	@Override
	public JsonResultEntity updateEntity(JSONObject json) {
		JSONObject jsonObject = json.getJSONObject("jsonStr");
		JSONObject jsonObjectMain = jsonObject.getJSONObject("main");//或者凭证目录
		JSONArray jsonArray = jsonObject.getJSONArray("details");
		if (StrUtil.isEmpty(jsonObject.getString("kjqj"))) {
			throw new RuntimeException("会计期间为空");
		}
		if (StrUtil.isEmpty(jsonObject.getString("gsdm"))) {
			throw new RuntimeException("公司代码为空");
		}
		if (StrUtil.isEmpty(jsonObject.getString("zth"))) {
			throw new RuntimeException("账套编号为空");
		}
		if (StrUtil.isEmpty(jsonObject.getString("pzh"))) {
			throw new RuntimeException("凭证号为空");
		}
		if (StrUtil.isEmpty(jsonObjectMain.getString("idpzh"))) {
			throw new RuntimeException("idpzh为空");
		}
		SenderGlPzmlEntity senderGlPzmlEntity = jsonObjectMain.toJavaObject(SenderGlPzmlEntity.class);
		senderGlPzmlEntity.setKjqj(jsonObject.getString("kjqj"));
		senderGlPzmlEntity.setGsdm(jsonObject.getString("gsdm"));
		senderGlPzmlEntity.setZth(jsonObject.getString("zth"));
		senderGlPzmlEntity.setPzh(jsonObject.getString("pzh"));
		try {
         logger.info("==========开始更新凭证日志,idpzh:{},pzh:{}",senderGlPzmlEntity.getIdpzh(),senderGlPzmlEntity.getPzh());
			SenderGlPzmlEntity senderGlPzmlEntitySend = senderGlPzmlDao.updateSenderGlPzmlEntity(senderGlPzmlEntity);
			List<JSONObject> list=new ArrayList<>();
			JSONObject jsonObjectPz=new JSONObject();
			jsonObjectPz.put("pzml",senderGlPzmlEntitySend);
			List<SenderGlPznrEntity> listPznr=new ArrayList<>();
		 //遍历数组，得到凭证内容
			if(jsonArray.size()>0&&jsonArray!=null){
				for (Object o : jsonArray) {
					SenderGlPznrEntity glPznrEntity=(SenderGlPznrEntity)o;
					SenderGlPznrEntity senderGlPznr=new SenderGlPznrEntity();
					senderGlPznr.setKjqj(jsonObject.getString("kjqj"));
					senderGlPznr.setGsdm(jsonObject.getString("gsdm"));
					senderGlPznr.setZth(jsonObject.getString("zth"));
					senderGlPznr.setPzh(jsonObject.getString("pzh"));
					senderGlPznr.setIdpznr(glPznrEntity.getIdpznr());
					//根据凭证内容id等条件查询在凭证内容日志中是否存在，如果存在，则更新，如果不存在则新增
					//比如 凭证内容8条，日志中只有7条，则多余的一条新增，剩下7条更新
					SenderGlPznrEntity pznrEntity = senderGlPznrDao.querySenderGlPznrEntityOne(senderGlPznr);
					if(pznrEntity==null){
						SenderGlPznrEntity senderGlPznrEntity = senderGlPznrDao.saveSenderGlPznrEntity(glPznrEntity);
						listPznr.add(senderGlPznrEntity);
					}else{
						SenderGlPznrEntity senderGlPznrEntity = senderGlPznrDao.updateSenderGlPznrEntity(glPznrEntity);
						listPznr.add(senderGlPznrEntity);
					}
				}
			}
			jsonObjectPz.put("pznr",listPznr);
			list.add(jsonObjectPz);
			return BaseResult.getSuccessMessageEntity("凭证日志更新成功",list);
		}catch (Exception e){
			logger.info("更新GRPU8凭证日志失败:{}", e.getMessage());
			return BaseResult.getFailureMessageEntity("凭证日志更新失败");
		}
	}

	//查询凭证
	@Override
	public JsonResultEntity queryEntityPageHealthBureau(JSONObject json) {
		JSONObject jsonObject = json.getJSONObject("jsonStr");
		SenderGlPzmlEntity receiverGlPzmlEntity = jsonObject.toJavaObject(SenderGlPzmlEntity.class);
		if(receiverGlPzmlEntity.getIdpzh()!=null) {
			try {
				List<JSONObject> list=new ArrayList<>();
				logger.info("====开始根据账套号:{}和凭证号:{}查询卫生局里面得凭证数据",receiverGlPzmlEntity.getZth(),receiverGlPzmlEntity.getIdpzh());
				List<SenderGlPzmlEntity> receiverGlPzmlEntities = senderGlPzmlDao.queryGlPzmlHealthBureau(receiverGlPzmlEntity);
				if(CollectionUtils.isNotEmpty(receiverGlPzmlEntities)){
					for (SenderGlPzmlEntity glPzmlEntity : receiverGlPzmlEntities) {
						JSONObject jsonObjectStr=new JSONObject();
						jsonObjectStr.put("main",glPzmlEntity);
						//根据凭证号，会计期间，账套号查询凭证内容信息
						SenderGlPznrEntity receiverGlPznrEntity = new SenderGlPznrEntity();
						receiverGlPznrEntity.setKjqj(glPzmlEntity.getKjqj());
						receiverGlPznrEntity.setZth(glPzmlEntity.getZth());
						receiverGlPznrEntity.setPzh(glPzmlEntity.getPzh());
						receiverGlPznrEntity.setGsdm(glPzmlEntity.getGsdm());
						List<SenderGlPznrEntity> receiverGlPznrEntities = senderGlPznrDao.queryGlPznrHealthBureau(receiverGlPznrEntity);
						jsonObjectStr.put("details",receiverGlPznrEntities);
						list.add(jsonObjectStr);
					}
					return BaseResult.getSuccessMessageEntity("查询凭证成功",list);
				}else{
					logger.info("根据idpzh:{}和账套号:{}查询接收方的凭证为空",receiverGlPzmlEntity.getZth(),receiverGlPzmlEntity.getIdpzh());
					return BaseResult.getSuccessMessageEntity("查询接收方的凭证为空");
				}
			} catch (Exception e) {
				logger.info("根据账套号:{}查询卫生局得GROU8凭证信息失败:{}", receiverGlPzmlEntity.getZth(),e.getMessage());
				return BaseResult.getFailureMessageEntity("查询接收方得GROU8凭证信息失败");
			}
		}
		return null;
	}

	//保存凭证
	@Override
	public JsonResultEntity saveEntityHealthBureau(JSONObject json) {
		JSONObject jsonObject = json.getJSONObject("jsonStr");
		JSONObject jsonObjectMain = jsonObject.getJSONObject("main");//获取凭证目录
		JSONArray jsonArray = jsonObject.getJSONArray("details");//获取凭证内容
		if (!checkStr(jsonObject.getString("kjqj"))) {
			return BaseResult.getFailureMessageEntity("会计期间为空");
		}
		if (!checkStr(jsonObject.getString("gsdm"))) {
			return BaseResult.getFailureMessageEntity("公司代码为空");
		}
		if (!checkStr(jsonObject.getString("zth"))) {
			return BaseResult.getFailureMessageEntity("账套编号为空");
		}
		if (!checkStr(jsonObject.getString("pzh"))) {
			return BaseResult.getFailureMessageEntity("凭证号为空");
		}
		//生成idpzh
		String idpzh = jsonObjectMain.getString("idpzh")==null?String.valueOf(UUID.randomUUID()):jsonObjectMain.getString("idpzh");
		jsonObjectMain.put("kjqj",jsonObject.getString("kjqj"));
		jsonObjectMain.put("idpzh",idpzh);
		jsonObjectMain.put("gsdm",jsonObject.getString("gsdm"));
		jsonObjectMain.put("zth",jsonObject.getString("zth"));
		jsonObjectMain.put("pzh",jsonObject.getString("pzh"));
		SenderGlPzmlEntity glPzmlEntity = jsonObjectMain.toJavaObject(SenderGlPzmlEntity.class);
		try {
			logger.info("===========根据账套号:{}开始保存凭证，idpzh:{},pzh:{}=========",glPzmlEntity.getZth(),glPzmlEntity.getIdpzh(),glPzmlEntity.getPzh());
			SenderGlPzmlEntity receiverGlPzmlEntity = senderGlPzmlDao.saveGlPzmlHealthBureau(glPzmlEntity);
			List<JSONObject> list=new ArrayList<>();
			JSONObject jsonObjectReceiver =new JSONObject();
			jsonObjectReceiver.put("gl_pzml",receiverGlPzmlEntity);
			List<SenderGlPznrEntity> listGlPznr=new ArrayList<>();
			//遍历数组，得到凭证内容
			if(jsonArray.size()>0&&jsonArray!=null) {
				for (Object o : jsonArray) {
					SenderGlPznrEntity receiverGlPznrEntity=(SenderGlPznrEntity)o;
					receiverGlPznrEntity.setKjqj(jsonObject.getString("kjqj"));
					receiverGlPznrEntity.setGsdm(jsonObject.getString("gsdm"));
					receiverGlPznrEntity.setZth(jsonObject.getString("zth"));
					receiverGlPznrEntity.setPzh(jsonObject.getString("pzh"));
					receiverGlPznrEntity.setDataSourceCode(glPzmlEntity.getDataSourceCode());
					receiverGlPznrEntity.setIdpznr(receiverGlPznrEntity.getIdpznr()== null ? String.valueOf(UUID.randomUUID()) : receiverGlPznrEntity.getIdpznr());
					SenderGlPznrEntity glPznrEntity = senderGlPznrDao.saveGlPznrHealthBureau(receiverGlPznrEntity);
					listGlPznr.add(glPznrEntity);
				}
			}
			jsonObjectReceiver.put("gl_pznr",listGlPznr);
			list.add(jsonObjectReceiver);
			return BaseResult.getSuccessMessageEntity("保存凭证成功",jsonObjectReceiver);
		}catch (Exception e){
			logger.info("根据账套号:{}保存GRPU8凭证失败:{}",jsonObjectMain.getString("zth"),e.getMessage());
			return BaseResult.getFailureMessageEntity("凭证保存失败");
		}
	}

	//更新凭证
	@Override
	public JsonResultEntity updateEntityHealthBureau(JSONObject json) {
		JSONObject jsonObject = json.getJSONObject("jsonStr");
		JSONObject jsonObjectMain = jsonObject.getJSONObject("main");//或者凭证目录
		JSONArray jsonArray = jsonObject.getJSONArray("details");
		if (!checkStr(jsonObject.getString("kjqj"))) {
			return BaseResult.getFailureMessageEntity("会计期间为空");
		}
		if (!checkStr(jsonObject.getString("gsdm"))) {
			return BaseResult.getFailureMessageEntity("公司代码为空");
		}
		if (!checkStr(jsonObject.getString("zth"))) {
			return BaseResult.getFailureMessageEntity("账套编号为空");
		}
		if (!checkStr(jsonObject.getString("pzh"))) {
			return BaseResult.getFailureMessageEntity("凭证号为空");
		}
		if (!checkStr(jsonObjectMain.getString("idpzh"))) {
			return BaseResult.getFailureMessageEntity("idpzh为空");
		}
		if(jsonArray.size()>0&&jsonArray!=null){
			for (Object o : jsonArray) {
				SenderGlPznrEntity senderGlPznrEntity = (SenderGlPznrEntity)o;
				if (StrUtil.isEmpty(senderGlPznrEntity.getIdpznr())) {
					return BaseResult.getFailureMessageEntity("凭证内容得id为空");
				}
			}
		}
		SenderGlPzmlEntity receiverGlPzmlEntity = jsonObjectMain.toJavaObject(SenderGlPzmlEntity.class);
		receiverGlPzmlEntity.setKjqj(jsonObject.getString("kjqj"));
		receiverGlPzmlEntity.setGsdm(jsonObject.getString("gsdm"));
		receiverGlPzmlEntity.setZth(jsonObject.getString("zth"));
		receiverGlPzmlEntity.setPzh(jsonObject.getString("pzh"));
		try {
			logger.info("==========开始根据账套号:{}更新凭证,idpzh:{},pzh:{}",receiverGlPzmlEntity.getZth(),receiverGlPzmlEntity.getIdpzh(),receiverGlPzmlEntity.getPzh());
			SenderGlPzmlEntity glPzmlEntity = senderGlPzmlDao.updateGlPzmlHealthBureau(receiverGlPzmlEntity);
			List<JSONObject> list=new ArrayList<>();
			JSONObject jsonObjectPz=new JSONObject();
			jsonObjectPz.put("gl_pzml",glPzmlEntity);
			List<SenderGlPznrEntity> listPznr=new ArrayList<>();
			//遍历数组，得到凭证内容
			if(jsonArray.size()>0 && jsonArray!=null){
				for (Object o : jsonArray) {
					SenderGlPznrEntity receiverGlPznr=(SenderGlPznrEntity)o;
					receiverGlPznr.setKjqj(jsonObject.getString("kjqj"));
					receiverGlPznr.setGsdm(jsonObject.getString("gsdm"));
					receiverGlPznr.setZth(jsonObject.getString("zth"));
					receiverGlPznr.setPzh(jsonObject.getString("pzh"));
					receiverGlPznr.setDataSourceCode(receiverGlPzmlEntity.getDataSourceCode());
					//根据凭证内容id等条件查询在接收方凭证内容中是否存在，如果存在，则更新，如果不存在则新增
					//比如 发送方的凭证内容8条，接收方只有7条，则多余的一条新增，剩下7条更新
					SenderGlPznrEntity senderGlPznrEntity = senderGlPznrDao.querySenderGlPznrEntityOne(receiverGlPznr);
					if(senderGlPznrEntity==null){
						SenderGlPznrEntity glPznrEntity = senderGlPznrDao.saveGlPznrHealthBureau(receiverGlPznr);
						listPznr.add(glPznrEntity);
					}else {
						SenderGlPznrEntity glPznrEntity = senderGlPznrDao.updateGlPznrHealthBureau(receiverGlPznr);
						listPznr.add(glPznrEntity);
					}
				}
			}
			jsonObjectPz.put("gl_pznr",listPznr);
			list.add(jsonObjectPz);
			return BaseResult.getSuccessMessageEntity("凭证更新成功",list);
		}catch (Exception e){
			logger.info("根据账套号:{}更新GRPU8凭证失败:{}", receiverGlPzmlEntity.getZth(),e.getMessage());
			return BaseResult.getFailureMessageEntity("凭证更新失败");
		}
	}

	//删除凭证
	@Override
	public JsonResultEntity deleteEntityHealthBureau(JSONObject json) {
		JSONObject jsonObject = json.getJSONObject("jsonStr");
		JSONObject jsonObjectMain = jsonObject.getJSONObject("main");//或者凭证目录
		JSONArray jsonArray = jsonObject.getJSONArray("details");
		if (!checkStr(jsonObject.getString("gsdm"))) {
			return BaseResult.getFailureMessageEntity("公司代码为空");
		}
		if (!checkStr(jsonObject.getString("zth"))) {
			return BaseResult.getFailureMessageEntity("账套编号为空");
		}
		if (!checkStr(jsonObject.getString("kjqj"))) {
			jsonObject.put("kjqj",DateUtil.format(new Date(),"yyyyMM"));
		}
		SenderGlPzmlEntity receiverGlPzmlEntity = jsonObjectMain.toJavaObject(SenderGlPzmlEntity.class);
		receiverGlPzmlEntity.setKjqj(jsonObject.getString("kjqj"));
		receiverGlPzmlEntity.setGsdm(jsonObject.getString("gsdm"));
		receiverGlPzmlEntity.setZth(jsonObject.getString("zth"));
		receiverGlPzmlEntity.setPzh(jsonObject.getString("pzh"));
		try {
			logger.info("==========开始根据账套号:{}删除凭证,idpzh:{},pzh:{}",receiverGlPzmlEntity.getZth(),receiverGlPzmlEntity.getIdpzh(),receiverGlPzmlEntity.getPzh());
			Integer integer = senderGlPzmlDao.deleteGlPzmlHealthBureau(receiverGlPzmlEntity);
			//遍历数组，得到凭证内容
			if(jsonArray.size()>0 && jsonArray!=null){
				for (Object o : jsonArray) {
					SenderGlPznrEntity receiverGlPznr=(SenderGlPznrEntity)o;
					receiverGlPznr.setKjqj(jsonObject.getString("kjqj"));
					receiverGlPznr.setGsdm(jsonObject.getString("gsdm"));
					receiverGlPznr.setZth(jsonObject.getString("zth"));
					receiverGlPznr.setPzh(jsonObject.getString("pzh"));
					receiverGlPznr.setDataSourceCode(receiverGlPzmlEntity.getDataSourceCode());
					Integer i = senderGlPznrDao.deleteGlPznrHealthBureau(receiverGlPznr);
				}
			}
			return BaseResult.getSuccessMessageEntity("凭证删除成功",integer);
		}catch (Exception e){
			logger.info("根据账套号:{}删除GRPU8凭证失败:{}", receiverGlPzmlEntity.getZth(),e.getMessage());
			return BaseResult.getFailureMessageEntity("凭证删除失败");
		}
	}


	//保存凭证 商学院，指标被哪些凭证使用
	@Override
	public Object queryGlPzmlSxy(JSONObject json){
		JSONObject jsonObject = json.getJSONObject("jsonStr");
		SenderGlPzmlEntity glPzmlEntity = jsonObject.toJavaObject(SenderGlPzmlEntity.class);
		if(StrUtil.isEmpty(glPzmlEntity.getKjqj())){
			glPzmlEntity.setKjqj(DateUtil.format(new Date(),"yyyyMM"));
		}
		//获取token
		String token = getToken();
		if(StrUtil.isEmpty(token)){
			return BaseResult.getFailureMessageEntity("token为空，请先获取token");
		}
		//查询凭证数据
		List<SenderGlPzmlEntity> list = senderGlPzmlDao.queryGlPzmlSxy(glPzmlEntity);
		if(CollectionUtils.isEmpty(list)){
			return BaseResult.getSuccessMessageEntity("没有需要同步得凭证",null);
		}
		try {
			String result=null;
			for (SenderGlPzmlEntity pzmlEntity : list) {
				String pzNum = pzmlEntity.getGsdm() + "_" + pzmlEntity.getZth() + "_" + pzmlEntity.getKjqj() + "_" + pzmlEntity.getPzh();
				//转换日期，如将20240514转为2024-05-14
				SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
				SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date date = inputFormat.parse(pzmlEntity.getSrrq());
				String outputDateString = outputFormat.format(date);
				//将金额四舍五入
				BigDecimal bigDecimalValue = new BigDecimal(pzmlEntity.getPzje());
				BigDecimal roundedValue = bigDecimalValue.setScale(2,
						RoundingMode.HALF_UP);
				JSONObject jsonObjectParams=new JSONObject();
				jsonObjectParams.put("code",pzmlEntity.getIdpzh());//pzid
				jsonObjectParams.put("budgetYear",pzmlEntity.getKjqj().substring(0,4));//预算年度
				jsonObjectParams.put("applyDate",outputDateString);//日期
				jsonObjectParams.put("userCode",pzmlEntity.getSrid());//用户编码
				jsonObjectParams.put("depCode","A518");//部门编码
				jsonObjectParams.put("description",pzmlEntity.getPzzy());//说明
				jsonObjectParams.put("amount",roundedValue.doubleValue());//金额
				jsonObjectParams.put("pzNum",pzNum);//凭证号 例如：公司代码+账套号+会计期间+凭证号：001_001_202408_付款_1
				//根据idpzh查询指标id和指标金额
				GbiZbxmbEntity gbiZbxmbEntity=new GbiZbxmbEntity();
				gbiZbxmbEntity.setDjId(pzmlEntity.getIdpzh());
				gbiZbxmbEntity.setKjnd(pzmlEntity.getKjqj().substring(0,4));
				gbiZbxmbEntity.setDataSourceCode(glPzmlEntity.getDataSourceCode());
				List<GbiZbxmbEntity> gbiZbsyrecEntities = gbiZbxmbDao.queryZbxmbByIdpzh(gbiZbxmbEntity);
				logger.info("=======根据凭证idpzh:{}查询的指标金额和指标id数据有{}条",pzmlEntity.getIdpzh(),gbiZbsyrecEntities.size());
				if(CollectionUtils.isEmpty(gbiZbsyrecEntities)){
					jsonObjectParams.put("reimburseItems",new ArrayList<>());
				}else{
					JSONArray jsonArray=new JSONArray();
					for (GbiZbxmbEntity zbxmbEntity : gbiZbsyrecEntities) {
						BigDecimal bigDecimalValueZbxmb = new BigDecimal(zbxmbEntity.getJe());
						BigDecimal roundedValueZbxmb = bigDecimalValueZbxmb.setScale(2, RoundingMode.HALF_UP);
						JSONObject jsonObjectZbxm=new JSONObject();
						jsonObjectZbxm.put("thirdProjectCode",zbxmbEntity.getZbid());
						jsonObjectZbxm.put("amount",roundedValueZbxmb);
						jsonObjectZbxm.put("financialCode",zbxmbEntity.getJjkmdm());
						jsonArray.add(jsonObjectZbxm);
					}
					jsonObjectParams.put("reimburseItems",jsonArray);
				}
				JSONArray jsonArray=new JSONArray();
				jsonArray.add(jsonObjectParams);
				JSONObject jsonObjectData=new JSONObject();
				jsonObjectData.put("data",jsonArray);
				String params = jsonObjectData.toJSONString();
				logger.info("调用商学院凭证保存接口请求参数：{}",params);
				 result = HttpRequest.post(URLTest + "/nky/service/zsApi/saveZJSYPZReimburse?accessToken="+token).header("Content-Type", "application/json;charset=UTF-8").timeout(30000).body(params).execute().body();
				logger.info("调用商学院凭证保存接口返回参数：{}",result);
			}
			JSONObject jsonObjectResult=new JSONObject();
			jsonObjectResult.put("status","200");
			jsonObjectResult.put("pzml",result);
			return jsonObjectResult;
		}catch (Exception e){
			logger.info("根据凭证idpzh:{}查询指标失败:{}",glPzmlEntity.getIdpzh(),e.getMessage());
			return BaseResult.getFailureMessageEntity("根据凭证查询指标失败");
		}
	}


	//获取token
	private String getToken(){
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("appkey","9832-b00b-babf-4d6b-9e66-f6c1-3541-a0e6");
		jsonObject.put("appsecret","fbab-16fc-348e-4151-4814-eb06-1526-5f22");
		String params = jsonObject.toJSONString();
		logger.info("=========获取凭证token请求参数:{}========",params);
		String urlToken="nky/service/session/getAccessToken";
		String result = HttpRequest.post(URLTest + urlToken).header("Content-Type", "application/json;charset=UTF-8").timeout(30000).body(params).execute().body();
		logger.info("=========获取凭证token返回结果:{}========",result);
		JSONObject jsonObjectResult=JSONObject.parseObject(result);
		String value=jsonObjectResult.getString("value");
		if(StrUtil.isNotEmpty(value)){
			JSONObject jsonObjectValue = JSONObject.parseObject(value);
			String accessToken = jsonObjectValue.getString("accessToken");
			logger.info("=========获取得凭证token值为:{}=======",accessToken);
			return accessToken;
		}
		return null;
	}



}

