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

import brave.Tracer;
import com.dhcc.common.Shift;
import com.dhcc.common.constant.FinanceStatusCode;
import com.dhcc.common.constant.SysConstants;
import com.dhcc.common.constant.SysStatusCode;
import com.dhcc.common.constant.enums.UsestateEnum;
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.IdGenerator;
import com.dhcc.common.util.SnowflakeIdWorker;
import com.dhcc.finance.constant.FinanceDictConsts;
import com.dhcc.finance.main.dao.*;
import com.dhcc.finance.main.domain.CwGlFreevalue;
import com.dhcc.finance.main.domain.*;
import com.dhcc.finance.main.domain.CwGlVouchermaxnoExample.Criteria;
import com.dhcc.finance.main.model.*;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.DefaultDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能描述：凭证信息实现类
 *
 * @author dml
 * @date 2019年3月28日 下午4:17:24
 * @修改日志：
 */
@Slf4j
@Service
public class CwGlVoucherServiceImpl implements CwGlVoucherService {
    @Autowired
    private Tracer tracer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    CwGlVoucherMapper cwGlVoucherMapper;//凭证信息

    @Autowired
    CwGlDetailMapper cwGlDetailMapper;//凭证分录信息

    @Autowired
    CwGlFreevalueMapper CwGlFreevalueMapper;//辅助标识表

    @Autowired
    CwGlVouchermaxnoMapper cwGlVouchermaxnoMapper;//最大凭证号

    @Autowired
    CwGlBalanceMapper cwGlBalanceMapper;//辅助余额表
    @Autowired
    CwGlSettleMapper cwGlSettleMapper;// 结账信息表
    @Autowired
    CwBdGlorgbookMapper cwBdGlorgbookMapper;//账套表
    @Autowired
    CwReverseOperationMapper cwReverseOperationMapper;//反向操作
    @Autowired
    CwBdAccassitemMapper cwBdAccassitemMapper;//辅助项表
    @Autowired
    CwBdRecordSerialMapper cwBdRecordSerialMapper;//记录流水凭证表
    @Autowired
    CwBdRecordNcpushMapper cwBdRecordNcpushMapper;//记录推送nc表
    @Autowired
    PmProjectChildMapper pmProjectChildMapper;//子项目表

    @Value("${dhcc.nc.pushVoucherInterface}")
    private String pushVoucherInterface;// nc接口

