package com.dhcc.finance.main.service.impl;

import brave.Tracer;
import com.dhcc.common.constant.FinanceStatusCode;
import com.dhcc.common.constant.SysConstants;
import com.dhcc.common.constant.SysStatusCode;
import com.dhcc.common.model.CurrencyMeta;
import com.dhcc.common.model.SysUserInfo;
import com.dhcc.common.model.response.RestfulResponse;
import com.dhcc.common.util.CacheDataUtil;
import com.dhcc.common.util.SnowflakeIdWorker;
import com.dhcc.finance.constant.FinanceDictConsts;
import com.dhcc.finance.main.dao.*;
import com.dhcc.finance.main.domain.*;
import com.dhcc.finance.main.domain.CwGlTransferdetailExample.Criteria;
import com.dhcc.finance.main.model.*;
import com.dhcc.finance.main.service.CwGlTransferExecService;
import com.dhcc.finance.main.service.CwGlVoucherService;
import com.dhcc.finance.util.FinanceDateUtil;
import com.dhcc.finance.util.MetaDataUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author hp
 *
 */
@Service
public class CwGlTransferExecServiceImpl implements CwGlTransferExecService{
	@Autowired
	CwGlTransferExecMapper cwGlTransferExecMapper;//结转信息表
	@Autowired
	private Tracer tracer;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	CwGlVoucherMapper cwGlVoucherMapper;//凭证表
	@Autowired
	CwBdGlorgbookMapper cwBdGlorgbookMapper;//账套表
	@Autowired
	CwGlTransferMapper cwGlTransferMapper;//结转方案表
	@Autowired
	CwGlTransferdetailMapper cwGlTransferdetailMapper;//结转方案明细
	@Autowired
	CwGlBalanceMapper cwGlBalanceMapper;//科目余额表
	@Autowired
	CwGlVouchermaxnoMapper cwGlVouchermaxnoMapper;//最大凭证号
	@Autowired
	CwBdAccsubjMapper cwBdAccsubjMapper;//会计科目表
	@Autowired
	CwGlDetailMapper cwGlDetailMapper;//分录信息表
	@Autowired
	CwGlTransfervouchMapper cwGlTransfervouchMapper;//结转凭证表
	@Autowired
	CwGlVoucherService cwGlVoucherService;
	@Autowired
	CwGlSettleMapper cwGlSettleMapper;//结账表
	@Autowired
	CwReverseOperationMapper cwReverseOperationMapper;//反向操作
	@Autowired
	CwBdParametricMapper cwBdParametricMapper;// 财务参数化设置表
	@Autowired
	CwBdAccountingMapper cwBdAccountingMapper;// 人员配置表
	@Autowired
	CwBdAccperiodquartMapper cwBdAccperiodquartMapper;//会计季度表
	@Autowired
	CwBdAccperiodyearMapper cwBdAccperiodyearMapper;//会计半年度表
	/* (非 Javadoc)  
	 * <p>Title: searchCwGlTransferExecAndName</p>  
	 * <p>Description: 查询所有的结转信息兼模糊查询</p>
	 * @param nameLike
	 * @param pageNum
	 * @param pageSize
	 * @param navigatePages
	 * @return  
	 * @see com.dhcc.finance.main.service.CwGlTransferExecService#searchCwGlTransferExecAndName(java.lang.String, int, int, int)    
	 * @author huangpeng
	 * @date 2019年4月1日 下午8:38:18
	 * @修改日志：
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public RestfulResponse<PageInfo<CwGlTransferExecAndName>, CurrencyMeta> searchCwGlTransferExecAndName(
			String nameLike,int pageNum, int pageSize, int navigatePages) {
		PageHelper.startPage(pageNum, pageSize,"CREATE_TIME DESC");
		List<CwGlTransferExecAndName> list=cwGlTransferExecMapper.selectAllDateByglorgbook(nameLike);
		PageInfo<CwGlTransferExecAndName> pageInfo = new PageInfo<>(list, navigatePages);
		return new RestfulResponse<PageInfo<CwGlTransferExecAndName>, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,pageInfo,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	}



	/* (非 Javadoc)  
	 * <p>Title: updateCwGlTransferExecForBatch</p>  
	 * <p>Description: 批量更新结转信息</p>
	 * @param cwGlTransferExecs
	 * @return  
	 * @see com.dhcc.finance.main.service.CwGlTransferExecService#updateCwGlTransferExecForBatch(java.util.List)    
	 * @author huangpeng
	 * @date 2019年4月2日 上午10:17:04
	 * @修改日志：
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public RestfulResponse<Object, CurrencyMeta> updateCwGlTransferExecForBatch(
			List<CwGlTransferWeb> cwGlTransferExecs) {
		SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
		if(sysUserInfo==null) {
			if (StringUtils.isNotBlank(cwGlTransferExecs.get(0).getAccounting_id())) {
				sysUserInfo = new SysUserInfo();
				sysUserInfo.setUserId("admin");
			} else {
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,SysStatusCode.USER_LOGOUT_ERROR.message(),MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
			}
		}
		for (CwGlTransferWeb CwGlTransferExec : cwGlTransferExecs) {
			String pkGlorgbook=CwGlTransferExec.getPkGlorgbook();//结转方案账套主键
			String period = CwGlTransferExec.getPkCurrperiod();//期间
			//根据账套主键查询账套内容
			CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(pkGlorgbook);
			String pkTransfer = cwBdGlorgbook.getPkTransfer();//结转主键
			long count=cwGlSettleMapper.countIsSettle(pkGlorgbook,period);//查询已结账数目
			if(count>0) {
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE.message(),
						MetaDataUtil.getMeta(tracer,FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE));
			}
			long i=cwGlVoucherMapper.countNotBooking(pkGlorgbook, period);//当前账套期间下的凭证是否所有都已记账
			if(i>0) {
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.EXISTENCE_OF_UNRECORDED.message(),
						MetaDataUtil.getMeta(tracer,FinanceStatusCode.EXISTENCE_OF_UNRECORDED));
			}
			// 查询该账套最后一次结转期间
			String maxPeriod = cwGlTransferExecMapper.selectMaxPeriod(pkGlorgbook);
			if(StringUtils.isNoneBlank(maxPeriod)&&period.compareTo(maxPeriod)<=0) {
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.GLORGBOOK_COVERAGE_BEEN_SETTLE.message(),
						MetaDataUtil.getMeta(tracer,FinanceStatusCode.GLORGBOOK_COVERAGE_BEEN_SETTLE));
			}
			// 插入结转信息表
			String transferExec = SnowflakeIdWorker.getInstance().nextIdString();//得到结转主键
			CwGlTransferExec exec =new CwGlTransferExec();
			//新增结转信息表	
			if (sysUserInfo != null) {
				exec.setUpdateUser(sysUserInfo.getUserId());	
				exec.setCreateUser(sysUserInfo.getUserId());
			}
			exec.setPeriod(period);
			exec.setPkGlorgbook(pkGlorgbook);
			exec.setPkTransferExec(transferExec);
			exec.setIstransfer("0");
			exec.setUseState("1");
			exec.setUpdateTime(new Date());
			exec.setCreateTime(new Date());
			//cwGlTransferExecMapper.insert(exec);
			
			//根据结转方案主键获取所有的结转方案明细
			CwGlTransferdetailExample cwGlTransferdetailExample = new CwGlTransferdetailExample();
			Criteria createCriteria = cwGlTransferdetailExample.createCriteria();
			createCriteria.andPkTransferEqualTo(pkTransfer);
			createCriteria.andUseStateEqualTo(FinanceDictConsts.Syzt.EFFECTIVE);
			List<CwGlTransferdetail> list = cwGlTransferdetailMapper.selectByExample(cwGlTransferdetailExample);
			List<CwGlVoucher> cwGlVoucherList=new ArrayList<CwGlVoucher>();//凭证集合用于批量审核、批量记账
			
			//遍历结转方案明细表 生成凭证
			RestfulResponse<Object, CurrencyMeta> res1 = addVoucherForTransfer(sysUserInfo,list,period,cwBdGlorgbook,transferExec,cwGlVoucherList,true);
			if(res1!=null) {
				exec.setUseState("0");
				cwGlTransferExecMapper.insert(exec);
				if(cwGlVoucherList.size()>0) {
					cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVoucherList);
				}
				return res1;
			}
			//自动审核记账
			if(cwGlVoucherList.size()>0) {
				RestfulResponse<Object, CurrencyMeta> res2 = automaticAuditAndSign(cwGlVoucherList);
				if(res2!=null) {
					exec.setUseState("0");
					cwGlTransferExecMapper.insert(exec);
					cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVoucherList);
					return res2;
				}
			}
			//是否利润结转
			if("12".equals(period.substring(period.indexOf("-")+1))) {
				List<CwGlVoucher> cwGlVoucherList1=new ArrayList<CwGlVoucher>();//凭证集合用于批量审核、批量记账
				RestfulResponse<Object, CurrencyMeta> resVoucher = addVoucherForTransfer(sysUserInfo,list,period,cwBdGlorgbook,transferExec,cwGlVoucherList1,false);
				if(resVoucher!=null) {
					exec.setUseState("0");
					cwGlTransferExecMapper.insert(exec);
					if(cwGlVoucherList.size()>0) {
						if(FinanceDictConsts.Syzt.EFFECTIVE.equals(cwGlVoucherList.get(0).getIssign())) {
							cwGlVoucherService.updateCwGlVoucherForReverseBooking(cwGlVoucherList);//反记账
						}
						if(FinanceDictConsts.Syzt.EFFECTIVE.equals(cwGlVoucherList.get(0).getIsaudit())) {
							cwGlVoucherService.updateCwGlVoucherForReverse(cwGlVoucherList);//反审核
						}

						cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVoucherList);
					}
					if(cwGlVoucherList1.size()>0) {
						cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVoucherList1);
					}
					return resVoucher;
				}
				//自动审核记账
				if(cwGlVoucherList1.size()>0) {
					RestfulResponse<Object, CurrencyMeta> res3 = automaticAuditAndSign(cwGlVoucherList1);
					if(res3!=null) {
						exec.setUseState("0");
						cwGlTransferExecMapper.insert(exec);
						if(cwGlVoucherList.size()>0) {
							if(FinanceDictConsts.Syzt.EFFECTIVE.equals(cwGlVoucherList.get(0).getIssign())) {
								cwGlVoucherService.updateCwGlVoucherForReverseBooking(cwGlVoucherList);//反记账
							}
							if(FinanceDictConsts.Syzt.EFFECTIVE.equals(cwGlVoucherList.get(0).getIsaudit())) {
								cwGlVoucherService.updateCwGlVoucherForReverse(cwGlVoucherList);//反审核
							}

							cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVoucherList);
						}
						cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVoucherList1);
						return res3;
					}
					cwGlVoucherList.addAll(cwGlVoucherList1);
				}
			}
			if(cwGlVoucherList.size()>0) {
				List<CwGlTransfervouch> cwGlTransfervouchList=new ArrayList<CwGlTransfervouch>();
				for (CwGlVoucher cwGlVoucher : cwGlVoucherList) {
					//生成结转凭证明细表
					CwGlTransfervouch cwGlTransfervouch = new CwGlTransfervouch();
					cwGlTransfervouch.setPkTransfervouch(SnowflakeIdWorker.getInstance().nextIdString());
					cwGlTransfervouch.setPkTransferExec(transferExec);
					cwGlTransfervouch.setPkVoucher(cwGlVoucher.getPkVoucher());
					cwGlTransfervouch.setPkTransfer(pkTransfer);
					cwGlTransfervouch.setCreateUser(sysUserInfo.getUserId());
					cwGlTransfervouch.setCreateTime(new Date());
					cwGlTransfervouch.setUpdateTime(new Date());
					cwGlTransfervouch.setUpdateUser(sysUserInfo.getUserId());
					cwGlTransfervouch.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
					cwGlTransfervouchList.add(cwGlTransfervouch);

				}
				cwGlTransfervouchMapper.insertForBatch(cwGlTransfervouchList);//增加结转凭证明细数据
			}
			exec.setIstransfer("1");
			exec.setTransferTime(new Date());
			exec.setTransferUser(sysUserInfo.getUserId());
			cwGlTransferExecMapper.insert(exec);
//			//更新结转信息表	
//			CwGlTransferExec exec1 =new CwGlTransferExec();
//			if (sysUserInfo != null) {
//				exec1.setUpdateUser(sysUserInfo.getUserId());	
//				exec1.setTransferUser(sysUserInfo.getUserId());
//			}
//			exec1.setPkTransferExec(transferExec);
//			exec1.setIstransfer("1");
//			exec1.setTransferTime(new Date());
//			exec1.setUpdateTime(new Date());
//			cwGlTransferExecMapper.updateByPrimaryKeySelective(exec1);
		}
		return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	}


	/* (非 Javadoc)  
	 * <p>Title: searchCwGlTransferExecAndNameForReverse</p>  
	 * <p>Description: 查询全部反结转信息列表</p>
	 * @param nameLike
	 * @param pkAccperiodLike
	 * @param pageNum
	 * @param pageSize
	 * @param navigatePages
	 * @return  
	 * @see com.dhcc.finance.main.service.CwGlTransferExecService#searchCwGlTransferExecAndNameForReverse(java.lang.String, java.lang.String, int, int, int)    
	 * @author huangpeng
	 * @date 2019年4月9日 下午8:55:27
	 * @修改日志：
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public RestfulResponse<PageInfo<CwGlTransferExecAndName>, CurrencyMeta> searchCwGlTransferExecAndNameForReverse(
			String nameLike, String pkAccperiodLike, int pageNum, int pageSize, int navigatePages,String istransfer, String transferUser, String transferTime) {
		PageHelper.startPage(pageNum, pageSize,"CREATE_TIME DESC");
		List<CwGlTransferExecAndName> list=cwGlTransferExecMapper.selectAllDateByNameLike(nameLike,pkAccperiodLike,"1",transferUser,transferTime);
		PageInfo<CwGlTransferExecAndName> pageInfo = new PageInfo<>(list, navigatePages);
		return new RestfulResponse<PageInfo<CwGlTransferExecAndName>, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,pageInfo,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	}


	/* (非 Javadoc)  
	 * <p>Title: updateCwGlTransferExecForBatchReverse</p>  
	 * <p>Description:反结转 </p>
	 * @param cwGlTransferExecs
	 * @return  
	 * @see com.dhcc.finance.main.service.CwGlTransferExecService#updateCwGlTransferExecForBatchReverse(java.util.List)    
	 * @author huangpeng
	 * @date 2019年4月9日 下午10:18:53
	 * @修改日志：
	 */
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public RestfulResponse<Object, CurrencyMeta> updateCwGlTransferExecForBatchReverse(
			List<CwGlTransferExec> cwGlTransferExecs) {
		SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
		for (CwGlTransferExec cwGlTransferExec : cwGlTransferExecs) {
			String period = cwGlTransferExec.getPeriod();
			//查询已结账账套
			long count=cwGlSettleMapper.countIsSettle(cwGlTransferExec.getPkGlorgbook(),cwGlTransferExec.getPeriod());
			if(count>0) {
				CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(cwGlTransferExec.getPkGlorgbook());
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE.message(),
						MetaDataUtil.getMeta(tracer,FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE));
			}
			//跨期反结转校验
			String maxPeriod=
					cwGlTransferExecMapper.selectMaxPeriod(cwGlTransferExec.getPkGlorgbook());
			if(StringUtils.isNoneBlank(maxPeriod)&&period.compareTo(maxPeriod)<0) {
				CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(cwGlTransferExec.getPkGlorgbook());
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.REVERSE_TRANSFER_ISFAIL.message()+",请先反结转"+maxPeriod+"期",
						MetaDataUtil.getMeta(tracer,FinanceStatusCode.REVERSE_TRANSFER_ISFAIL));
			}
			//根据结转主键查询结转明细
			List<CwGlVoucher> cwGlVouchers=new ArrayList<CwGlVoucher>();
			List<CwGlTransfervouch> cwGlTransfervouchList=cwGlTransfervouchMapper.selectByKey(cwGlTransferExec.getPkTransferExec());
			if(cwGlTransfervouchList.size()>0) {
				for(CwGlTransfervouch cwGlTransfervouch:cwGlTransfervouchList) {
					//根据结转明细查询凭证信息表
					CwGlVoucher cwGlVoucher=cwGlVoucherMapper.selectByPrimaryKey(cwGlTransfervouch.getPkVoucher());
					if(cwGlVoucher==null) {
						return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.NOTFOUND_PKVOUCHER.message(),
								MetaDataUtil.getMeta(tracer,FinanceStatusCode.NOTFOUND_PKVOUCHER));
					}
					cwGlVouchers.add(cwGlVoucher);
					cwGlTransfervouch.setUseState("0");
					cwGlTransfervouchMapper.updateByPrimaryKey(cwGlTransfervouch);   
					
				}
				if(FinanceDictConsts.Syzt.EFFECTIVE.equals(cwGlVouchers.get(0).getIssign())) {
					cwGlVoucherService.updateCwGlVoucherForReverseBooking(cwGlVouchers);//反记账
				}
				
