package com.dxhy.domestic.service.drawback.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.api.model.config.Business;
import com.dxhy.api.model.config.Tax;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.AuthStatusEnum;
import com.dxhy.common.enums.FpztEnum;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.service.impl.TabulateRedisServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.UserInfoUtil;
import com.dxhy.common.utils.BaseContextHandler;
import com.dxhy.common.utils.RRException;
import com.dxhy.common.vo.InvoiceLog;
import com.dxhy.domestic.dao.DomesticRecordInvoiceDao;
import com.dxhy.domestic.model.dto.*;
import com.dxhy.domestic.model.vo.*;
import com.dxhy.domestic.service.drawback.DomesticInvoiceDrawbackService;
import com.dxhy.domestic.util.InvoiceTypeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author dxhy
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Slf4j
@Service("domesticInvoiceDrawbackService")
public class DomesticInvoiceDrawbackServiceImpl implements DomesticInvoiceDrawbackService {

    /** 查询条件中全部对应值 */
    private static final String CONDITION_ALL_TAG = "99";
    /** 认证方式，0：手工认证，1：导入认证 */
    private static final String[] AUTHENTICATION_WAY = {"0", "1"};
    /** 判断日期 yyyy-mm-dd 的正则表达式（能够区分真实日期，区分闰年） */
    private static final String PATTERN_JUDGE_DATE =
        "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
    /** 判断小数点后2位的数字的正则表达式 */
    private static final String PATTERN_JUDGE_AMOUNT = "^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$";
    @Resource
    private InvoiceLogService invoiceLogService;
    @Resource
    private DomesticRecordInvoiceDao domesticRecordInvoiceDao;
    @Resource
    private TabulateRedisServiceImpl tabulateRedisService;
    @Resource
    private DictdetaServcice dictdetaServcice;

    /**
     * 退税手工认证列表查询
     *
     * @param dto
     *            查询条件
     * @param userInfo
     *            登陆信息
     */
    @Override
    public CommonListResponseVO<ManualAuthenticationListVO> authenticationList(AuthenticationConditionDTO dto,
        UserInfo userInfo) {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);

        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(dto.getCompany(), dto.getMenuId());

        CommonListResponseVO<ManualAuthenticationListVO> responseVO =
            tabulateMenu.toJavaObject(CommonListResponseVO.class);
        // 判断购方税号是否指定
        List<String> buyerTaxNoList;
        if (CONDITION_ALL_TAG.equals(dto.getBuyerTaxNo())) {
            buyerTaxNoList = UserInfoUtil.getGfshAll(userInfo.getOrg());
        } else {
            buyerTaxNoList = new ArrayList<>();
            buyerTaxNoList.add(dto.getBuyerTaxNo());
        }

        // 将购方税号放入查询条件中并查询
        dto.setTaxNoList(buyerTaxNoList);
        if (CollectionUtils.isEmpty(dto.getTaxNoList())) {
            responseVO.setDatalist(new ArrayList<>());
            responseVO.setTotal(0L);
            return responseVO;
        }
        PageHelper.startPage(dto.getCurrentPage(), dto.getPageSize());

        if(StringUtils.isNotBlank(dto.getInvoiceNo())){
            if(dto.getInvoiceNo().length()==8){

            }else {
                dto.setEleInvoiceNo(dto.getInvoiceNo());
                dto.setInvoiceNo("");
            }
        }