    /*
     * (非 Javadoc)
     * <p>Title: searchCwGlVoucherAllData</p>
     * <p>Description:查询全部凭证信息 </p>
     * @param pageNum
     * @param pageSize
     * @param navigatePages
     * @param cwGlVoucherAndLike
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#searchCwGlVoucherAllData(int, int, int, com.dhcc.finance.main.model.CwGlVoucherAndLike)
     * @author huangpeng
     * @date 2019年10月15日 下午4:26:11
     * @修改日志：
     */
    @Override
    public RestfulResponse<PageInfo<CwGlVoucherAndName>, CurrencyMeta> searchCwGlVoucherAllData(int pageNum, int pageSize,
                                                                                                int navigatePages, CwGlVoucherAndLike cwGlVoucherAndLike) {
        PageHelper.startPage(pageNum, pageSize);
        List<CwGlVoucherAndName> listCwGlVoucher = cwGlVoucherMapper.selectOrderMaking(cwGlVoucherAndLike);
        PageInfo<CwGlVoucherAndName> pageInfo = new PageInfo<>(listCwGlVoucher, navigatePages);
        return new RestfulResponse<PageInfo<CwGlVoucherAndName>, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, pageInfo, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * Title: addCwGlVoucher
     * Description:新增凭证信息
     * @param cwGlVoucher
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#addCwGlVoucher(com.dhcc.finance.main.domain.CwGlVoucher)
     * @author dml
     * @date 2019年3月28日 下午4:36:36
     * @修改日志：
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestfulResponse<Object, CurrencyMeta> addCwGlVoucher(CwGlVoucherWeb cwGlVoucherWeb) {
        if (cwGlVoucherWeb.chackData()) {
            log.info("业务数据校验不通过>>>" + cwGlVoucherWeb);
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, SysStatusCode.SERVER_CHECK_ERROR.message(),
                    MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
        }
        //校验：该账套和期间已经结账则不允许操作
        long count = cwGlSettleMapper.countIsSettle(cwGlVoucherWeb.getPkGlorgbook(), cwGlVoucherWeb.getPeriod());
        if (count > 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE.message(),
                    MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
        }
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        if (sysUserInfo != null) {
            cwGlVoucherWeb.setCreateUser(sysUserInfo.getUserId());
        } else {
            cwGlVoucherWeb.setCreateUser(cwGlVoucherWeb.getPkPrepared());
        }
        cwGlVoucherWeb.setCreateTime(new Date());
        cwGlVoucherWeb.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
        cwGlVoucherWeb.setVouchertype(FinanceDictConsts.Cwpzzt.YZD);//已制单
        String pkVoucher;
        if (cwGlVoucherWeb.getPkVoucher() != null) {//此判断在结转时会用到
            pkVoucher = cwGlVoucherWeb.getPkVoucher();
        } else {
            pkVoucher = SnowflakeIdWorker.getInstance().nextIdString();
        }
        cwGlVoucherWeb.setPkVoucher(pkVoucher);
        // 摘要设置
        String abstracts = StringUtils.isBlank(cwGlVoucherWeb.getAbstracts()) ? cwGlVoucherWeb.getCwGlDetailList().get(0).getAbstracts() : cwGlVoucherWeb.getAbstracts();
        cwGlVoucherWeb.setAbstracts(abstracts);
        // 设置业务发生日期 ,手工凭证就是当前时间，系统生成的传过来
        if (cwGlVoucherWeb.getOccDate() == null) {
            cwGlVoucherWeb.setOccDate(new Date());
        }
        // 新增凭证信息
        CwGlVoucher cwGlVoucher = new CwGlVoucher();
        BeanUtils.copyProperties(cwGlVoucherWeb, cwGlVoucher);
        if (StringUtils.isBlank(cwGlVoucher.getFqmjbh())) {// 如果没有分期统一为null
            cwGlVoucher.setFqmjbh(null);
        }
        int res1 = cwGlVoucherMapper.insert(cwGlVoucher);

        //修改最大凭证号表
        int res2 = 1;
        if (cwGlVoucherWeb.getIsManual() != null && "1".equals(cwGlVoucherWeb.getIsManual())) {
            res2 = updateVoucherMaxno(cwGlVoucherWeb);
        }
        //新增凭证分录信息
        List<CwGlDetail> cwGlDetailAddList = addCwGlDetailInfo(cwGlVoucherWeb);
        int res3 = cwGlDetailMapper.insertCwGlDetailBatch(cwGlDetailAddList);
        if (res1 * res2 * res3 == 0) {
            log.info(">>>>新增结果校验不通过抛出异常让事务回滚");
            Shift.fatalThrow(SysStatusCode.OPERATION_FAIL);
        }
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, cwGlVoucher.getPkVoucher(),
                MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /**
     * 功能描述：新增凭证List
     * @param cwGlVoucherWebList
     * @return RestfulResponse<Object, CurrencyMeta>
     * @author leiyu
     * @date 2020年7月10日 下午9:29:20
     */
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<Object, CurrencyMeta> addCwGlVoucherList(List<CwGlVoucherWeb> cwGlVoucherWebList) {
    	List<String> pkVoucherList = new ArrayList<String>();
    	for(CwGlVoucherWeb cwGlVoucherWeb : cwGlVoucherWebList) {
    		if (cwGlVoucherWeb.chackData()) {
                log.info("业务数据校验不通过>>>" + cwGlVoucherWeb);
                return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, SysStatusCode.SERVER_CHECK_ERROR.message(),
                        MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
            }
            //校验：该账套和期间已经结账则不允许操作
            long count = cwGlSettleMapper.countIsSettle(cwGlVoucherWeb.getPkGlorgbook(), cwGlVoucherWeb.getPeriod());
            if (count > 0) {
                return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.GLORGBOOK_HAS_BEEN_SETTLE.message(),
                        MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
            }
            SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
            if (sysUserInfo != null) {
                cwGlVoucherWeb.setCreateUser(sysUserInfo.getUserId());
            } else {
                cwGlVoucherWeb.setCreateUser(cwGlVoucherWeb.getPkPrepared());
            }
            cwGlVoucherWeb.setCreateTime(new Date());
            cwGlVoucherWeb.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
            cwGlVoucherWeb.setVouchertype(FinanceDictConsts.Cwpzzt.YZD);//已制单
            String pkVoucher;
            if (cwGlVoucherWeb.getPkVoucher() != null) {//此判断在结转时会用到
                pkVoucher = cwGlVoucherWeb.getPkVoucher();
            } else {
                pkVoucher = SnowflakeIdWorker.getInstance().nextIdString();
            }
            cwGlVoucherWeb.setPkVoucher(pkVoucher);
            // 摘要设置
            String abstracts = StringUtils.isBlank(cwGlVoucherWeb.getAbstracts()) ? cwGlVoucherWeb.getCwGlDetailList().get(0).getAbstracts() : cwGlVoucherWeb.getAbstracts();
            cwGlVoucherWeb.setAbstracts(abstracts);
            // 设置业务发生日期 ,手工凭证就是当前时间，系统生成的传过来
            if (cwGlVoucherWeb.getOccDate() == null) {
                cwGlVoucherWeb.setOccDate(new Date());
            }
            // 新增凭证信息
            CwGlVoucher cwGlVoucher = new CwGlVoucher();
            BeanUtils.copyProperties(cwGlVoucherWeb, cwGlVoucher);
            if (StringUtils.isBlank(cwGlVoucher.getFqmjbh())) {// 如果没有分期统一为null
                cwGlVoucher.setFqmjbh(null);
            }
            int res1 = cwGlVoucherMapper.insert(cwGlVoucher);

            //修改最大凭证号表
            int res2 = 1;
            if (cwGlVoucherWeb.getIsManual() != null && "1".equals(cwGlVoucherWeb.getIsManual())) {
                res2 = updateVoucherMaxno(cwGlVoucherWeb);
            }
            //新增凭证分录信息
            List<CwGlDetail> cwGlDetailAddList = addCwGlDetailInfo(cwGlVoucherWeb);
            int res3 = cwGlDetailMapper.insertCwGlDetailBatch(cwGlDetailAddList);
            if (res1 * res2 * res3 == 0) {
                log.info(">>>>新增结果校验不通过抛出异常让事务回滚");
                Shift.fatalThrow(SysStatusCode.OPERATION_FAIL);
            }
            pkVoucherList.add(cwGlVoucher.getPkVoucher());
    	}
    	String pkVoucherString = new String();
		for (String pk : pkVoucherList) {
			pkVoucherString = pkVoucherString+pk+",";
		}
		pkVoucherString = pkVoucherString.substring(0, pkVoucherString.length()-1);
    	return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, pkVoucherString,
                MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }


    /*
     * (非 Javadoc)
     * Title: updateCwGlVoucherByPk
     * Description:修改凭证信息
     * @param cwGlVoucher
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateCwGlVoucherByPk(com.dhcc.finance.main.domain.CwGlVoucher)
     * @author dml
     * @date 2019年3月28日 下午4:36:43
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> updateCwGlVoucherByPk(CwGlVoucher cwGlVoucher) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        if (sysUserInfo != null) {
            cwGlVoucher.setUpdateUser(sysUserInfo.getUserId());
        }
        cwGlVoucher.setUpdateTime(new Date());
        cwGlVoucherMapper.updateByPrimaryKeySelective(cwGlVoucher);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * Title: deleteCwGlVoucherByPk
     * Description:逻辑删除凭证信息
     * @param pkVoucher
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#deleteCwGlVoucherByPk(java.lang.String)
     * @author dml
     * @date 2019年3月28日 下午4:36:56
     * @修改日志：
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<Object, CurrencyMeta> deleteCwGlVoucherByPk(String pkVoucher) {
        CwGlVoucher cwGlVoucher = new CwGlVoucher();
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        if (sysUserInfo != null) {
            cwGlVoucher.setUpdateUser(sysUserInfo.getUserId());
        }
        cwGlVoucher.setUpdateTime(new Date());
        cwGlVoucher.setUseState(FinanceDictConsts.Syzt.INVALID);
        cwGlVoucher.setPkVoucher(pkVoucher);
        cwGlVoucherMapper.updateByPrimaryKeySelective(cwGlVoucher);
        // 分录信息
        CwGlDetail cwGlDetail = new CwGlDetail();
        if (sysUserInfo != null) {
            cwGlDetail.setUpdateUser(sysUserInfo.getUserId());
        }
        cwGlDetail.setUpdateTime(new Date());
        cwGlDetail.setUseState(FinanceDictConsts.Syzt.INVALID);
        cwGlDetail.setPkVoucher(pkVoucher);
        cwGlDetailMapper.deleteByPkVoucherLogic(cwGlDetail);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }
    /* (非 Javadoc)
     * <p>Title: updateCwGlVoucherByPkForBatch</p>
     * <p>Description: 批量审核凭证</p>
     * @param cwGlVouchers
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateCwGlVoucherByPkForBatch(java.util.List)
     * @author huangpeng
     * @date 2019年4月1日 下午3:38:45
     * @修改日志：
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<Object, CurrencyMeta> updateCwGlVoucherByPkForBatch(List<CwGlVoucher> cwGlVouchers) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        for (CwGlVoucher cwGlVoucher : cwGlVouchers) {
            CwGlVoucher voucher = new CwGlVoucher();
            //校验：该账套和期间已经结账则不允许操作
            long count = cwGlSettleMapper.countIsSettle(cwGlVoucher.getPkGlorgbook(), cwGlVoucher.getPeriod());
            if (count > 0) {
                CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(cwGlVoucher.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));
            }
            //校验：审核人与制单人不能相同
            if (sysUserInfo != null || cwGlVoucher.getPkAudit() != null) {
                if (sysUserInfo != null) {
                    voucher.setUpdateUser(sysUserInfo.getUserId());
                }
                // 区分页面点击还是自动审批
                String pkAudit = StringUtils.isBlank(cwGlVoucher.getPkAudit()) ? sysUserInfo.getUserId() : cwGlVoucher.getPkAudit();
                if (pkAudit.equals(cwGlVoucher.getPkPrepared())) {
                    return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.PKPREPARED_THESAME_PKAUDIT.message(),
                            MetaDataUtil.getMeta(tracer, FinanceStatusCode.PKPREPARED_THESAME_PKAUDIT));
                } else {
                    voucher.setPkAudit(pkAudit);
                }
            } else {
                return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, SysStatusCode.USER_LOGOUT_ERROR.message(), MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
            }
            voucher.setPkVoucher(cwGlVoucher.getPkVoucher());
            voucher.setUpdateTime(new Date());
            voucher.setAuditdate(new Date());
            voucher.setIsaudit("1");
            voucher.setVouchertype(FinanceDictConsts.Cwpzzt.YSH);
            cwGlVoucherMapper.updateByPrimaryKeySelective(voucher);
        }
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: searchCwGlVoucherForAudit</p>
     * <p>Description:获取审核列表信息 </p>
     * @param pageNum
     * @param pageSize
     * @param navigatePages
     * @param cwGlVoucherAndLike
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#searchCwGlVoucherForAudit(int, int, int, com.dhcc.finance.main.model.CwGlVoucherAndLike)
     * @author huangpeng
     * @date 2019年10月15日 下午4:26:33
     * @修改日志：
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<PageInfo<CwGlVoucherAndName>, CurrencyMeta> searchCwGlVoucherForAudit(int pageNum, int pageSize, int navigatePages, CwGlVoucherAndLike cwGlVoucherAndLike) {
        PageHelper.startPage(pageNum, pageSize);
        List<CwGlVoucherAndName> list = cwGlVoucherMapper.selectForAuditByLike(cwGlVoucherAndLike);
        PageInfo<CwGlVoucherAndName> pageInfo = new PageInfo<>(list, navigatePages);
        return new RestfulResponse<PageInfo<CwGlVoucherAndName>, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, pageInfo, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /* (非 Javadoc)
     * <p>Title: searchCwGlVoucherForBooking</p>
     * <p>Description: 获取记账列表信息</p>
     * @param vouchernoLike
     * @param pageNum
     * @param pageSize
     * @param navigatePages
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#searchCwGlVoucherForBooking(java.lang.String, int, int, int)
     * @author huangpeng
     * @date 2019年4月1日 下午5:35:18
     * @修改日志：
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<PageInfo<CwGlVoucherAndName>, CurrencyMeta> searchCwGlVoucherForBooking(
            int pageNum, int pageSize, int navigatePages, CwGlVoucherAndLike cwGlVoucherAndLike) {
        PageHelper.startPage(pageNum, pageSize);
        List<CwGlVoucherAndName> list = cwGlVoucherMapper.selectForBookingByLike(cwGlVoucherAndLike);
        PageInfo<CwGlVoucherAndName> pageInfo = new PageInfo<>(list, navigatePages);
        return new RestfulResponse<PageInfo<CwGlVoucherAndName>, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, pageInfo, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /* (非 Javadoc)
     * <p>Title: updateCwGlVoucherForBookingBatch</p>
     * <p>Description: 批量更新记账信息</p>
     * @param cwGlVouchers
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateCwGlVoucherForBookingBatch(java.util.List)
     * @author huangpeng
     * @date 2019年4月1日 下午5:39:15
     * @修改日志：
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<Object, CurrencyMeta> updateCwGlVoucherForBookingBatch(List<CwGlVoucher> cwGlVouchers) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        for (CwGlVoucher cwGlVoucher : cwGlVouchers) {
            //校验：该账套和期间已经结账则不允许操作
            long count = cwGlSettleMapper.countIsSettle(cwGlVoucher.getPkGlorgbook(), cwGlVoucher.getPeriod());
            if (count > 0) {
                CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(cwGlVoucher.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));
            }
            CwGlVoucher voucher = new CwGlVoucher();
            if (sysUserInfo != null || StringUtils.isNotBlank(cwGlVoucher.getPkSign())) {
                if (sysUserInfo != null) {
                    voucher.setUpdateUser(sysUserInfo.getUserId());
                }
                // 用于区分页面点击和自动记账
                voucher.setPkSign(StringUtils.isBlank(cwGlVoucher.getPkSign()) ? sysUserInfo.getUserId() : cwGlVoucher.getPkSign());
            }
            voucher.setPkVoucher(cwGlVoucher.getPkVoucher());
            voucher.setUpdateTime(new Date());
            voucher.setSigndate(new Date());
            voucher.setIssign("1");
            voucher.setVouchertype(FinanceDictConsts.Cwpzzt.YJZ);
            cwGlVoucherMapper.updateByPrimaryKeySelective(voucher);
        }
        bookingBalanceCount(cwGlVouchers, true);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /**
     * 功能描述：记账反记账时修改辅助余额表
     *
     * @param cwGlVouchers
     * @param isBooking    true 记账 false 反记账
     * @author dml
     * @date 2019年4月19日 下午7:48:39
     * @修改日志：
     */
    private void bookingBalanceCount(List<CwGlVoucher> cwGlVouchers, boolean isBooking) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        for (CwGlVoucher cwGlVoucher : cwGlVouchers) {// 遍历凭证
            // 查询该凭证所有分录
            List<CwGlDetail> selectByPkVoucher = cwGlDetailMapper.selectByPkVoucher(cwGlVoucher.getPkVoucher(), FinanceDictConsts.Syzt.EFFECTIVE);
            for (CwGlDetail cwGlDetail : selectByPkVoucher) {
                CwGlBalance cwGlBalance = new CwGlBalance();
                cwGlBalance.setPkGlorgbook(cwGlVoucher.getPkGlorgbook());
                cwGlBalance.setPeriod(cwGlVoucher.getPeriod());
                cwGlBalance.setPkAccsubj(cwGlDetail.getPkAccsubj());
                cwGlBalance.setFqmjbh(cwGlVoucher.getFqmjbh());// 设置分期募集编号
                // 新增时需要的数据
                cwGlBalance.setDebitamount(cwGlDetail.getDebitamount() == null ? new BigDecimal("0") : cwGlDetail.getDebitamount());
                cwGlBalance.setCreditamount(cwGlDetail.getCreditamount() == null ? new BigDecimal("0") : cwGlDetail.getCreditamount());
                cwGlBalance.setLocalcreditamount(cwGlDetail.getLocalcreditamount() == null ? new BigDecimal("0") : cwGlDetail.getLocalcreditamount());
                cwGlBalance.setLocaldebitamount(cwGlDetail.getLocaldebitamount() == null ? new BigDecimal("0") : cwGlDetail.getLocaldebitamount());
                cwGlBalance.setSubjcode(cwGlDetail.getSubjcode());
                cwGlBalance.setSubjname(cwGlDetail.getSubjname());
                cwGlBalance.setPkCurrtype(cwGlDetail.getPkCurrtype());
                //判断assid是否存在
                if (StringUtils.isNotBlank(cwGlDetail.getAssid())) {
                    cwGlBalance.setAssid(cwGlDetail.getAssid());
                }
                //查询余额表
                CwGlBalance selectCwGlBalance = cwGlBalanceMapper.selectCwGlBalance(cwGlBalance);
                //辅助余额表中存在则统计修改
                if (selectCwGlBalance != null || !isBooking) {
                    cwGlBalance.setUpdateTime(new Date());
                    if (sysUserInfo != null) {
                        cwGlBalance.setUpdateUser(sysUserInfo.getUserId());
                    }
                    int res = cwGlBalanceMapper.updateBalanceCount(cwGlBalance);
                    if (res != 1) {
                        log.error("余额表修改结果有误抛出异常");
                        Shift.fatalThrow(SysStatusCode.OPERATION_FAIL);
                    }
                    //不存在新增
                } else {
                    cwGlBalance.setCreateTime(new Date());
                    if (sysUserInfo != null) {
                        cwGlBalance.setCreateUser(sysUserInfo.getUserId());
                    }
                    cwGlBalance.setPkBalance(SnowflakeIdWorker.getInstance().nextIdString());
                    cwGlBalance.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
                    int res = cwGlBalanceMapper.insertBalance(cwGlBalance);
                    if (res != 1) {
                        log.error("新增余额表数据失败抛出异常");
                        Shift.fatalThrow(SysStatusCode.OPERATION_FAIL);
                    }
                }

            }

        }
    }

    /* (非 Javadoc)
     * <p>Title: updateCwGlVoucherForReverse</p>
     * <p>Description: 批量反审核凭证</p>
     * @param cwGlVouchers
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateCwGlVoucherForReverse(java.util.List)
     * @author huangpeng
     * @date 2019年4月5日 上午9:33:07
     * @修改日志：
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<Object, CurrencyMeta> updateCwGlVoucherForReverse(List<CwGlVoucher> cwGlVouchers) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        for (CwGlVoucher cwGlVoucher : cwGlVouchers) {
            //校验：该账套和期间已经结账则不允许操作
            long count = cwGlSettleMapper.countIsSettle(cwGlVoucher.getPkGlorgbook(), cwGlVoucher.getPeriod());
            if (count > 0) {
                CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(cwGlVoucher.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));
            }
            //只能反审核自己的审核通过的凭证
//			if(sysUserInfo != null) {
//				if(!sysUserInfo.getUserId().equals(cwGlVoucher.getPkAudit())) {
//					return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.RVERSER_NOT_MYSELF_AUDIT.message(),
//							MetaDataUtil.getMeta(tracer,FinanceStatusCode.RVERSER_NOT_MYSELF_AUDIT));
//				}
//			}else {
//				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,SysStatusCode.USER_LOGOUT_ERROR.message(),MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
//			}
        }
        for (CwGlVoucher cwGlVoucher : cwGlVouchers) {
            CwGlVoucherForReverse cwGlVoucherForReverse = new CwGlVoucherForReverse();
            if (sysUserInfo != null) {
                cwGlVoucherForReverse.setUpdateUser(sysUserInfo.getUserId());
            }
            cwGlVoucherForReverse.setPkVoucher(cwGlVoucher.getPkVoucher());
            cwGlVoucherForReverse.setUpdateTime(new Date());
            cwGlVoucherForReverse.setAuditdate(null);
            cwGlVoucherForReverse.setIsaudit("0");
            cwGlVoucherForReverse.setPkAudit(null);
            cwGlVoucherForReverse.setVouchertype("1");
            int res = cwGlVoucherMapper.updateByRerverseAudit(cwGlVoucherForReverse);
            if (res > 0) {
                CwReverseOperation cwReverseOperation = new CwReverseOperation();
                cwReverseOperation.setPkGlorgbook(cwGlVoucher.getPkGlorgbook());
                cwReverseOperation.setPeriod(cwGlVoucher.getPeriod());
                if (sysUserInfo != null) {
                    cwReverseOperation.setOperator(sysUserInfo.getUserId());
                }
                cwReverseOperation.setReverseType(FinanceDictConsts.Cwfxcz.FSH);
                cwReverseOperation.setOperationtime(new Date());
                cwReverseOperation.setPkVoucher(cwGlVoucher.getPkVoucher());
                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));
    }

    /* (非 Javadoc)
     * <p>Title: updateCwGlVoucherForReverseBooking</p>
     * <p>Description:批量反记账凭证 </p>
     * @param cwGlVouchers
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateCwGlVoucherForReverseBooking(java.util.List)
     * @author huangpeng
     * @date 2019年4月5日 上午9:49:10
     * @修改日志：
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestfulResponse<Object, CurrencyMeta> updateCwGlVoucherForReverseBooking(List<CwGlVoucher> cwGlVouchers) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        for (CwGlVoucher cwGlVoucher : cwGlVouchers) {
            //校验：该账套和期间已经结账则不允许操作
            long count = cwGlSettleMapper.countIsSettle(cwGlVoucher.getPkGlorgbook(), cwGlVoucher.getPeriod());
            if (count > 0) {
                CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(cwGlVoucher.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));
            }
            CwGlVoucherForReverse cwGlVoucherForReverse = new CwGlVoucherForReverse();
            if (sysUserInfo != null) {
                cwGlVoucherForReverse.setUpdateUser(sysUserInfo.getUserId());
            }
            cwGlVoucherForReverse.setPkVoucher(cwGlVoucher.getPkVoucher());
            cwGlVoucherForReverse.setPkSign(null);
            cwGlVoucherForReverse.setUpdateTime(new Date());
            cwGlVoucherForReverse.setSigndate(null);
            cwGlVoucherForReverse.setIssign("0");
            cwGlVoucherForReverse.setVouchertype("2");
            int res = cwGlVoucherMapper.updateByRerverseBooking(cwGlVoucherForReverse);    //凭证表更新反记账

            if (res > 0) {
                CwReverseOperation cwReverseOperation = new CwReverseOperation();
                cwReverseOperation.setPkGlorgbook(cwGlVoucher.getPkGlorgbook());
                cwReverseOperation.setPeriod(cwGlVoucher.getPeriod());
                if (sysUserInfo != null) {
                    cwReverseOperation.setOperator(sysUserInfo.getUserId());
                }
                cwReverseOperation.setReverseType(FinanceDictConsts.Cwfxcz.FJIZ);
                cwReverseOperation.setOperationtime(new Date());
                cwReverseOperation.setPkVoucher(cwGlVoucher.getPkVoucher());
                cwReverseOperation.setPkReverse(SnowflakeIdWorker.getInstance().nextIdString());
                cwReverseOperationMapper.insert(cwReverseOperation);//插入反记账信息
            }
        }
        bookingBalanceCount(cwGlVouchers, false);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * Title: deleteOrderMakingBatch
     * Description:批量删除凭证信息（制单）
     * @param cwGlVoucherList
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#deleteOrderMakingBatch(java.util.List)
     * @author dml
     * @date 2019年4月8日 上午11:06:59
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> deleteOrderMakingBatch(List<CwGlVoucher> cwGlVoucherList) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        Map<String, Object> map = new HashMap<>();
        if (sysUserInfo != null) {
            map.put("updateUser", sysUserInfo.getUserId());
        }
        map.put("updateTime", new Date());
        map.put("list", cwGlVoucherList);
        cwGlVoucherMapper.deleteOrderMakingBatch(map);
        for (CwGlVoucher cwGlVoucher : cwGlVoucherList) {
            // 分录信息
            CwGlDetail cwGlDetail = new CwGlDetail();
            if (sysUserInfo != null) {
                cwGlDetail.setUpdateUser(sysUserInfo.getUserId());
            }
            cwGlDetail.setUpdateTime(new Date());
            cwGlDetail.setUseState(FinanceDictConsts.Syzt.INVALID);
            cwGlDetail.setPkVoucher(cwGlVoucher.getPkVoucher());
            cwGlDetailMapper.deleteByPkVoucherLogic(cwGlDetail);
        }
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: searchCwGlVoucherForRerverseBooking</p>
     * <p>Description:查询反记账列表信息 </p>
     * @param pageNum
     * @param pageSize
     * @param navigatePages
     * @param cwGlVoucherAndLike
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#searchCwGlVoucherForRerverseBooking(int, int, int, com.dhcc.finance.main.model.CwGlVoucherAndLike)
     * @author huangpeng
     * @date 2019年10月15日 下午4:27:04
     * @修改日志：
     */

    @Override
    public RestfulResponse<PageInfo<CwGlVoucherAndName>, CurrencyMeta> searchCwGlVoucherForRerverseBooking(int pageNum,
                                                                                                           int pageSize, int navigatePages, CwGlVoucherAndLike cwGlVoucherAndLike) {
        PageHelper.startPage(pageNum, pageSize);
        List<CwGlVoucherAndName> list = cwGlVoucherMapper.selectForReverseBooking(cwGlVoucherAndLike);
        PageInfo<CwGlVoucherAndName> pageInfo = new PageInfo<>(list, navigatePages);
        return new RestfulResponse<PageInfo<CwGlVoucherAndName>, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, pageInfo, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * Title: selectOrderMakingDetil
     * Description:查询制单详情
     * @param pkVoucher
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#selectOrderMakingDetil(java.lang.String)
     * @author dml
     * @date 2019年4月15日 上午11:32:22
     * @修改日志：
     */
    @Override
    public RestfulResponse<CwGlVoucherWeb, CurrencyMeta> selectOrderMakingDetil(String pkVoucher, String useState) {
        CwGlVoucherWeb cwGlVoucherWeb = cwGlVoucherMapper.selectOrderMakingDetil(pkVoucher, useState);
        if (cwGlVoucherWeb == null) {
            return new RestfulResponse<CwGlVoucherWeb, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.VOUCHER_DETAIL_NOT_FOUND.message(), MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
        }
        List<CwGlDetail> selectByPkVoucher = cwGlDetailMapper.selectByPkVoucher(pkVoucher, useState);
        // 对摘要重新赋值
        if (cwGlVoucherWeb.getCwGlDetailList() != null && cwGlVoucherWeb.getCwGlDetailList().size() > 0) {
            cwGlVoucherWeb.getCwGlDetailList().forEach(x -> {
                // 对摘要重新赋值
                for (CwGlDetail cwGlDetail : selectByPkVoucher) {
                    if (x.getPkDetail().equals(cwGlDetail.getPkDetail())) {
                        x.setAbstracts(cwGlDetail.getAbstracts());
                    }
                }
                // 辅助项转中文名(不用转了)
                if (x.getCwGlFreevalueList() != null && !x.getCwGlFreevalueList().isEmpty() && StringUtils.isNotBlank(x.getAssid())) {

                } else {
                    x.setCwGlFreevalueList(new ArrayList<CwGlFreevalue>());
                }
            });
        }
        return new RestfulResponse<CwGlVoucherWeb, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, cwGlVoucherWeb, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * Title: selectOrderMakingDetil
     * Description:打印查询制单详情
     * @param pkVoucher
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#selectOrderMakingDetil(java.lang.String)
     * @author dml
     * @date 2019年4月15日 上午11:32:22
     * @修改日志：
     */
    @Override
    public RestfulResponse<CwGlVoucherWeb, CurrencyMeta> selectOrderMakingPrint(String pkVoucher, String useState) {
        CwGlVoucherWeb cwGlVoucherWeb = cwGlVoucherMapper.selectOrderMakingDetil(pkVoucher, useState);
        List<CwGlDetail> selectByPkVoucher = cwGlDetailMapper.selectByPkVoucher(pkVoucher, useState);
        // 对摘要重新赋值
        if (cwGlVoucherWeb != null) {
            cwGlVoucherWeb.getCwGlDetailList().forEach(x -> {
                // 对摘要重新赋值
                for (CwGlDetail cwGlDetail : selectByPkVoucher) {
                    if (x.getPkDetail().equals(cwGlDetail.getPkDetail())) {
                        x.setAbstracts(cwGlDetail.getAbstracts());
                    }
                }
                // 辅助项转中文名
                if (x.getCwGlFreevalueList() != null && !x.getCwGlFreevalueList().isEmpty() && StringUtils.isNotBlank(x.getAssid())) {
                    x.getCwGlFreevalueList().forEach(y -> {
                        CwBdAccassitem cwBdAccassitem = cwBdAccassitemMapper.selectByPrimaryKey(y.getChecktype());
                        if (cwBdAccassitem != null) {
                            String sql = "select " + cwBdAccassitem.getCodefield() + " as checkname from " + cwBdAccassitem.getTablecode() +
                                    "  where " + cwBdAccassitem.getPkfield() + " = '" + y.getCheckvalue() + "'";
                            String res = cwBdAccassitemMapper.selectCheckname(sql);
                            y.setCheckname(res);
                        }
                    });
                } else {
                    x.setCwGlFreevalueList(new ArrayList<CwGlFreevalue>());
                }
            });
        }
        return new RestfulResponse<CwGlVoucherWeb, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, cwGlVoucherWeb, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * Title: updateOrderMakingDetil
     * Description:修改制单详情
     * @param cwGlVoucherWeb
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateOrderMakingDetil(com.dhcc.finance.main.model.CwGlVoucherWeb)
     * @author dml
     * @date 2019年4月15日 下午8:23:39
     * @修改日志：
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestfulResponse<Object, CurrencyMeta> updateOrderMakingDetil(CwGlVoucherWeb cwGlVoucherWeb) {

        if (cwGlVoucherWeb.chackData() || StringUtils.isBlank(cwGlVoucherWeb.getPkVoucher())) {
            log.info("业务数据校验不通过,修改时主键不能为空>>>" + cwGlVoucherWeb);
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, SysStatusCode.SERVER_CHECK_ERROR.message(),
                    MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
        }
        //校验：该账套和期间已经结账则不允许操作
        long count = cwGlSettleMapper.countIsSettle(cwGlVoucherWeb.getPkGlorgbook(), cwGlVoucherWeb.getPeriod());
        if (count > 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, "该账套在该期间中已经结账",
                    MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
        }
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        if (sysUserInfo != null) {
            cwGlVoucherWeb.setUpdateUser(sysUserInfo.getUserId());
        }
        cwGlVoucherWeb.setUpdateTime(new Date());

        //查询库中原有数据
        CwGlVoucher cwGlVoucherOld = cwGlVoucherMapper.selectByPrimaryKey(cwGlVoucherWeb.getPkVoucher());
        if (!(cwGlVoucherWeb.getPkGlorgbook().equals(cwGlVoucherOld.getPkGlorgbook()) &&
                cwGlVoucherWeb.getPkVoucherty().equals(cwGlVoucherOld.getPkVoucherty()) &&
                cwGlVoucherWeb.getPeriod().equals(cwGlVoucherOld.getPeriod()) &&
                cwGlVoucherWeb.getVoucherno().equals(cwGlVoucherOld.getVoucherno()))) {
            //修改最大凭证号表
            updateVoucherMaxno(cwGlVoucherWeb);
        }
        // 修改凭证信息
        CwGlVoucher cwGlVoucher = new CwGlVoucher();
        //摘要
        String abstracts = StringUtils.isBlank(cwGlVoucherWeb.getAbstracts()) ? cwGlVoucherWeb.getCwGlDetailList().get(0).getAbstracts() : cwGlVoucherWeb.getAbstracts();
        cwGlVoucherWeb.setAbstracts(abstracts);
        BeanUtils.copyProperties(cwGlVoucherWeb, cwGlVoucher);
        if (StringUtils.isBlank(cwGlVoucher.getFqmjbh())) {// 如果没有分期统一为null
            cwGlVoucher.setFqmjbh(null);
        }
        cwGlVoucherMapper.updateByPrimaryKeySelective(cwGlVoucher);
        // 将所有分录状态置为0(后边修改时会修改为1没修改的即为页面删除的)
        cwGlDetailMapper.updateByPkVoucher(cwGlVoucherWeb.getPkVoucher(), sysUserInfo == null ? null : sysUserInfo.getUserId());
        return updCwGlDetailInfo(cwGlVoucherWeb);
    }

    /**
     * 功能描述：修改分录辅助项
     *
     * @param cwGlVoucherWeb
     * @return List<CwGlDetail>
     * @author dml
     * @date 2019年4月15日 下午8:46:28
     * @修改日志：
     */
    private RestfulResponse<Object, CurrencyMeta> updCwGlDetailInfo(CwGlVoucherWeb cwGlVoucherWeb) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        String userId = cwGlVoucherWeb.getPkPrepared();
        if (sysUserInfo != null) {
            userId = sysUserInfo.getUserId();
        }
        //新增凭证分录信息
        List<CwGlDetailWeb> cwGlDetailList = cwGlVoucherWeb.getCwGlDetailList();

        List<CwGlDetail> cwGlDetailAddList = new ArrayList<CwGlDetail>();// 暂存分录list
        List<CwGlFreevalue> cwGlFreevalueListAll = new ArrayList<CwGlFreevalue>();// 暂存辅助项list
        List<String> assidListAll = new ArrayList<String>();// 暂存Assid list
        for (CwGlDetailWeb cwGlDetailWeb : cwGlDetailList) {
            cwGlDetailWeb.setCreateUser(userId);// 假如有新增的会用到新增时间和人员
            cwGlDetailWeb.setUpdateUser(userId);
            cwGlDetailWeb.setCreateTime(new Date());
            cwGlDetailWeb.setUpdateTime(new Date());
            cwGlDetailWeb.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
            cwGlDetailWeb.setPkVoucher(cwGlVoucherWeb.getPkVoucher());
            cwGlDetailWeb.setPkGlorgbook(cwGlVoucherWeb.getPkGlorgbook());
            cwGlDetailWeb.setPreparedate(cwGlVoucherWeb.getPreparedate());
            if (cwGlDetailWeb.getLocaldebitamount() == null) {
                cwGlDetailWeb.setLocaldebitamount(new BigDecimal("0"));
            }
            if (cwGlDetailWeb.getLocalcreditamount() == null) {
                cwGlDetailWeb.setLocalcreditamount(new BigDecimal("0"));
            }
            //TODO 原币借贷方金额暂时和本币一样
            cwGlDetailWeb.setDebitamount(cwGlDetailWeb.getLocaldebitamount());
            cwGlDetailWeb.setCreditamount(cwGlDetailWeb.getLocalcreditamount());
            //新增辅助标识
            List<CwGlFreevalue> cwGlFreevalueList = cwGlDetailWeb.getCwGlFreevalueList();
            if (cwGlFreevalueList != null && !cwGlFreevalueList.isEmpty()) {
                String assid = SnowflakeIdWorker.getInstance().nextIdString();
                if (StringUtils.isNotBlank(cwGlDetailWeb.getAssid())) {
                    // 旧的辅助信息
                    assidListAll.add(cwGlDetailWeb.getAssid());
                }
                //添加辅助表示信息
                for (CwGlFreevalue cwGlFreevalue : cwGlFreevalueList) {
                    cwGlFreevalue.setCreateUser(userId);
                    //保存辅助项的中文值
                    if (StringUtils.isBlank(cwGlFreevalue.getValuename())) {
                        CwBdAccassitem cwBdAccassitem = cwBdAccassitemMapper.selectByPrimaryKey(cwGlFreevalue.getChecktype());
                        if (cwBdAccassitem != null) {
                            String sql = "select " + cwBdAccassitem.getCodefield() + " as checkname from " + cwBdAccassitem.getTablecode() +
                                    "  where " + cwBdAccassitem.getPkfield() + " = '" + cwGlFreevalue.getCheckvalue() + "'";
                            String res = cwBdAccassitemMapper.selectCheckname(sql);
                            cwGlFreevalue.setValuename(res);
                        }
                    }
                    cwGlFreevalue.setCreateTime(new Date());
                    cwGlFreevalue.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
                    cwGlFreevalue.setPkFreevalue(SnowflakeIdWorker.getInstance().nextIdString());
                    cwGlFreevalue.setAssid(assid);
                    cwGlFreevalue.setCreditamount(cwGlDetailWeb.getLocalcreditamount());
                    cwGlFreevalue.setDebitamount(cwGlDetailWeb.getLocaldebitamount());
                }
                cwGlFreevalueListAll.addAll(cwGlFreevalueList);
                cwGlDetailWeb.setAssid(assid);
            }
            CwGlDetail cwGlDetail = new CwGlDetail();
            BeanUtils.copyProperties(cwGlDetailWeb, cwGlDetail);
            cwGlDetailAddList.add(cwGlDetail);
        }
        if (!assidListAll.isEmpty()) {
            CwGlFreevalueMapper.deleteByAssid(assidListAll);
        }
        if (!cwGlFreevalueListAll.isEmpty()) {
            CwGlFreevalueMapper.insertCwGlFreevalueBatch(cwGlFreevalueListAll);
        }
        // 原有的分录
        List<CwGlDetail> oldDetailList = cwGlDetailAddList.stream().filter(x -> StringUtils.isNotBlank(x.getPkDetail())).collect(Collectors.toList());
        // 需要新增的分录
        List<CwGlDetail> newDetailList = cwGlDetailAddList.stream().filter(x -> StringUtils.isBlank(x.getPkDetail())).collect(Collectors.toList());
        if (!newDetailList.isEmpty()) {
            newDetailList.forEach(x -> {
                x.setPkDetail(SnowflakeIdWorker.getInstance().nextIdString());
            });
            cwGlDetailMapper.insertCwGlDetailBatch(newDetailList);
        }
        cwGlDetailMapper.updateDetailBatch(oldDetailList);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,
                MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /**
     * 功能描述：分录信息组装辅助信新增等
     *
     * @param cwGlVoucherWeb
     * @return List<CwGlDetail>
     * @author dml
     * @date 2019年4月15日 下午8:46:28
     * @修改日志：
     */
    private List<CwGlDetail> addCwGlDetailInfo(CwGlVoucherWeb cwGlVoucherWeb) {
        CwBdAccassitemExample example = new CwBdAccassitemExample();
        example.createCriteria().andUseStateEqualTo(UsestateEnum.EFFECTIVE.getCodeStr());
        List<CwBdAccassitem> cwBdAccassitems = cwBdAccassitemMapper.selectByExample(example);

        //新增凭证分录信息
        List<CwGlDetailWeb> cwGlDetailList = cwGlVoucherWeb.getCwGlDetailList();
        List<CwGlDetail> cwGlDetailAddList = new ArrayList<CwGlDetail>();
        List<CwGlFreevalue> cwGlFreevalueListAll = new ArrayList<CwGlFreevalue>();// 暂存辅助项list
        cwGlDetailList.forEach(cwGlDetailWeb -> {
            cwGlDetailWeb.setCreateUser(cwGlVoucherWeb.getCreateUser());
            cwGlDetailWeb.setCreateTime(new Date());
            cwGlDetailWeb.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
            cwGlDetailWeb.setPkVoucher(cwGlVoucherWeb.getPkVoucher());
            cwGlDetailWeb.setPkGlorgbook(cwGlVoucherWeb.getPkGlorgbook());
            cwGlDetailWeb.setPreparedate(cwGlVoucherWeb.getPreparedate());
            String pkDetail = SnowflakeIdWorker.getInstance().nextIdString();
            cwGlDetailWeb.setPkDetail(pkDetail);
            if (cwGlDetailWeb.getLocaldebitamount() == null) {
                cwGlDetailWeb.setLocaldebitamount(new BigDecimal("0"));
            }
            if (cwGlDetailWeb.getLocalcreditamount() == null) {
                cwGlDetailWeb.setLocalcreditamount(new BigDecimal("0"));
            }
            //TODO 原币借贷方金额暂时和本币一样
            cwGlDetailWeb.setDebitamount(cwGlDetailWeb.getLocaldebitamount());
            cwGlDetailWeb.setCreditamount(cwGlDetailWeb.getLocalcreditamount());
            //新增辅助标识
            List<CwGlFreevalue> cwGlFreevalueList = cwGlDetailWeb.getCwGlFreevalueList();
            if (cwGlFreevalueList != null && !cwGlFreevalueList.isEmpty()) {
                String assid = SnowflakeIdWorker.getInstance().nextIdString();
                //添加辅助表示信息
                cwGlFreevalueList.forEach(cwGlFreevalue -> {
                    cwGlFreevalue.setCreateUser(cwGlVoucherWeb.getCreateUser());
                    //保存辅助项的中文值
                    if (StringUtils.isBlank(cwGlFreevalue.getValuename()) && StringUtils.isNotBlank(cwGlFreevalue.getChecktype())) {
                        for (CwBdAccassitem cwBdAccassitem : cwBdAccassitems) {
                            if (cwGlFreevalue.getChecktype().equals(cwBdAccassitem.getPkAccassitem())) {
                                String sql = "select " + cwBdAccassitem.getCodefield() + " as checkname from " + cwBdAccassitem.getTablecode() +
                                        "  where " + cwBdAccassitem.getPkfield() + " = '" + cwGlFreevalue.getCheckvalue() + "'";
                                String res = cwBdAccassitemMapper.selectCheckname(sql);
                                cwGlFreevalue.setValuename(res);
                                break;
                            }
                        }
                    }
                    cwGlFreevalue.setCreateTime(new Date());
                    cwGlFreevalue.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
                    cwGlFreevalue.setPkFreevalue(SnowflakeIdWorker.getInstance().nextIdString());
                    cwGlFreevalue.setAssid(assid);
                    cwGlFreevalue.setCreditamount(cwGlDetailWeb.getLocalcreditamount());
                    cwGlFreevalue.setDebitamount(cwGlDetailWeb.getLocaldebitamount());
                });
                //新增辅助信息

/*				//生成assid查询条件
				StringBuilder checktypes = new StringBuilder();
				StringBuilder checkvalues = new StringBuilder();
				cwGlFreevalueList.sort((x,y) ->{
					return x.getChecktype().compareTo(y.getChecktype());
				});
				cwGlFreevalueList.forEach(x ->{
					checktypes.append(x.getChecktype()+"-");
					checkvalues.append(x.getCheckvalue()+"-");
				});
				checktypes.deleteCharAt(checktypes.length() - 1);
				checkvalues.deleteCharAt(checkvalues.length() - 1);
				//查询assid是否存在
				CwGlFreevalue selectAssid = CwGlFreevalueMapper.selectAssid(checktypes.toString(), checkvalues.toString(),cwGlFreevalueList.get(0).getCheckvalue());
				if (selectAssid != null && StringUtils.isNotBlank(selectAssid.getAssid())) {
					//已存在则使用存在的assid
					assid = selectAssid.getAssid();
				}else {
					//不存在新增
					assid = String.valueOf(idWorker.nextId());
					//添加辅助表示信息
					cwGlFreevalueList.forEach(cwGlFreevalue ->{
						if (sysUserInfo != null) {
							cwGlFreevalue.setCreateUser(sysUserInfo.getUserId());
						}
						cwGlFreevalue.setCreateTime(new Date());
						cwGlFreevalue.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
						cwGlFreevalue.setPkFreevalue(String.valueOf(idWorker.nextId()));
						cwGlFreevalue.setAssid(assid);
					});
					//新增辅助信息
					CwGlFreevalueMapper.insertCwGlFreevalueBatch(cwGlFreevalueList);
				}*/
                cwGlDetailWeb.setAssid(assid);
                cwGlFreevalueListAll.addAll(cwGlFreevalueList);
            }
            CwGlDetail cwGlDetail = new CwGlDetail();
            BeanUtils.copyProperties(cwGlDetailWeb, cwGlDetail);
            cwGlDetailAddList.add(cwGlDetail);
        });
        if (!cwGlFreevalueListAll.isEmpty()) {
            CwGlFreevalueMapper.insertCwGlFreevalueBatch(cwGlFreevalueListAll);
        }
        return cwGlDetailAddList;
    }

    /**
     * 功能描述：修改最大凭证号
     *
     * @param cwGlVoucherWeb
     * @return int
     * @author dml
     * @date 2019年4月15日 下午8:43:03
     * @修改日志：
     */
    private int updateVoucherMaxno(CwGlVoucherWeb cwGlVoucherWeb) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        CwGlVouchermaxno cwGlVouchermaxno = new CwGlVouchermaxno();
        cwGlVouchermaxno.setMaxno(cwGlVoucherWeb.getVoucherno());
        if (sysUserInfo != null) {
            cwGlVouchermaxno.setUpdateUser(sysUserInfo.getUserId());
        }
        cwGlVouchermaxno.setUpdateTime(new Date());
        CwGlVouchermaxnoExample cwGlVouchermaxnoExample = new CwGlVouchermaxnoExample();
        Criteria criteria = cwGlVouchermaxnoExample.createCriteria();
        criteria.andPkGlorgbookEqualTo(cwGlVoucherWeb.getPkGlorgbook());
        criteria.andPeriodEqualTo(cwGlVoucherWeb.getPeriod());
        log.info("--------------------------------------------------------------------------------------");
        log.info("\r\n{}", cwGlVouchermaxno);
        int res2 = 0;
        try {
            res2 = cwGlVouchermaxnoMapper.updateByExampleSelective(cwGlVouchermaxno, cwGlVouchermaxnoExample);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
        log.info("--------------------------------------------------------------------------------------");
        return res2;
    }

    /*
     * (非 Javadoc)
     * Title: updateBalance
     * Description:结账时刷新余额
     * @param cwGlVouchers
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateBalance(java.util.List)
     * @author dml
     * @date 2019年4月25日 下午3:54:35
     * @修改日志：
     */
    @Override
    public void updateBalance(List<CwGlVoucher> cwGlVouchers) {
        bookingBalanceCount(cwGlVouchers, true);
    }

    /*
     * (非 Javadoc)
     * <p>Title: searchCwGlVoucherForTransfer</p>
     * <p>Description:查询结转凭证信息 </p>
     * @param pkGlorgbook
     * @param period
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#searchCwGlVoucherForTransfer(java.lang.String, java.lang.String)
     * @author huangpeng
     * @date 2019年6月6日 下午5:03:42
     * @修改日志：
     */
    @Override
    public RestfulResponse<List<CwGlVoucherWeb>, CurrencyMeta> searchCwGlVoucherForTransfer(String pkGlorgbook,
                                                                                            String period) {
        List<CwGlVoucherWeb> list = cwGlVoucherMapper.selectVoucherForTransfer(pkGlorgbook, period, FinanceDictConsts.Cwpzlx.JIEZPZ);
        // 对摘要重新赋值
        for (CwGlVoucherWeb cwGlVoucherWeb : list) {
            cwGlVoucherWeb.getCwGlDetailList().forEach(x -> {
                List<CwGlDetail> selectByPkVoucher = cwGlDetailMapper.selectByPkVoucher(x.getPkVoucher(), "1");
                // 对摘要重新赋值
                for (CwGlDetail cwGlDetail : selectByPkVoucher) {
                    if (x.getPkDetail().equals(cwGlDetail.getPkDetail())) {
                        x.setAbstracts(cwGlDetail.getAbstracts());
                    }
                }
            });
        }
        return new RestfulResponse<List<CwGlVoucherWeb>, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, list, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * Title: reverseVoucher
     * Description:恢复已删除的凭证信息 （数据量很小基本都是一条）
     * @param cwGlVoucherList
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#reverseVoucher(java.util.List)
     * @author dml
     * @date 2019年6月14日 下午1:58:15
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> reverseVoucher(List<CwGlVoucher> cwGlVoucherList) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        for (CwGlVoucher cwGlVouchers : cwGlVoucherList) {
            CwGlVoucher cwGlVoucher = new CwGlVoucher();
            if (sysUserInfo != null) {
                cwGlVoucher.setUpdateUser(sysUserInfo.getUserId());
            }
            cwGlVoucher.setUpdateTime(new Date());
            cwGlVoucher.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
            cwGlVoucher.setPkVoucher(cwGlVouchers.getPkVoucher());
            String pkGlorgbook = cwGlVouchers.getPkGlorgbook();
            CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(pkGlorgbook);
            String pkCurrperiod = cwBdGlorgbook.getPkCurrperiod();
            // 分录信息
            CwGlDetail cwGlDetail = new CwGlDetail();
            if (!cwGlVouchers.getPeriod().equals(pkCurrperiod)) {
                cwGlVoucher.setPeriod(pkCurrperiod);
                // CwGlVouchermaxno voucherMaxno = cwGlVouchermaxnoMapper.selectGetMaxNo(pkGlorgbook, pkCurrperiod);//得到最大凭证号信息
                CwGlVouchermaxno voucherMaxno = cwGlVouchermaxnoMapper.getVoucherMaxNo(pkGlorgbook, pkCurrperiod);//得到最大凭证号信息
                String maxNo = Integer.valueOf(voucherMaxno.getMaxno()) + 1 + "";
                cwGlVoucher.setVoucherno(maxNo);
                String period = FinanceDateUtil.getMonthFirstDayDate(pkCurrperiod);//得到第一天
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date = sdf.parse(period);
                    cwGlVoucher.setPreparedate(date);
                    cwGlDetail.setPreparedate(date);

                    //更新凭证号表
                    CwGlVouchermaxno cwGlVouchermaxno = new CwGlVouchermaxno();
                    cwGlVouchermaxno.setMaxno(maxNo);
                    if (sysUserInfo != null) {
                        cwGlVouchermaxno.setUpdateUser(sysUserInfo.getUserId());
                    }
                    cwGlVouchermaxno.setUpdateTime(new Date());
                    CwGlVouchermaxnoExample cwGlVouchermaxnoExample = new CwGlVouchermaxnoExample();
                    Criteria criteria = cwGlVouchermaxnoExample.createCriteria();
                    criteria.andPkGlorgbookEqualTo(pkGlorgbook);
                    criteria.andPeriodEqualTo(pkCurrperiod);
                    criteria.andUseStateEqualTo(FinanceDictConsts.Syzt.EFFECTIVE);
                    cwGlVouchermaxnoMapper.updateByExampleSelective(cwGlVouchermaxno, cwGlVouchermaxnoExample);//更新最大凭证号信息
                } catch (ParseException e) {
                    log.error("日期转换失败>>>>>>>>", e);
                }
            }
            cwGlVoucherMapper.updateByPrimaryKeySelective(cwGlVoucher);

            if (sysUserInfo != null) {
                cwGlDetail.setUpdateUser(sysUserInfo.getUserId());
            }
            cwGlDetail.setUpdateTime(new Date());
            cwGlDetail.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
            cwGlDetail.setPkVoucher(cwGlVouchers.getPkVoucher());
            cwGlDetailMapper.deleteByPkVoucherLogic(cwGlDetail);
        }

        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: searchCwGlVoucherCount</p>
     * <p>Description: 查询凭证数量 </p>
     * @param useState
     * @param vouchertype
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#searchCwGlVoucherCount(java.lang.String, java.lang.String)
     * @author huangpeng
     * @date 2019年7月5日 上午10:09:53
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> searchCwGlVoucherCount(String useState, String vouchertype, String falg, String pkGlorgbook, String period, String fqmc) {
        pkGlorgbook = StringUtils.isBlank(pkGlorgbook) ? null : pkGlorgbook;
        period = StringUtils.isBlank(period) ? null : period;
        fqmc = StringUtils.isBlank(fqmc) ? null : fqmc;
        Map<String, Integer> count = cwGlVoucherMapper.searchCwGlVoucherCount(useState, vouchertype, falg, pkGlorgbook, period, fqmc);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, count, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: searchVoucherDetailForSerialNo</p>
     * <p>Description:根据流水号查询凭证信息 </p>
     * @param serialNo
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#searchVoucherDetailForSerialNo(java.lang.String)
     * @author huangpeng
     * @date 2019年7月18日 下午2:25:41
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> searchVoucherDetailForSerialNo(
            List<String> serialNoList, String tradeCode) {
        if (serialNoList.size() <= 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.SEARIAL_PARAMETERIS_EMPTY.message(),
                    MetaDataUtil.getMeta(tracer, FinanceStatusCode.SEARIAL_PARAMETERIS_EMPTY));
        }
        List<CwBdRecordSerialForVoucher> pkVoucherList = cwBdRecordSerialMapper.searchPkVoucherList(serialNoList);
        if (pkVoucherList.size() == 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.VOUCHER_IS_GENERATING.message(),
                    MetaDataUtil.getMeta(tracer, FinanceStatusCode.VOUCHER_IS_GENERATING));
        }
        boolean flag = false;
        List<String> voucherList = new ArrayList<String>();
        Set<String> batchList = new HashSet<String>();
        for (CwBdRecordSerialForVoucher cwBdRecordSerialForVoucher : pkVoucherList) {
            //生成中
            if (FinanceDictConsts.STATE.generate.equals(cwBdRecordSerialForVoucher.getSignType())) {
                return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.VOUCHER_IS_GENERATING.message(),
                        MetaDataUtil.getMeta(tracer, FinanceStatusCode.VOUCHER_IS_GENERATING));
            }
            //估值不生成凭证
            if (FinanceDictConsts.STATE.fail.equals(cwBdRecordSerialForVoucher.getSignType())
                    && FinanceStatusCode.VALUATION_NOT_CREATE_VOUCHER.message().equals(cwBdRecordSerialForVoucher.getFailReason())) {
                flag = true;
            }
            //若有成功的
            if (FinanceDictConsts.STATE.success.equals(cwBdRecordSerialForVoucher.getSignType())) {
                voucherList.add(cwBdRecordSerialForVoucher.getPkVoucher());
            }
            batchList.add(cwBdRecordSerialForVoucher.getBatchNo());
        }
        if (!flag && voucherList.size() == 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.VOUCHER_IS_CREATE_FAIL.message(), batchList,
                    MetaDataUtil.getMeta(tracer, FinanceStatusCode.VOUCHER_IS_CREATE_FAIL));
        }
        if (flag && voucherList.size() == 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.VALUATION_NOT_CREATE_VOUCHER.message(),
                    MetaDataUtil.getMeta(tracer, FinanceStatusCode.VALUATION_NOT_CREATE_VOUCHER));
        }
        List<String> pkList = new ArrayList<String>();
        for (String pkVoucher : voucherList) {
            if (StringUtils.contains(pkVoucher, ",")) {
                String[] split = pkVoucher.split(",");
                for (String string : split) {
                    pkList.add(string);
                }
            } else {
                pkList.add(pkVoucher);
            }

        }
        List<CwGlVoucherWeb> list = cwGlVoucherMapper.searchVoucherDetailForSerialNo(pkList, FinanceDictConsts.Cwpzlx.JIZPZ);
        if (list.size() == 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.NOT_FOUND_VOUCHERDETAIL.message(),
                    MetaDataUtil.getMeta(tracer, FinanceStatusCode.NOT_FOUND_VOUCHERDETAIL));
        }
        // 对摘要重新赋值
        for (CwGlVoucherWeb cwGlVoucherWeb : list) {
            cwGlVoucherWeb.getCwGlDetailList().forEach(x -> {
                List<CwGlDetail> selectByPkVoucher = cwGlDetailMapper.selectByPkVoucher(x.getPkVoucher(), "1");
                // 对摘要重新赋值
                for (CwGlDetail cwGlDetail : selectByPkVoucher) {
                    if (x.getPkDetail().equals(cwGlDetail.getPkDetail())) {
                        x.setAbstracts(cwGlDetail.getAbstracts());
                    }
                }
            });
        }
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, list, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /**
     * 功能描述   制单下查询贷方合计总和和借放方合计综合
     *
     * @author lipeng
     * @date 2019年7月25日 下午1:25:05
     * 修改日志
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> searchDebitANdCredit(CwGlVoucherAndLike cwGlVoucherAndLike) {
        Map<String, Long> searchDebitANdCredit = cwGlVoucherMapper.searchDebitANdCredit(cwGlVoucherAndLike);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, searchDebitANdCredit, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /**
     * 功能描述   审核下查询贷方合计总和和借放方合计综合
     *
     * @author xxx
     * @date 2019年7月29日 下午1:25:05
     * 修改日志
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> sumDebitANdCredit(CwGlVoucherAndLike cwGlVoucherAndLike) {
        Map<String, Long> sumDebitANdCredit = cwGlVoucherMapper.sumDebitANdCredit(cwGlVoucherAndLike);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, sumDebitANdCredit, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /**
     * 功能描述   记账下查询贷方合计总和和借放方合计综合
     *
     * @author xxx
     * @date 2019年7月29日 下午1:25:05
     * 修改日志
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> sumDebitANdCreditByLike(CwGlVoucherAndLike cwGlVoucherAndLike) {
        Map<String, Long> sumDebitANdCreditByLike = cwGlVoucherMapper.sumDebitANdCreditByLike(cwGlVoucherAndLike);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, sumDebitANdCreditByLike, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /* (non-Javadoc) <br/>
     * Title: selectCwGlDetailInfoByPkVoucher <br/>
     * Description: TODO <br/>
     * @param PkVoucher
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#selectVouchtempBInfoByPkVoucher(java.lang.String)
     */
    @Override
    public RestfulResponse<List<CwGlDetail>, CurrencyMeta> selectCwGlDetailInfoByPkVoucher(String PkVoucher) {
        // TODO Auto-generated method stub

        List<CwGlDetail> selectCwGlDetailInfoByPkVoucher = cwGlVoucherMapper.selectCwGlDetailInfoByPkVoucher(PkVoucher);
        return new RestfulResponse<List<CwGlDetail>, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, selectCwGlDetailInfoByPkVoucher, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: deleteCwGlVoucherForBatch</p>
     * <p>Description:反结转删除 </p>
     * @param cwGlVoucherList
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#deleteCwGlVoucherForBatch(java.util.List)
     * @author huangpeng
     * @date 2019年8月10日 下午4:37:27
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> deleteCwGlVoucherForBatch(List<CwGlVoucher> cwGlVoucherList) {
        List<String> assidList = cwGlDetailMapper.selectAssidList(cwGlVoucherList);
        if (assidList.size() != 0) {
            CwGlFreevalueMapper.updateUserStateByAssid(assidList);
        }
        cwGlDetailMapper.updateUserStateForTwo(cwGlVoucherList);
        cwGlVoucherMapper.updateUserStateForTwo(cwGlVoucherList);
        // TODO Auto-generated method stub
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: searchVoucherNoByBatchno</p>
     * <p>Description:查询凭证号的接口，费用报销使用 </p>
     * @param batchNo
     * @return
     * @see com.dhcc.finance.main.service.CwGlVouchermaxnoService#searchVoucherNoByBatchno(java.lang.String)
     * @author huangpeng
     * @date 2019年12月17日 上午9:12:00
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> searchVoucherNoByBatchno(String batchNo) {
        List<String> voucherList = cwBdRecordSerialMapper.searchVoucherByBatchno(batchNo);
        if (voucherList.size() <= 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.BATCHNO_NOTEXIST_VOUCHER.message(),
                    MetaDataUtil.getMeta(tracer, FinanceStatusCode.BATCHNO_NOTEXIST_VOUCHER));
        }
        List<String> vouList = new ArrayList<String>();
        for (String voucher : voucherList) {
            if (voucher.contains(",")) {
                String[] arr = voucher.split(",");
                for (String array : arr) {
                    vouList.add(array);
                }
            } else {
                vouList.add(voucher);
            }
        }
        List<CwGlVoucher> list = cwGlVoucherMapper.selectVoucherForBatch(vouList);
        if (list.size() <= 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.NOT_FOUND_VOUCHERDETAIL.message(),
                    MetaDataUtil.getMeta(tracer, FinanceStatusCode.NOT_FOUND_VOUCHERDETAIL));
        }
        String periodNum = "";
        for (CwGlVoucher cwGlVoucher : list) {
            String period = cwGlVoucher.getPeriod();
            String voucherno = cwGlVoucher.getVoucherno();
            String[] perArr = period.split("-");
            periodNum = periodNum + perArr[1] + "-" + voucherno + ",";
        }
        periodNum = periodNum.substring(0, periodNum.length() - 1);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, periodNum, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: updateCwGlVoucherByAuditForBatch</p>
     * <p>Description: 批量审核凭证信息</p>
     * @param cwGlVouchers
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateCwGlVoucherByAuditForBatch(java.util.List)
     * @author huangpeng
     * @date 2019年12月25日 上午9:51:26
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> updateCwGlVoucherByAuditForBatch(List<CwGlVoucher> cwGlVouchers) {
        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_FAIL));
        }
        for (CwGlVoucher cwGlVoucher : cwGlVouchers) {
            if (sysUserInfo.getUserId().equals(cwGlVoucher.getPkPrepared())) {
                return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.PKPREPARED_THESAME_PKAUDIT.message(),
                        MetaDataUtil.getMeta(tracer, FinanceStatusCode.PKPREPARED_THESAME_PKAUDIT));
            }
        }
        List<CwGlVoucher> collect = cwGlVouchers.stream().distinct().collect(Collectors.toList());
        List<String> searchIsCount = cwGlSettleMapper.searchIsCount(collect);//校验：该账套和期间已经结账则不允许操作
        if (searchIsCount.size() > 0) {
            String arr = searchIsCount.get(0);
            String[] split = arr.split(",");
            CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(split[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));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pkAudit", sysUserInfo.getUserId());
        map.put("list", cwGlVouchers);
        map.put("updateUser", sysUserInfo.getUserId());
        map.put("updateTime", new Date());
        map.put("auditdate", new Date());
        map.put("isaudit", FinanceDictConsts.SF.yes);
        map.put("vouchertype", FinanceDictConsts.Cwpzzt.YSH);
        cwGlVoucherMapper.updateCwGlVoucherForBatch(map);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: updateCwGlVoucherByChargeForBatch</p>
     * <p>Description:批量记账凭证信息 </p>
     * @param cwGlVouchers
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateCwGlVoucherByChargeForBatch(java.util.List)
     * @author huangpeng
     * @date 2019年12月25日 上午9:53:12
     * @修改日志：
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<Object, CurrencyMeta> updateCwGlVoucherByChargeForBatch(List<CwGlVoucher> cwGlVouchers) {
        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_FAIL));
        }
        List<CwGlVoucher> collect = cwGlVouchers.stream().distinct().collect(Collectors.toList());//集合去重
        List<String> searchIsCount = cwGlSettleMapper.searchIsCount(collect);//校验：该账套和期间已经结账则不允许操作
        if (searchIsCount.size() > 0) {
            String arr = searchIsCount.get(0);
            String[] split = arr.split(",");
            CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(split[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));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pkSign", sysUserInfo.getUserId());
        map.put("list", cwGlVouchers);
        map.put("updateUser", sysUserInfo.getUserId());
        map.put("updateTime", new Date());
        map.put("signdate", new Date());
        map.put("issign", FinanceDictConsts.SF.yes);
        map.put("vouchertype", FinanceDictConsts.Cwpzzt.YJZ);
        cwGlVoucherMapper.updateCwGlVoucherForBatch(map);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * Title: refreshBalance
     * Description:刷新余额表
     * @param cwGlVouchers
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#refreshBalance(java.util.List)
     * @author dml
     * @date 2019年12月26日 下午2:04:04
     * @修改日志：
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestfulResponse<Object, CurrencyMeta> refreshBalance(List<CwGlVoucher> cwGlVouchers) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        Set<String> set = new HashSet<String>();
        for (CwGlVoucher cwGlVoucher : cwGlVouchers) {
            set.add(cwGlVoucher.getPeriod());
        }
        List<String> list = new ArrayList<>();
        list.addAll(set);
        cwGlBalanceMapper.deleteBypkPeriod(list);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("createUser", sysUserInfo.getUserId());
        map.put("list", list);
        cwGlBalanceMapper.insertBypkPeriod(map);
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: updateCwGlVoucherForReverseByAudit</p>
     * <p>Description: 批量反审核</p>
     * @param cwGlVouchers
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateCwGlVoucherForReverseByAudit(java.util.List)
     * @author huangpeng
     * @date 2019年12月27日 上午9:33:40
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> updateCwGlVoucherForReverseByAudit(List<CwGlVoucher> cwGlVouchers) {
        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_FAIL));
        }
        List<CwGlVoucher> collect = cwGlVouchers.stream().distinct().collect(Collectors.toList());
        List<String> searchIsCount = cwGlSettleMapper.searchIsCount(collect);//校验：该账套和期间已经结账则不允许操作
        if (searchIsCount.size() > 0) {
            String arr = searchIsCount.get(0);
            String[] split = arr.split(",");
            CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(split[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));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pkAudit", null);
        map.put("list", cwGlVouchers);
        map.put("updateUser", sysUserInfo.getUserId());
        map.put("updateTime", new Date());
        map.put("auditdate", null);
        map.put("isaudit", FinanceDictConsts.SF.no);
        map.put("vouchertype", FinanceDictConsts.Cwpzzt.YZD);
        int res = cwGlVoucherMapper.updateCwGlVoucherForBatch(map);
        if (res > 0) {
            List<CwReverseOperation> CwReverseOperationList = new ArrayList<CwReverseOperation>();
            for (CwGlVoucher cwGlVoucher : cwGlVouchers) {
                CwReverseOperation cwReverseOperation = new CwReverseOperation();
                cwReverseOperation.setPkGlorgbook(cwGlVoucher.getPkGlorgbook());
                cwReverseOperation.setPeriod(cwGlVoucher.getPeriod());
                if (sysUserInfo != null) {
                    cwReverseOperation.setOperator(sysUserInfo.getUserId());
                }
                cwReverseOperation.setReverseType(FinanceDictConsts.Cwfxcz.FSH);
                cwReverseOperation.setOperationtime(new Date());
                cwReverseOperation.setPkVoucher(cwGlVoucher.getPkVoucher());
                cwReverseOperation.setPkReverse(SnowflakeIdWorker.getInstance().nextIdString());
                CwReverseOperationList.add(cwReverseOperation);
            }
            cwReverseOperationMapper.insertBatch(CwReverseOperationList);
        }
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /*
     * (非 Javadoc)
     * <p>Title: updateCwGlVoucherForReverseBookingToBatch</p>
     * <p>Description: 批量反记账凭证信息 </p>
     * @param cwGlVouchers
     * @return
     * @see com.dhcc.finance.main.service.CwGlVoucherService#updateCwGlVoucherForReverseBookingToBatch(java.util.List)
     * @author huangpeng
     * @date 2019年12月27日 上午9:35:24
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> updateCwGlVoucherForReverseBookingToBatch(
            List<CwGlVoucher> cwGlVouchers) {
        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_FAIL));
        }
        List<CwGlVoucher> collect = cwGlVouchers.stream().distinct().collect(Collectors.toList());//集合去重
        List<String> searchIsCount = cwGlSettleMapper.searchIsCount(collect);//校验：该账套和期间已经结账则不允许操作
        if (searchIsCount.size() > 0) {
            String arr = searchIsCount.get(0);
            String[] split = arr.split(",");
            CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(split[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));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pkSign", null);
        map.put("list", cwGlVouchers);
        map.put("updateUser", sysUserInfo.getUserId());
        map.put("updateTime", new Date());
        map.put("signdate", null);
        map.put("issign", FinanceDictConsts.SF.no);
        map.put("vouchertype", FinanceDictConsts.Cwpzzt.YSH);
        int res = cwGlVoucherMapper.updateCwGlVoucherForBatch(map);
        if (res > 0) {
            List<CwReverseOperation> CwReverseOperationList = new ArrayList<CwReverseOperation>();
            for (CwGlVoucher cwGlVoucher : cwGlVouchers) {
                CwReverseOperation cwReverseOperation = new CwReverseOperation();
                cwReverseOperation.setPkGlorgbook(cwGlVoucher.getPkGlorgbook());
                cwReverseOperation.setPeriod(cwGlVoucher.getPeriod());
                if (sysUserInfo != null) {
                    cwReverseOperation.setOperator(sysUserInfo.getUserId());
                }
                cwReverseOperation.setReverseType(FinanceDictConsts.Cwfxcz.FJIZ);
                cwReverseOperation.setOperationtime(new Date());
                cwReverseOperation.setPkVoucher(cwGlVoucher.getPkVoucher());
                cwReverseOperation.setPkReverse(SnowflakeIdWorker.getInstance().nextIdString());
                CwReverseOperationList.add(cwReverseOperation);
            }
            cwReverseOperationMapper.insertBatch(CwReverseOperationList);
        }
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

    /**
     * @param [cwGlVoucherRequests]
     * @return com.dhcc.common.model.response.RestfulResponse<java.lang.Object, com.dhcc.common.model.CurrencyMeta>
     * @description: 费用报销代垫凭证推送NC系统
     * @author liuxianjv
     * @date 2020-05-20 14:24
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> pushVoucherToNC(List<CwGlVoucherRequest> cwGlVoucherRequests) {
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);

        for (CwGlVoucherRequest cwGlVoucherRequest : cwGlVoucherRequests) {
            CwBdRecordNcpush cwBdRecordNcpush = new CwBdRecordNcpush();

            try {
                cwBdRecordNcpush.setPayeeMan(cwGlVoucherRequest.getPayee());
                cwBdRecordNcpush.setUseState(UsestateEnum.EFFECTIVE.getCodeStr());
                cwBdRecordNcpush.setInstId(cwGlVoucherRequest.getLcslywbh());
                cwBdRecordNcpush.setProjectCode(cwGlVoucherRequest.getZxmbh());
                cwBdRecordNcpush.setPkVoucher(cwGlVoucherRequest.getLcslywbh());
                if (sysUserInfo != null) {
                    cwBdRecordNcpush.setCreateUser(sysUserInfo.getUserId());
                }
                // 用流程实例业务编号查询对应生成凭证主键
                List<String> voucherKeys = cwGlVoucherMapper.searchVoucherPkByFlowId(cwGlVoucherRequest.getLcslywbh(), cwGlVoucherRequest.getBxlx());
                if (voucherKeys != null && voucherKeys.size() > 0) {
                    // 筛选已推送凭证
                    List<String> readyKeys = cwGlVoucherMapper.searchFinVoucherPk(voucherKeys);
                    List<String> finKeys = new ArrayList<>(voucherKeys);
                    finKeys.removeAll(readyKeys);
                    if (finKeys.size() > 0) {

                        for (String s : voucherKeys) {
                            cwBdRecordNcpush.setId(IdGenerator.INSTANCE.nextId());
                            cwBdRecordNcpush.setPkVoucher(s);
                            cwBdRecordNcpush.setCreateTime(new Date());

                            // 使用凭证主键获取凭证信息
                            RestfulResponse<CwGlVoucherWeb, CurrencyMeta> res2 = selectOrderMakingDetil(s, "1"); //
                            if (res2 == null || res2.getCode() != 1) {
                                return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.VOUCHER_DETAIL_NOT_FOUND.message(), MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
                            }
                            CwGlVoucherWeb cwGlVoucherWeb = res2.getData();
                            CwBdGlorgbook cwBdGlorgbook = cwBdGlorgbookMapper.selectByPrimaryKey(cwGlVoucherWeb.getPkGlorgbook());
                            String deptCode = "";
                            if (cwGlVoucherRequest.getZxmbh() != null && !"".equals(cwGlVoucherRequest.getZxmbh())) {
                                deptCode = pmProjectChildMapper.selectDeptCodeByZxmbh(cwGlVoucherRequest.getZxmbh());
                            }

                            String finalNcAbstracts = cwBdGlorgbookMapper.getNCAbstracts(cwGlVoucherRequest.getLcslywbh()) + cwGlVoucherRequest.getPayee();

                            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String time = df.format(new Date());

                            Document document = DocumentHelper.createDocument();

                            // 拼装接口所需格式的xml
                            Element ufinterface = document.addElement("ufinterface");
                            ufinterface.addAttribute("account", "");
                            ufinterface.addAttribute("billtype", "vouchergl");
                            ufinterface.addAttribute("businessunitcode", "");
                            ufinterface.addAttribute("filename", "");
                            ufinterface.addAttribute("groupcode", "1");
                            ufinterface.addAttribute("isexchange", "");
                            ufinterface.addAttribute("orgcode", "13805");
                            ufinterface.addAttribute("receiver", "");
                            ufinterface.addAttribute("replace", "");
                            ufinterface.addAttribute("roottag", "");
                            ufinterface.addAttribute("sender", "nc65");

                            Element voucher = ufinterface.addElement("voucher");
                            Element voucher_head = voucher.addElement("voucher_head");
                            Element pk_voucher = voucher_head.addElement("pk_voucher").addText("");                                   // -------
                            Element pk_vouchertype = voucher_head.addElement("pk_vouchertype").addText("01");
                            Element year = voucher_head.addElement("year").addText(cwGlVoucherWeb.getPeriod().split("-")[0]);  //period 前四
                            Element pk_system = voucher_head.addElement("pk_system").addText("GL");
                            Element voucherkind = voucher_head.addElement("voucherkind").addText("0");
                            Element pk_accountingbook = voucher_head.addElement("pk_accountingbook").addText("13805-0002");      // -------cw_bd_glorgbook --xtxmbh
                            Element discardflag = voucher_head.addElement("discardflag").addText("N");
                            Element period = voucher_head.addElement("period").addText(cwGlVoucherWeb.getPeriod().split("-")[1]);                  // -------period 6-7
                            Element no = voucher_head.addElement("no").addText("");                                                      // ------- 空
                            Element attachment = voucher_head.addElement("attachment").addText("2");                                    // ------- 空
                            Element prepareddate = voucher_head.addElement("prepareddate").addText(time);
                            Element pk_prepared = voucher_head.addElement("pk_prepared").addText("tongjx");
                            //   Element pk_prepared = voucher_head.addElement("pk_prepared").addText(cwGlVoucherWeb.getPkPrepared());
                            Element pk_org = voucher_head.addElement("pk_org").addText("13805");                                          // -------13805
                            Element pk_org_v = voucher_head.addElement("pk_org_v").addText("13805");                                          // -------13805
                            Element pk_group = voucher_head.addElement("pk_group").addText("1");                                          // -------1

                            List<CwGlDetailWeb> cwGlDetailList = cwGlVoucherWeb.getCwGlDetailList();
                            if (cwGlDetailList != null) {
                                cwGlDetailList.sort((o1, o2) -> {
                                    if (o1.getDebitamount().compareTo(new BigDecimal(0)) > 0 || o1.getLocaldebitamount().compareTo(new BigDecimal(0)) > 0) {
                                        return -1;
                                    } else {
                                        return 1;
                                    }
                                });
                                if (cwGlDetailList.size() > 0) {
                                    Element details = voucher_head.addElement("details");

                                    String finalDeptCode = deptCode;
                                    cwGlDetailList.forEach(data -> {
                                        Element item = details.addElement("item");
                                        String code = "";
                                        String index = "";
                                        if (data.getDebitamount().compareTo(new BigDecimal(0)) > 0 || data.getLocaldebitamount().compareTo(new BigDecimal(0)) > 0) {
                                            code = "122104";
                                            index = "1";
                                        } else {
                                            if ("1".equals(cwGlVoucherRequest.getPzlx())) {
                                                code = "1002010201";
                                            }
                                            if ("2".equals(cwGlVoucherRequest.getPzlx())) {
                                                code = "122199";
                                            }
                                            index = "2";
                                        }
                                        Element detailindex = item.addElement("detailindex").addText(index);
                                        Element accsubjcode = item.addElement("accsubjcode").addText(code);
                                        Element explanation = item.addElement("explanation").addText(finalNcAbstracts);
                                        Element verifydate = item.addElement("verifydate").addText(time);       // -------
                                        Element price = item.addElement("price").addText("");                                                // -------空
                                        Element excrate2 = item.addElement("excrate2").addText("");                                          // -------
                                        Element debitquantity = item.addElement("debitquantity").addText("");                              // -------
                                        Element debitamount = item.addElement("debitamount").addText(String.valueOf(data.getDebitamount()));
                                        Element groupdebitamount = item.addElement("groupdebitamount").addText("");                              // -------
                                        Element globaldebitamount = item.addElement("globaldebitamount").addText("");                        // -------
                                        Element localdebitamount = item.addElement("localdebitamount").addText(String.valueOf(data.getLocaldebitamount()));
                                        Element creditquantity = item.addElement("creditquantity").addText("");                              // -------
                                        Element creditamount = item.addElement("creditamount").addText(String.valueOf(data.getCreditamount()));
                                        Element groupcreditamount = item.addElement("groupcreditamount").addText("");                        // -------
                                        Element globalcreditamount = item.addElement("globalcreditamount").addText("");                        // -------
                                        Element localcreditamount = item.addElement("localcreditamount").addText(String.valueOf(data.getLocalcreditamount()));
                                        Element pk_currtype = item.addElement("pk_currtype").addText("CNY");
                                        Element pk_accasoa = item.addElement("pk_accasoa").addText(code);
                                        if (!"122199".equals(code)) {

                                            Element ass = item.addElement("ass");
                                            Element item2 = ass.addElement("item");
                                            if ("122104".equals(code)) {
                                                Element pk_Checktype = item2.addElement("pk_Checktype").addText("0001");
                                                Element pk_Checkvalue = item2.addElement("pk_Checkvalue").addText(finalDeptCode);
                                                Element item3 = ass.addElement("item");
                                                Element pk_Checktype2 = item3.addElement("pk_Checktype").addText("XM");
                                                Element pk_Checkvalue2 = item3.addElement("pk_Checkvalue").addText(cwBdGlorgbook.getXtxmbh());  //
                                            }
                                            if ("1002010201".equals(code)) {
                                                Element pk_Checktype = item2.addElement("pk_Checktype").addText("0007");
                                                Element pk_Checkvalue = item2.addElement("pk_Checkvalue").addText("1124");
                                            }
                                        }
                                    });
                                }
                            }

                            String xmlStr = document.asXML();

                            int sysint_basews03 = 1000 * 60 * 30;// 接口最大等待时间

                            log.info(pushVoucherInterface);
                            String sysinit_basews01 = pushVoucherInterface;//接口地址

                            URL realURL = new URL(sysinit_basews01);
                            HttpURLConnection connection = (HttpURLConnection) realURL
                                    .openConnection();
                            //			Logger.debug("连接已开启");
                            connection.setConnectTimeout(sysint_basews03);
                            //			Logger.debug("设置连接时间:" + sysint_basews03);
                            connection.setDoOutput(true);
                            connection.setDoInput(true);
                            connection.setRequestProperty("Content-type", "text/xml");
                            connection.setRequestMethod("POST");
                            // 解决生僻汉字乱码问题
                            DefaultDocument doc = (DefaultDocument) DocumentHelper
                                    .parseText(xmlStr);
                            doc.setXMLEncoding("GBK");
                            OutputFormat format = OutputFormat.createPrettyPrint();
                            format.setEncoding("GBK");
                            OutputStreamWriter osw = new OutputStreamWriter(
                                    connection.getOutputStream(), "GBK");
                            // end
                            XMLWriter writer2 = new XMLWriter(osw, format);
                            writer2.write(doc);
                            writer2.close();
                            InputStream inputStream = connection.getInputStream();
                            byte[] tempBytes = new byte[inputStream.available()];
                            inputStream.read(tempBytes);

                    /*for (int count = 0; (count = inputStream.read(tempBytes)) != -1; )
                        strbuf.append(new String(tempBytes, 0, count, "utf-8"));*/

                            inputStream.close();
                            connection.disconnect();
                            String result = new String(tempBytes);
                            log.info("<><><><><><><><>" + result);

                            String resultCode = result.substring(result.indexOf("successful=") + 12, result.indexOf("successful=") + 13);
                            String resultInfo = result.substring(result.lastIndexOf("<resultdescription>") + 19, result.lastIndexOf("</resultdescription>"));

                            cwBdRecordNcpush.setPushType("Y".equals(resultCode) ? "1" : "0");
                            cwBdRecordNcpush.setReturnData(result);
                            cwBdRecordNcpush.setRemark(resultInfo);
                            cwBdRecordNcpushMapper.insertSelective(cwBdRecordNcpush);

                            if ("0".equals(cwBdRecordNcpush.getPushType())) {
                                return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.NC_CHECK_FAIL.message(), MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
                            }
                        }
                    }
                } else {
                    return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.VOUCHER_NOT_FOUND.message(), MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
                }
            } catch (Exception e) {
                log.error("推送nc系统异常>>>>>>>>>", e);
                if (cwBdRecordNcpush.getId() == null) {
                    cwBdRecordNcpush.setId(IdGenerator.INSTANCE.nextId());
                }
                cwBdRecordNcpush.setPushType("0");
                cwBdRecordNcpush.setReturnData("推送nc系统异常>>>>>>>>>" + e);
                cwBdRecordNcpush.setRemark("服务未调通");
                cwBdRecordNcpushMapper.insertSelective(cwBdRecordNcpush);

                return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, SysConstants.DEFAULT_MESSAGE.OPERATION_FAIL, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
            }
        }

        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));

    }

    /**
     * 功能描述：根据子项目编号和制单日期查询凭证详情
     *
     * @param xtzxmbh
     * @param dateTime
     * @return RestfulResponse<Object, CurrencyMeta>
     * @author leiyu
     * @date 2020年6月18日 下午2:29:37
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> searchVoucherDetailForXtzxmbh(String xtzxmbh, String dateTime) {
        List<CwGlVoucherWeb> list = cwGlVoucherMapper.searchVoucherDetailForXtzxmbh(xtzxmbh, dateTime);
        if (list.size() == 0) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.NOT_FOUND_VOUCHERDETAIL.message(),
                    MetaDataUtil.getMeta(tracer, FinanceStatusCode.NOT_FOUND_VOUCHERDETAIL));
        }
        // 对摘要重新赋值
        for (CwGlVoucherWeb cwGlVoucherWeb : list) {
            cwGlVoucherWeb.getCwGlDetailList().forEach(x -> {
                List<CwGlDetail> selectByPkVoucher = cwGlDetailMapper.selectByPkVoucher(x.getPkVoucher(), "1");
                // 对摘要重新赋值
                for (CwGlDetail cwGlDetail : selectByPkVoucher) {
                    if (x.getPkDetail().equals(cwGlDetail.getPkDetail())) {
                        x.setAbstracts(cwGlDetail.getAbstracts());
                    }
                }
            });
        }
        return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, list, MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }

}