				if(FinanceDictConsts.Syzt.EFFECTIVE.equals(cwGlVouchers.get(0).getIsaudit())) {
					cwGlVoucherService.updateCwGlVoucherForReverse(cwGlVouchers);//反审核
				}
				cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVouchers);
			}
			//更新结转信息表
			CwGlTransferExecExample example = new CwGlTransferExecExample();
			CwGlTransferExecExample.Criteria createCriteria = example.createCriteria();
			createCriteria.andPkGlorgbookEqualTo(cwGlTransferExec.getPkGlorgbook());
			createCriteria.andPeriodEqualTo(cwGlTransferExec.getPeriod());
			
			if (sysUserInfo != null) {
				cwGlTransferExec.setUpdateUser(sysUserInfo.getUserId());	
			}
			cwGlTransferExec.setIstransfer("0");
			cwGlTransferExec.setUseState("0");
			cwGlTransferExec.setUpdateTime(new Date());
			cwGlTransferExec.setPkTransferExec(null);
			cwGlTransferExec.setTransferUser(null);
			int res =cwGlTransferExecMapper.updateByExampleSelective(cwGlTransferExec, example);
			
			if(res>0) {
				CwReverseOperation cwReverseOperation = new CwReverseOperation();
				cwReverseOperation.setPkGlorgbook(cwGlTransferExec.getPkGlorgbook());
				cwReverseOperation.setPeriod(cwGlTransferExec.getPeriod());
				if (sysUserInfo != null) {
				cwReverseOperation.setOperator(sysUserInfo.getUserId());
				}
				cwReverseOperation.setReverseType(FinanceDictConsts.Cwfxcz.FJIEZ);
				cwReverseOperation.setOperationtime(new Date());
				cwReverseOperation.setPkReverse(SnowflakeIdWorker.getInstance().nextIdString());
				cwReverseOperationMapper.insert(cwReverseOperation);//插入反结转标志
			}
		}			
		return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	}



	@Override
	public RestfulResponse<Object, CurrencyMeta> countTransferTotal(String nameLike, String pkAccperiodLike,
			String istransfer, String transferUser, String transferTime) {
		long countTransferTotal = cwGlTransferExecMapper.countTransferTotal(nameLike, pkAccperiodLike, istransfer, transferUser, transferTime);
		return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,
				countTransferTotal,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	}
    
    /** 功能描述：初始化结转数据
     * @return
     * @author xuxiao
     * @date 2019年8月23日 上午11:52:51
     * @修改日志：
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<Object, CurrencyMeta> insertForTransfer(String period)
    {
    	SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
    	Map<String, Object> map =new HashMap<String, Object>();
    	map.put("createUser", sysUserInfo == null? null:sysUserInfo.getUserId());
    	map.put("updateUser", sysUserInfo == null? null:sysUserInfo.getUserId());
    	map.put("period", period);
    	int res = cwGlTransferExecMapper.insertForTransfer(map);
		if(res>0){
			return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
		}else{
			return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.ALLGLORGBOOK_IS_ADD.message(),
					MetaDataUtil.getMeta(tracer, FinanceStatusCode.ALLGLORGBOOK_IS_ADD));
		}
    }


    /*
     * (非 Javadoc)  
     * <p>Title: searchTransferForIncome</p>  
     * <p>Description:查询结转收入费用余额 </p>
     * @param pkGlorgbook
     * @param period
     * @param pageNum
     * @param pageSize
     * @param navigatePages
     * @return  
     * @see com.dhcc.finance.main.service.CwGlTransferExecService#searchTransferForIncome(java.lang.String, java.lang.String, int, int, int)    
     * @author huangpeng
     * @date 2019年10月9日 下午2:12:49
     * @修改日志：
     */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public RestfulResponse<List<CwGlTransferExecDetail>, CurrencyMeta> searchTransferForIncome(String pkGlorgbook,
			String period) {
		SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
		if(sysUserInfo==null) {
			return new RestfulResponse<List<CwGlTransferExecDetail>, CurrencyMeta>(SysConstants.CODE.FAIL,SysStatusCode.USER_LOGOUT_ERROR.message(),MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
		}
		List<CwGlTransferExecDetail> list=new ArrayList<CwGlTransferExecDetail>();
		
		//根据账套主键查询账套内容
		CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(pkGlorgbook);
		String pkTransfer = cwBdGlorgbook.getPkTransfer();//结转主键
		String pkSubjscheme = cwBdGlorgbook.getPkSubjscheme();//科目版本
		long count=cwGlSettleMapper.countIsSettle(pkGlorgbook,period);//查询已结账数目
		if(count>0) {
			return new RestfulResponse<List<CwGlTransferExecDetail>, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE.message(),
					MetaDataUtil.getMeta(tracer,FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE));
		}
		long i=cwGlVoucherMapper.countNotBooking(pkGlorgbook, period);//当前账套期间下的凭证是否所有都已记账
		if(i>0) {
			return new RestfulResponse<List<CwGlTransferExecDetail>, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.EXISTENCE_OF_UNRECORDED.message(),
					MetaDataUtil.getMeta(tracer,FinanceStatusCode.EXISTENCE_OF_UNRECORDED));
		}
		//根据结转方案主键获取所有的结转方案明细
		CwGlTransferdetailExample cwGlTransferdetailExample = new CwGlTransferdetailExample();
		Criteria createCriteria = cwGlTransferdetailExample.createCriteria();
		createCriteria.andPkTransferEqualTo(pkTransfer);
		createCriteria.andUseStateEqualTo(FinanceDictConsts.Syzt.EFFECTIVE);
		List<CwGlTransferdetail> transferList = cwGlTransferdetailMapper.selectByExample(cwGlTransferdetailExample);

		for (CwGlTransferdetail cwGlTransferdetail : transferList) {
			String pkSrcaccsubj = cwGlTransferdetail.getPkSrcaccsubj();//来源科目
			String orientation = cwGlTransferdetail.getOrientation();//方向
			List<String> subjectList=cwBdAccsubjMapper.selectParentSubject(pkSrcaccsubj,pkSubjscheme);//查询科目的所有子级科目
		    List<CwGlTransferExecDetail> balanceList = 
		    		cwGlBalanceMapper.searchBalanceForIncome(pkGlorgbook,period,orientation,subjectList);
		    if(balanceList.size()>0&&(StringUtils.isEmpty(balanceList.get(0).getSubjcode())||"0.00".equals(balanceList.get(0).getBalance()))) {
		    	continue;
		    }
		    list.addAll(balanceList);	
		}
		return new RestfulResponse<List<CwGlTransferExecDetail>, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,list,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	}


	/*
	 * (非 Javadoc)  
	 * <p>Title: updateCwGlTransferExecForProfit</p>  
	 * <p>Description: 利润结转 </p>
	 * @param cwGlTransferExecs
	 * @return  
	 * @see com.dhcc.finance.main.service.CwGlTransferExecService#updateCwGlTransferExecForProfit(java.util.List)    
	 * @author huangpeng
	 * @date 2019年10月13日 上午10:55:32
	 * @修改日志：
	 */
	@Override
	public RestfulResponse<Object, CurrencyMeta> updateCwGlTransferExecForProfit(
			List<CwGlTransferWeb> cwGlTransferExecs) {
		SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
		if(sysUserInfo==null) {
			return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,SysStatusCode.USER_LOGOUT_ERROR.message(),MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
		}
		for (CwGlTransferWeb CwGlTransferExec : cwGlTransferExecs) {
			String pkGlorgbook=CwGlTransferExec.getPkGlorgbook();//结转方案账套主键
			String period = CwGlTransferExec.getPkCurrperiod();//期间
			List<CwGlTransferExec> selectPkTransfer = cwGlTransferExecMapper.selectPkTransfer(pkGlorgbook,period);
			if(selectPkTransfer.size()==0) {
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.CURRENT_PERIOD_CARRY_FORWARD.message(),
						MetaDataUtil.getMeta(tracer,FinanceStatusCode.CURRENT_PERIOD_CARRY_FORWARD));
			}
			String pkTransferExec = selectPkTransfer.get(0).getPkTransferExec();
			//根据账套主键查询账套内容
			CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(pkGlorgbook);
			String pkTransfer = cwBdGlorgbook.getPkTransfer();//结转主键
			long count=cwGlSettleMapper.countIsSettle(pkGlorgbook,period);//查询已结账数目
			if(count>0) {
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE.message(),
						MetaDataUtil.getMeta(tracer,FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE));
			}
			long i=cwGlVoucherMapper.countNotBooking(pkGlorgbook, period);//当前账套期间下的凭证是否所有都已记账
			if(i>0) {
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.EXISTENCE_OF_UNRECORDED.message(),
						MetaDataUtil.getMeta(tracer,FinanceStatusCode.EXISTENCE_OF_UNRECORDED));
			}
			//根据结转方案主键获取所有的结转方案明细
			CwGlTransferdetailExample cwGlTransferdetailExample = new CwGlTransferdetailExample();
			Criteria createCriteria = cwGlTransferdetailExample.createCriteria();
			createCriteria.andPkTransferEqualTo(pkTransfer);
			createCriteria.andUseStateEqualTo(FinanceDictConsts.Syzt.EFFECTIVE);
			List<CwGlTransferdetail> list = cwGlTransferdetailMapper.selectByExample(cwGlTransferdetailExample);
			List<CwGlVoucher> cwGlVoucherList=new ArrayList<CwGlVoucher>();//凭证集合用于批量审核、批量记账
			//遍历结转方案明细表 生成凭证
			RestfulResponse<Object, CurrencyMeta> res1 = addVoucherForTransfer(sysUserInfo,list,period,cwBdGlorgbook,pkTransferExec,cwGlVoucherList,false);
			if(res1!=null) {
				if(cwGlVoucherList.size()>0) {
					cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVoucherList);
				}
				return res1;
			}
			//自动审核、记账
			if(cwGlVoucherList.size()>0) {
				RestfulResponse<Object, CurrencyMeta> res = automaticAuditAndSign(cwGlVoucherList);
				if(res!=null) {
					cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVoucherList);
					return res;
				}
			}
			if(cwGlVoucherList.size()>0) {
				List<CwGlTransfervouch> cwGlTransfervouchList=new ArrayList<CwGlTransfervouch>();
				for (CwGlVoucher cwGlVoucher : cwGlVoucherList) {
					//生成结转凭证明细表
					CwGlTransfervouch cwGlTransfervouch = new CwGlTransfervouch();
					cwGlTransfervouch.setPkTransfervouch(SnowflakeIdWorker.getInstance().nextIdString());
					cwGlTransfervouch.setPkTransferExec(pkTransferExec);
					cwGlTransfervouch.setPkVoucher(cwGlVoucher.getPkVoucher());
					cwGlTransfervouch.setPkTransfer(pkTransfer);
					cwGlTransfervouch.setCreateUser(sysUserInfo.getUserId());
					cwGlTransfervouch.setCreateTime(new Date());
					cwGlTransfervouch.setUpdateTime(new Date());
					cwGlTransfervouch.setUpdateUser(sysUserInfo.getUserId());
					cwGlTransfervouch.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
					cwGlTransfervouchList.add(cwGlTransfervouch);

				}
				cwGlTransfervouchMapper.insertForBatch(cwGlTransfervouchList);//增加结转凭证明细数据
			}
			
		}
		return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	}
	/**
	 * 功能描述 自动审核
	 *@param cwGlVoucherList
	 *@return RestfulResponse<Object,CurrencyMeta>
	 *@author huangpeng
	 *@date 2019年10月13日 上午11:09:57
	 *修改日志:
	 */
	private RestfulResponse<Object, CurrencyMeta> automaticAuditAndSign(List<CwGlVoucher> cwGlVoucherList) {
		SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
		// 查询是否自动审核
		CwBdParametric audit = cwBdParametricMapper.searchCwBdParametricByCode("1003");
		// 查询是否自动记账
		CwBdParametric sign = cwBdParametricMapper.searchCwBdParametricByCode("1004");
		if (audit != null && FinanceDictConsts.Syzt.EFFECTIVE.equals(audit.getParametricValue())) {
			// 查询自动审核记账人员配置
			List<CwBdAccounting> selectCwBdAccountingByLikes = cwBdAccountingMapper.selectCwBdAccountingByLikes(sysUserInfo.getUserId());
			if (selectCwBdAccountingByLikes.isEmpty()) {
				cwGlVoucherService.deleteCwGlVoucherForBatch(cwGlVoucherList);
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.GET_ACCOUNTING_ERROR.message(),
						MetaDataUtil.getMeta(tracer, FinanceStatusCode.GET_ACCOUNTING_ERROR));
			}
			for (CwGlVoucher cwGlVoucher : cwGlVoucherList) {
				cwGlVoucher.setPkAudit(selectCwBdAccountingByLikes.get(0).getPkAudit());
			}
			RestfulResponse<Object, CurrencyMeta> res1 = cwGlVoucherService
					.updateCwGlVoucherByPkForBatch(cwGlVoucherList);// 审核
			if (SysConstants.CODE.FAIL == res1.getCode().intValue()) {
				return res1;
			}
			if (sign != null && sign.getParametricValue().equals(FinanceDictConsts.Syzt.EFFECTIVE)) {
				for (CwGlVoucher cwGlVoucher : cwGlVoucherList) {
					cwGlVoucher.setPkSign(selectCwBdAccountingByLikes.get(0).getPkSign());
				}
				RestfulResponse<Object, CurrencyMeta> res2 = cwGlVoucherService
						.updateCwGlVoucherForBookingBatch(cwGlVoucherList);// 记账
				if (SysConstants.CODE.FAIL == res2.getCode().intValue()) {
					return res2;
				}
			}
		}
		return null;
	}
	/**
	 * 功能描述 生成结转凭证
	 *@param list
	 *@param period
	 *@param cwBdGlorgbook
	 *@param transferExec
	 *@param cwGlVoucherList
	 *@return RestfulResponse<Object,CurrencyMeta>
	 *@author huangpeng
	 * @param type 
	 *@date 2019年10月13日 下午12:05:04
	 *修改日志:
	 */
	private RestfulResponse<Object, CurrencyMeta> addVoucherForTransfer(SysUserInfo sysUserInfo,List<CwGlTransferdetail> list,String period,CwBdGlorgbook cwBdGlorgbook,
			String transferExec,List<CwGlVoucher> cwGlVoucherList, boolean type) {
		String pkGlorgbook=cwBdGlorgbook.getPkGlorgbook();
		String pkSubjscheme = cwBdGlorgbook.getPkSubjscheme();//科目版本
		//遍历结转方案明细表
		for (CwGlTransferdetail cwGlTransferdetail : list) {
			if(type) {//损益结转
				if(FinanceDictConsts.Cwzzlx.LRZJ.equals(cwGlTransferdetail.getTransfertype())) {
					continue;
				}
			}else {//利润结转
				if(FinanceDictConsts.Cwzzlx.SYZZ.equals(cwGlTransferdetail.getTransfertype())) {
					continue;
				}
			}
			//转账频度校验 月：正常  季度：期间3,6,9,12半年:6,12, 年:12
			String zzpd=cwGlTransferdetail.getTransfrequency();
			String[] periodArr = period.split("-");
			String beginMonth=periodArr[1];
			String minPeriod=null;
			if(FinanceDictConsts.ZZPD.SEASON.equals(zzpd)) {//季
				beginMonth = cwBdAccperiodquartMapper.countPeridIsExists(periodArr[0], periodArr[1]);
				if(StringUtils.isBlank(beginMonth)) {
					continue;
				}
			}else if(FinanceDictConsts.ZZPD.HALFYEAR.equals(zzpd)) {//半年
				beginMonth = cwBdAccperiodyearMapper.selectHalfYearIsExists(periodArr[0], periodArr[1]);
				if(StringUtils.isBlank(beginMonth)) {
					continue;
				}
			}else if(FinanceDictConsts.ZZPD.YEAR.equals(zzpd)) {//年
				if(!"12".equals(periodArr[1])) {
					continue;
				}
					beginMonth="01";
			}
			if(FinanceDictConsts.JZSX.FSE.equals(cwGlTransferdetail.getTranssystem())) {//发生额区间
				minPeriod=periodArr[0]+"-"+beginMonth;					  
			 }else {
				minPeriod=periodArr[0]+"-00";
			 }
			String pkSrcaccsubj = cwGlTransferdetail.getPkSrcaccsubj();//来源科目主键
			if(!"12".equals(periodArr[1])) {
				CwBdAccsubj cwBdAccsubj = cwBdAccsubjMapper.selectByPrimaryKey(pkSrcaccsubj);//查询来源科目详情
				if("400301".equals(cwBdAccsubj.getSubjcode())||"400302".equals(cwBdAccsubj.getSubjcode())) {
					continue;
				}
			}
			List<String> subjectList=cwBdAccsubjMapper.selectParentSubject(pkSrcaccsubj,pkSubjscheme);//查询科目的所有子级科目

			
			List<String> fqmjbhList = cwGlBalanceMapper.selectFqmjbhForTransfer(pkGlorgbook,minPeriod,period,subjectList);//查询分期号
			if(fqmjbhList.size()==0) {
				continue;
			}
			String pkDesaccsubj = cwGlTransferdetail.getPkDesaccsubj();//目的科目主键
			CwBdAccsubj selectByPrimaryKey = cwBdAccsubjMapper.selectByPrimaryKey(pkDesaccsubj);//查询目的科目详情
			for (String fqmjbh : fqmjbhList) {
				if(StringUtils.isBlank(fqmjbh)) {
					fqmjbh=null;
				}
				CwGlVoucherWeb cwGlVoucherWeb = new CwGlVoucherWeb();//生成凭证实体类
				cwGlBalanceMapper.deleteBalanceforTransfer(pkGlorgbook,period,fqmjbh,subjectList);//删除科目余额表
				cwGlBalanceMapper.insertBalanceforTransfer(pkGlorgbook,period,fqmjbh,subjectList);//插入科目余额表
//				CwGlBalance sumCwGlBalance=
//						cwGlBalanceMapper.selectCwGlBalanceBytransfer(pkGlorgbook,period,minPeriod,fqmjbh,subjectList);//查询总额
//			if(sumCwGlBalance!=null) {
//				if("1".equals(cwGlTransferdetail.getOrientation())) {//根据借贷方向来设置凭证总额
//					cwGlVoucherWeb.setTotalcredit(sumCwGlBalance.getLocalcreditamount().subtract(sumCwGlBalance.getLocaldebitamount()));
//					cwGlVoucherWeb.setTotaldebit(sumCwGlBalance.getLocalcreditamount().subtract(sumCwGlBalance.getLocaldebitamount()));
//				}else {
//					cwGlVoucherWeb.setTotalcredit(sumCwGlBalance.getLocaldebitamount().subtract(sumCwGlBalance.getLocalcreditamount()));
//					cwGlVoucherWeb.setTotaldebit(sumCwGlBalance.getLocaldebitamount().subtract(sumCwGlBalance.getLocalcreditamount()));
//				}	
//			}
				//获取当前最大凭证号
				// CwGlVouchermaxno selectGetMaxNo = cwGlVouchermaxnoMapper.selectGetMaxNo(pkGlorgbook, period);
				CwGlVouchermaxno selectGetMaxNo = cwGlVouchermaxnoMapper.getVoucherMaxNo(pkGlorgbook, period);
				if(selectGetMaxNo!=null) {
					cwGlVoucherWeb.setVoucherno(Integer.valueOf(selectGetMaxNo.getMaxno())+1+"");
				}else {
					// 如果查询不到则返回
					return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,cwBdGlorgbook.getName()+FinanceStatusCode.MAXNO_INFO_NOTFOUND.message(),
							MetaDataUtil.getMeta(tracer,FinanceStatusCode.MAXNO_INFO_NOTFOUND));
				}
				//新增凭证设置内容 
				String pkVoucher = SnowflakeIdWorker.getInstance().nextIdString();//得到共用的凭证主键
				cwGlVoucherWeb.setPkVoucher(pkVoucher);
				cwGlVoucherWeb.setPkGlorgbook(pkGlorgbook);
				cwGlVoucherWeb.setFqmjbh(fqmjbh);
				cwGlVoucherWeb.setPkVoucherty(FinanceDictConsts.Cwpzlx.JIEZPZ);
				cwGlVoucherWeb.setVouchertype(FinanceDictConsts.Cwpzzt.YZD);
				cwGlVoucherWeb.setPkPrepared(sysUserInfo.getUserId());
				cwGlVoucherWeb.setAbstracts(type?"损益结转":"利润结转");
				// upd 2019/10/22设置制单日期如果当前时间在该期间内就用当前时间，如果不在则用会计期间最后一天
				String period2 = FinanceDateUtil.getPeriod(new Date());
				if (period2.equals(period)) {
					cwGlVoucherWeb.setPreparedate(new Date());
					cwGlVoucherWeb.setOccDate(new Date());
				} else {
					Date monthLastDayDate = FinanceDateUtil.getMonthLastDayDate(period);
					cwGlVoucherWeb.setPreparedate(monthLastDayDate);
					cwGlVoucherWeb.setOccDate(monthLastDayDate);
				}
				cwGlVoucherWeb.setPeriod(period);
				cwGlVoucherWeb.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
				cwGlVoucherWeb.setCreateUser(sysUserInfo.getUserId());
				cwGlVoucherWeb.setCreateTime(new Date());
				cwGlVoucherWeb.setUpdateUser(sysUserInfo.getUserId());
				cwGlVoucherWeb.setUpdateTime(new Date());
				cwGlVoucherWeb.setPkSystem(FinanceDictConsts.LYXT.YWXT);
				//凭证分录明细List
				List<CwGlDetailWeb> cwGlDetailList = new ArrayList<CwGlDetailWeb>();
				//根据科目余额表查询分录信息
				List<CwGlBalance> cwGlBalanceList = cwGlBalanceMapper.selectByForTransfer(pkGlorgbook,period,minPeriod,fqmjbh,subjectList);
				if(cwGlBalanceList.size()==0) {//不存在来源分录信息
					continue;
//					return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.DETAILE_INFORMATION_NOTFOUND.message(),
//							MetaDataUtil.getMeta(tracer,FinanceStatusCode.DETAILE_INFORMATION_NOTFOUND));
				}
				BigDecimal totaldebit = new BigDecimal("0"),totalcredit = new BigDecimal("0");
				for (CwGlBalance cwGlBalance2 : cwGlBalanceList) {//遍历来添加凭证分录
				 CwGlDetailWeb cwGlDetailWeb = new CwGlDetailWeb();
				 if("1".equals(cwGlTransferdetail.getOrientation())) {//借，则贷-借 结果放借上边
					 cwGlDetailWeb.setDebitamount(cwGlBalance2.getLocalcreditamount().subtract(cwGlBalance2.getLocaldebitamount()));
					 cwGlDetailWeb.setLocaldebitamount(cwGlBalance2.getLocalcreditamount().subtract(cwGlBalance2.getLocaldebitamount()));
					 cwGlDetailWeb.setCreditamount(new BigDecimal("0"));
					 cwGlDetailWeb.setLocalcreditamount(new BigDecimal("0"));
					 totaldebit = totaldebit.add(cwGlBalance2.getLocalcreditamount().subtract(cwGlBalance2.getLocaldebitamount()));
					 totalcredit = totalcredit.add(cwGlBalance2.getLocalcreditamount().subtract(cwGlBalance2.getLocaldebitamount()));
				 }else {//贷，则相反
					 cwGlDetailWeb.setCreditamount(cwGlBalance2.getLocaldebitamount().subtract(cwGlBalance2.getLocalcreditamount()));
					 cwGlDetailWeb.setLocalcreditamount(cwGlBalance2.getLocaldebitamount().subtract(cwGlBalance2.getLocalcreditamount()));
					 cwGlDetailWeb.setDebitamount(new BigDecimal("0"));
					 cwGlDetailWeb.setLocaldebitamount(new BigDecimal("0"));
					 totaldebit = totaldebit.add(cwGlBalance2.getLocaldebitamount().subtract(cwGlBalance2.getLocalcreditamount()));
					 totalcredit = totalcredit.add(cwGlBalance2.getLocaldebitamount().subtract(cwGlBalance2.getLocalcreditamount()));
			     }
				 cwGlDetailWeb.setPkAccsubj(cwGlBalance2.getPkAccsubj());
				 cwGlDetailWeb.setSubjname(cwGlBalance2.getSubjname());
				 cwGlDetailWeb.setSubjcode(cwGlBalance2.getSubjcode());
				 cwGlDetailWeb.setAssid(cwGlBalance2.getAssid());
				 cwGlDetailWeb.setPkCurrtype(cwGlBalance2.getPkCurrtype());
				 cwGlDetailWeb.setPkVoucher(pkVoucher);
				 cwGlDetailWeb.setAbstracts(type?"损益结转":"利润结转");
				 cwGlDetailWeb.setPkDetail(SnowflakeIdWorker.getInstance().nextIdString());
				// TODO 如果分录金额为0就过滤掉
				 if (cwGlDetailWeb.getLocalcreditamount().compareTo(BigDecimal.ZERO) != 0 || cwGlDetailWeb.getLocaldebitamount().compareTo(BigDecimal.ZERO) != 0) {
						cwGlDetailList.add(cwGlDetailWeb);
					}
				}
				//增加目的科目分录信息
				CwGlDetailWeb cwGlDetailWeb1 = new CwGlDetailWeb();
				cwGlDetailWeb1.setPkVoucher(pkVoucher);
				cwGlDetailWeb1.setPkDetail(SnowflakeIdWorker.getInstance().nextIdString());
				cwGlDetailWeb1.setPkAccsubj(pkDesaccsubj);
				cwGlDetailWeb1.setSubjcode(selectByPrimaryKey.getSubjcode());
				cwGlDetailWeb1.setSubjname(selectByPrimaryKey.getSubjname());
				if("1".equals(cwGlTransferdetail.getOrientation())) {//借，则设置贷方金额
						cwGlDetailWeb1.setCreditamount(totalcredit);
						cwGlDetailWeb1.setLocalcreditamount(totalcredit);
						cwGlDetailWeb1.setDebitamount(new BigDecimal("0"));
						cwGlDetailWeb1.setLocaldebitamount(new BigDecimal("0"));
				}else {//贷，则设置借方金额
						cwGlDetailWeb1.setDebitamount(totaldebit);
						cwGlDetailWeb1.setLocaldebitamount(totaldebit);
						cwGlDetailWeb1.setCreditamount(new BigDecimal("0"));
						cwGlDetailWeb1.setLocalcreditamount(new BigDecimal("0"));
				}
				cwGlDetailWeb1.setPkCurrtype("CNY");
				cwGlDetailWeb1.setAbstracts(type?"损益结转":"利润结转");
				cwGlDetailWeb1.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
				cwGlDetailWeb1.setCreateUser(sysUserInfo.getUserId());
				cwGlDetailWeb1.setCreateTime(new Date());
				cwGlDetailWeb1.setUpdateUser(sysUserInfo.getUserId());
				cwGlDetailWeb1.setUpdateTime(new Date());
				
				// TODO 如果分录金额为0就过滤掉
				if (cwGlDetailWeb1.getLocalcreditamount().compareTo(BigDecimal.ZERO) != 0 || cwGlDetailWeb1.getLocaldebitamount().compareTo(BigDecimal.ZERO) != 0) {
					cwGlDetailList.add(cwGlDetailWeb1);
				}
				if(cwGlDetailList.size()==0) {//分录上的金额借贷都为零
					continue;
				}
				cwGlVoucherWeb.setTotalcredit(totalcredit);
				cwGlVoucherWeb.setTotaldebit(totaldebit);
				//生成结转凭证
				cwGlVoucherWeb.setCwGlDetailList(cwGlDetailList);

				RestfulResponse<Object, CurrencyMeta> addCwGlVoucher = cwGlVoucherService.addCwGlVoucher(cwGlVoucherWeb);//调用生成凭证接口
				//生成凭证判断结果
				if (SysConstants.CODE.SUCCESS == addCwGlVoucher.getCode().intValue()) {
							
					//用于审核记账
					CwGlVoucher cwGlVoucher = new CwGlVoucher();
   				    BeanUtils.copyProperties(cwGlVoucherWeb, cwGlVoucher);
					cwGlVoucherList.add(cwGlVoucher);
				}else {
					return addCwGlVoucher;
				}
				
			}
		}
		return null;
	}
}