        List<ManualAuthenticationListVO> resultList = domesticRecordInvoiceDao.selectByAuthenticationCondition(dto);
        PageInfo<ManualAuthenticationListVO> pageInfo = new PageInfo<>(resultList);
        int startRow = new Long(pageInfo.getStartRow()).intValue();
        // 将查询结果转化成VO
        resultList.forEach(invoice -> {
            invoice.setOrder(String.valueOf(resultList.indexOf(invoice) + startRow));
            String judgeResult = judgeInvoiceSelected(invoice);
            invoice.setSelected(StringUtils.isEmpty(judgeResult) ? "1" : "0");
            invoice.setSelectDisabled(judgeResult);
            if(StringUtils.isNotEmpty(invoice.getInvoiceAmount())){
                invoice.setInvoiceAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(invoice.getInvoiceAmount())));
            }
            if(StringUtils.isNotEmpty(invoice.getTaxAmount())){
                invoice.setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(invoice.getTaxAmount())));
            }
            // 字典转换
            invoice.setSignInType(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, invoice.getSignInType()));
            invoice.setSignInStatus(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, invoice.getSignInStatus()));
            invoice.setInvoiceStatus(
                dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, invoice.getInvoiceStatus()));
        });
        // 当前页为第一页时统计总税额
        if (dto.getCurrentPage() == 1) {
            QuerySummaryDTO querySummaryDTO = domesticRecordInvoiceDao.selectTotalAmount(dto);
            responseVO.setTotalAmount(querySummaryDTO.getTotalAmount());
            responseVO.setTotalTaxAmount(querySummaryDTO.getTotalTaxAmount());
            responseVO.formatTotalAmount();
        }
        responseVO.setDatalist(resultList);
        responseVO.setTotal(pageInfo.getTotal());
        return responseVO;
    }

    /**
     * 退税手工认证，退税导入认证
     *
     * @param dto
     *            认证信息
     * @param userInfo
     *            用户信息
     * @param userName
     *            用户名
     */
    @Override
    public AuthenticationResultVO authentication(AuthenticationDTO dto, UserInfo userInfo, String userName) {
        if (!Arrays.asList(AUTHENTICATION_WAY).contains(dto.getAuthenticationWay())) {
            throw new RRException("未知的认证方式");
        }
        List<String> buyerTaxNoList = userInfo.getOrg().stream().map(Tax::getTaxno).collect(Collectors.toList());
        if (buyerTaxNoList.isEmpty()) {
            throw new RRException("当前登录用户未配置购方税号");
        }
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        List<String> uuidList = dto.getUuidList();
        List<TDxRecordInvoice> invoiceList = domesticRecordInvoiceDao.selectByUuidList(uuidList);
        // 记录失败原因
        Map<String, List<String>> errorMap = new HashMap<>(16);
        String totalAuthenticationAmount = "0";
        String totalAuthenticationTaxAmount = "0";
        int successCount = 0;
        List<InvoiceLog> logList = new ArrayList<>();
        for (TDxRecordInvoice invoice : invoiceList) {
            String errMsg = judgeInvoiceAuthentication(invoice);
            if (!StringUtils.isEmpty(errMsg)) {
                List<String> noList = errorMap.get(errMsg) == null ? new ArrayList<>() : errorMap.get(errMsg);
                noList.add(invoice.getInvoiceNo());
                errorMap.put(errMsg, noList);
                continue;
            }
            Calendar calendar = Calendar.getInstance();
            invoice.setRzlx("2");
            invoice.setBdkStatus("3");
            invoice.setGxType("0".equals(dto.getAuthenticationWay()) ? "7" : "8");
            invoice.setAuthStatus("2");
            invoice.setConfirmDate(calendar.getTime());
            invoice.setRzhBelongDate(new SimpleDateFormat("yyyyMM").format(calendar.getTime()));
            invoice.setConfirmUser(userName);
            invoice.setGxUserAccount(BaseContextHandler.getLonginname());
            invoice.setGxUserName(userName);
            DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_WRITE);
            int count = domesticRecordInvoiceDao.updateByPrimaryKeySelective(invoice);

            // 统计成功金额数量
            successCount += count;
            if(ObjectUtil.isNotEmpty(invoice.getInvoiceAmount())){
                totalAuthenticationAmount =
                        MathUtil.round(MathUtil.add(totalAuthenticationAmount, invoice.getInvoiceAmount().toPlainString()));
            }

            if(ObjectUtil.isNotEmpty(invoice.getTaxAmount())){
                totalAuthenticationTaxAmount =
                        MathUtil.round(MathUtil.add(totalAuthenticationTaxAmount, invoice.getTaxAmount().toPlainString()));
            }

            // 记录日志
            InvoiceLog invoiceLog = new InvoiceLog();
            invoiceLog.setInvoiceCode(invoice.getInvoiceCode());
            invoiceLog.setInvoiceNo(invoice.getInvoiceNo());
            invoiceLog.setType("7");
            invoiceLog.setCreateDate(new Date());
            invoiceLog.setInputName(userName);
            invoiceLog.setInputStatus("14");
            logList.add(invoiceLog);
        }

        if (!logList.isEmpty()) {
            invoiceLogService.toInvoiceLog(logList);
        }

        AuthenticationResultVO resultVO = new AuthenticationResultVO();
        resultVO.setSuccessCount(String.valueOf(successCount));
        resultVO.setTotalAmount(totalAuthenticationAmount);
        resultVO.setTotalTax(totalAuthenticationTaxAmount);
        StringBuilder errMsg = new StringBuilder();
        errorMap.forEach((k, v) -> errMsg.append(k).append(JSON.toJSONString(v)).append(" \n "));

        resultVO.setMessage(errMsg.toString());
        return resultVO;
    }

    /**
     * 退税导入认证导入结果校验
     *
     * @param dtoList
     *            导入信息
     * @param userInfo
     *            用户信息
     * @param menuId
     *            菜单id
     */
    @Override
    public CommonListResponseVO<ImportAuthenticationListVO>
        importAuthenticationCheck(List<AuthenticationImportDTO> dtoList, UserInfo userInfo, String menuId) {

        log.info("退税导入认证，dtoList：{}", JSON.toJSONString(dtoList));

        List<String> taxNoList = userInfo.getOrg().stream().map(Tax::getTaxno).collect(Collectors.toList());

        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);

        List<ImportAuthenticationListVO> list = dtoList.stream().map(dto -> {
            ImportAuthenticationListVO vo = new ImportAuthenticationListVO();
            BeanUtils.copyProperties(dto, vo);
            vo.setOrder(String.valueOf(dtoList.indexOf(dto) + 1));
            vo.setSelected("1");
            //如果号码是20位，拆分代码号码
            if(StringUtils.isNotEmpty(dto.getInvoiceNo())&&dto.getInvoiceNo().length()==20){
                dto.setInvoiceCode(dto.getInvoiceNo().substring(0,12));
                dto.setInvoiceNo(dto.getInvoiceNo().substring(12,20));
            }
            // 非空校验+格式校验+重复校验
            String judgeResult = judgeImportInvoice(dto, dtoList);
            if (!StringUtils.isBlank(judgeResult)) {
                vo.setAuthenticationFail(judgeResult);
                vo.setSelected("0");
                return vo;
            }
            String uuid = dto.getInvoiceCode() + dto.getInvoiceNo();
            List<TDxRecordInvoice> TDxRecordInvoices =
                domesticRecordInvoiceDao.selectByUuidList(Collections.singletonList(uuid));
            // 底账信息查询
            if (TDxRecordInvoices.isEmpty()) {
                vo.setAuthenticationFail("无底账信息");
                vo.setSelected("0");
                return vo;
            }
            TDxRecordInvoice invoice = TDxRecordInvoices.get(0);
            // 权限校验
            if (!taxNoList.contains(invoice.getGfTaxNo())) {
                vo.setAuthenticationFail("无该发票购方税号权限");
                vo.setSelected("0");
                return vo;
            }
            // 填充vo
            convertImportVo(invoice, vo);
            if ("1".equals(userInfo.getQsStatus()) && !"1".equals(invoice.getQsStatus())) {
                vo.setAuthenticationFail("发票未签收");
                vo.setSelected("0");
                return vo;
            }
            // 与底账库信息对比
            if (!dto.getInvoiceNo().equals(vo.getInvoiceNo()) || !dto.getInvoiceCode().equals(vo.getInvoiceCode())) {
                vo.setAuthenticationFail("发票代码号码与底账库信息不一致");
                vo.setSelected("0");
                return vo;
            }
            if (!dto.getInvoiceDate().equals(vo.getInvoiceDate())) {
                vo.setAuthenticationFail("开票日期与底账库信息不一致");
                vo.setSelected("0");
                return vo;
            }
            if (!AmountFormatUtil.fmtMicrometer(dto.getTaxAmount()).equals(vo.getTaxAmount())) {
                vo.setAuthenticationFail("税额与底账库信息不一致");
                vo.setSelected("0");
                return vo;
            }
            if ("1".equals(invoice.getSfdbts())) {
                vo.setAuthenticationFail("代办退税发票不允许导入");
                vo.setSelected("0");
                return vo;
            }
            vo.setEleInvoiceNo(invoice.getEleInvoiceNo());
            //dto.setEleInvoiceNo(invoice.getEleInvoiceNo());

            return vo;
        }).collect(Collectors.toList());

        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(userInfo.getCompany(), menuId);

        CommonListResponseVO<ImportAuthenticationListVO> responseVO =
            tabulateMenu.toJavaObject(CommonListResponseVO.class);
        responseVO.setDatalist(list);
        responseVO.setTotal((long)list.size());
        return responseVO;
    }

    /**
     * 退税认证查询列表
     *
     * @param dto
     *            查询条件
     * @param userInfo
     *            用户登陆信息
     */
    @Override
    public CommonListResponseVO<AuthenticationCheckListVO> authenticationCheck(AuthenticationCheckConditionDTO dto,
        UserInfo userInfo) {

        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(dto.getCompany(), dto.getMenuId());

        CommonListResponseVO<AuthenticationCheckListVO> responseVO =
            tabulateMenu.toJavaObject(CommonListResponseVO.class);

        // 判断购方税号是否指定
        List<String> buyerTaxNoList;
        if (!CONDITION_ALL_TAG.equals(dto.getBuyerTaxNo())) {
            buyerTaxNoList = new ArrayList<>();
            buyerTaxNoList.add(dto.getBuyerTaxNo());
        } else {
            buyerTaxNoList = userInfo.getOrg().stream().map(Tax::getTaxno).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(buyerTaxNoList)) {
            responseVO.setDatalist(new ArrayList<>());
            responseVO.setTotal(0L);
            return responseVO;
        }
        dto.setTaxNoList(buyerTaxNoList);
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        PageHelper.startPage(dto.getCurrentPage(), dto.getPageSize());

        if(StringUtils.isNotBlank(dto.getInvoiceNo())){
            if(dto.getInvoiceNo().length()==8){

            }else {
                dto.setEleInvoiceNo(dto.getInvoiceNo());
                dto.setInvoiceNo("");
            }
        }

        List<AuthenticationCheckListVO> resultList = domesticRecordInvoiceDao.selectByAuthenticationCheckCondition(dto);
        PageInfo<AuthenticationCheckListVO> pageInfo = new PageInfo<>(resultList);
        int startRow = new Long(pageInfo.getStartRow()).intValue();
        resultList.forEach(result -> {
            result.setOrder(String.valueOf(resultList.indexOf(result) + startRow));
            if(StringUtils.isNotEmpty(result.getInvoiceAmount())){
                result.setInvoiceAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(result.getInvoiceAmount())));
            }
            if(StringUtils.isNotEmpty(result.getTaxAmount())){
                result.setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(result.getTaxAmount())));
            }
            // 字典转换
            result.setInvoiceStatus(
                dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, result.getInvoiceStatus()));
            result.setSignInStatus(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, result.getSignInStatus()));
            result.setSignInType(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, result.getSignInType()));
            result.setAuthenticationStatus(
                dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, result.getAuthenticationStatus()));
            result.setAuthenticationType(
                dictdetaServcice.queryDictName(DictConstant.INVOICE_RZLX, result.getAuthenticationType()));
            result.setAuthenticationDetailStatus(
                dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, result.getAuthenticationDetailStatus()));
        });
        if (dto.getCurrentPage() == 1) {
            QuerySummaryDTO querySummaryDTO = domesticRecordInvoiceDao.selectTotalAmountByAuthenticationCheck(dto);
            responseVO.setTotalTaxAmount(querySummaryDTO.getTotalTaxAmount());
            responseVO.setTotalAmount(querySummaryDTO.getTotalAmount());
            responseVO.formatTotalAmount();
        }
        responseVO.setDatalist(resultList);
        responseVO.setTotal(pageInfo.getTotal());

        return responseVO;
    }

    /**
     * 退税导入认证DO向VO转换
     *
     * @param invoice
     *            抵账信息
     * @param vo
     *            导入信息
     */
    private void convertImportVo(TDxRecordInvoice invoice, ImportAuthenticationListVO vo) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        BeanUtils.copyProperties(invoice, vo);
        vo.setInvoiceDate(dateFormat.format(invoice.getInvoiceDate()));
        vo.setBuyerName(invoice.getGfName());
        vo.setSellerName(invoice.getXfName());
        if(ObjectUtil.isNotEmpty(invoice.getInvoiceAmount())){
            vo.setInvoiceAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(invoice.getInvoiceAmount().toPlainString())));
        }
        if(ObjectUtil.isNotEmpty(invoice.getTaxAmount())){
            vo.setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(invoice.getTaxAmount().toPlainString())));
        }

        vo.setSignInStatus(InvoiceTypeUtils.signInStatusTransfer(invoice.getQsStatus()));
        if (invoice.getQsDate() != null) {
            vo.setSignInDate(dateFormat.format(invoice.getQsDate()));
        }
        vo.setSignInType(InvoiceTypeUtils.signInTypeTransfer(invoice.getQsType()));
        vo.setSignInPeople(invoice.getQsName());
        vo.setTaxPeriod(invoice.getDqskssq());
        if (!"0".equals(invoice.getInvoiceStatus())&&!"7".equals(invoice.getInvoiceStatus())) {
            vo.setSelected("0");
            vo.setAuthenticationFail("发票" + FpztEnum.getEnumMap().get(invoice.getInvoiceStatus()));
        }
        if (!Arrays.asList("0", "5", "6").contains(invoice.getAuthStatus())) {
            vo.setSelected("0");
            vo.setAuthenticationFail("发票" + AuthStatusEnum.getVal(invoice.getAuthStatus()));
        }
        if (!"0".equals(invoice.getRzhYesorno())) {
            vo.setSelected("0");
            vo.setAuthenticationFail("发票已认证或者已认证不抵扣");
        }

    }

    /**
     * 校验导入发票信息
     *
     * @param dto
     *            认证信息
     * @param dtoList
     *            认证信息
     */
    private String judgeImportInvoice(AuthenticationImportDTO dto, List<AuthenticationImportDTO> dtoList) {
        String invoiceCode = dto.getInvoiceCode();
        String invoiceNo = dto.getInvoiceNo();
        String invoiceDate = dto.getInvoiceDate();
        String taxAmount = dto.getTaxAmount();

        if (StringUtils.isEmpty(invoiceCode)) {
            return "发票代码格式错误";
        }
        if (invoiceCode.length() != 10 && invoiceCode.length() != 12) {
            return "发票代码格式错误";
        }
        if (StringUtils.isBlank(invoiceNo) && invoiceNo.length() != 8) {
            return "发票号码格式错误";
        }
        if (StringUtils.isBlank(invoiceDate)) {
            return "开票日期不能为空";
        }
        // 判断日期 yyyy-mm-dd 的正则表达式（能够区分真实日期，区分闰年）
        Pattern pattern = Pattern.compile(PATTERN_JUDGE_DATE);
        Matcher match = pattern.matcher(invoiceDate);
        if (!match.matches()) {
            return "开票日期格式错误";
        }
        if (StringUtils.isBlank(taxAmount)) {
            return "税额不能为空";
        }
        pattern = Pattern.compile(PATTERN_JUDGE_AMOUNT);
        if (!pattern.matcher(taxAmount).matches()) {
            return "税额格式错误";
        }

        List<TDxRecordInvoice> TDxRecordInvoices =
                domesticRecordInvoiceDao.selectByUuidList(Arrays.asList(invoiceCode+invoiceNo));
        if(!CollectionUtils.isEmpty(TDxRecordInvoices)){
            // 发票类型校验
            //InvoiceUtil invoiceUtil = new InvoiceUtil(dto.getInvoiceCode());
            String invoiceType = TDxRecordInvoices.get(0).getInvoiceType();
            if (!Arrays.asList("01", "08","31","185").contains(invoiceType)) {
                return "发票类型错误";
            }
        }

        // 重复校验
        String uuid = dto.getInvoiceCode() + dto.getInvoiceNo();
        long repeatCount = dtoList.subList(dtoList.indexOf(dto), dtoList.size()).stream()
            .filter(sub -> uuid.equals(sub.getInvoiceCode() + sub.getInvoiceNo())).count();
        if (repeatCount > 1) {
            return "重复发票";
        }

        return null;
    }

    /**
     * 校验发票认证信息
     *
     * @param invoice
     *            发票信息
     * @return 返回
     */
    private String judgeInvoiceAuthentication(TDxRecordInvoice invoice) {
        if (StringUtils.isEmpty(invoice.getInvoiceStatus())
            && !FpztEnum.ZC.getFpztDm().equals(invoice.getInvoiceStatus())
            && !FpztEnum.BFNC.getFpztDm().equals(invoice.getInvoiceStatus())
        ) {
            return "以下发票号码的状态异常：";
        }

        if (StringUtils.isEmpty(invoice.getInvoiceType())
            || !Arrays.asList("01", "08","31","185").contains(invoice.getInvoiceType())) {
            return "以下发票号码的类型异常：";
        }
        //如果是代扣代缴，不验证以下信息
        if(!"4".equals(invoice.getXxly())){
            if (invoice.getTaxAmount().compareTo(BigDecimal.ZERO) < 0) {
                return "以下发票号码的税额小于零：";
            }
        }
        if (StringUtils.isEmpty(invoice.getAuthStatus())
            || !Arrays.asList("0", "5", "6").contains(invoice.getAuthStatus())) {
            return "以下发票号码的认证状态异常：";
        }
        return null;
    }

    /**
     * 校验发票是否可以选中
     *
     * @param invoice
     *            发票信息
     */
    private String judgeInvoiceSelected(ManualAuthenticationListVO invoice) {
        if (!StringUtils.isEmpty(invoice.getInvoiceStatus())
            && !FpztEnum.ZC.getFpztDm().equals(invoice.getInvoiceStatus())
            && !FpztEnum.BFNC.getFpztDm().equals(invoice.getInvoiceStatus())
        ) {
            return "发票状态异常,无法选中";
        }
        //如果是代扣代缴，不验证以下信息
        if(!"4".equals(invoice.getXxly())){
            if (new BigDecimal(invoice.getInvoiceAmount()).compareTo(BigDecimal.ZERO) < 0) {
                return "发票金额异常,无法选中";
            }
            if (new BigDecimal(invoice.getTaxAmount()).compareTo(BigDecimal.ZERO) < 0) {
                return "发票税额异常,无法选中";
            }
        }

        return null;
    }

    /**
     * 根据deptId获取businessName
     *
     * @param deptId
     *            部门信息
     * @param userInfo
     *            用户信息
     */
    private String getBusinessName(String deptId, UserInfo userInfo) {
        if (StringUtils.isEmpty(deptId) || userInfo == null) {
            return null;
        }
        List<Business> business = userInfo.getBusiness();
        return business.stream().filter(b -> deptId.equals(b.getBusinessCode())).findFirst()
            .map(Business::getBusinessName).orElse(null);
    }
}
