package com.dxhy.erp.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.enums.SNFplxEnum;
import com.dxhy.common.util.InvoiceUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.utils.R;
import com.dxhy.common.vo.UserInfo;
import com.dxhy.erp.dao.*;
import com.dxhy.erp.entity.*;
import com.dxhy.erp.entity.kfpt.ApiCheckInvoiceSingleRequest;
import com.dxhy.erp.entity.kfpt.ApiRequest;
import com.dxhy.erp.entity.kfpt.ApiResponse;
import com.dxhy.erp.entity.kfpt.TokenResponse;
import com.dxhy.erp.entity.sdny.InvoiceDetail;
import com.dxhy.erp.entity.sdny.InvoiceInfo;
import com.dxhy.erp.entity.sdny.SNInvoice;
import com.dxhy.erp.entity.sdny.area.Area;
import com.dxhy.erp.utils.Base64;
import com.dxhy.erp.utils.*;
import com.google.gson.JsonObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 与山东能源交互数据主类
 *
 * @author ariesy
 * @date 2023年3月22日下午5:02:49
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Service
@Slf4j
public class SNPushCheckRecordService extends AbstractServiceAdapter {

    @Value("${sdny.snYxUrl}")
    private String snYxUrl;

    @Value("${params.api.invoiceCheckSingleUrl}")
    private String invoiceCheckSingleUrl;

    @Value("${params.api.appKey}")
    private String appKey;

    @Value("${params.api.appSecret}")
    private String appSecret;

    @Value("${params.api.entCode}")
    private String entCode;

    @Value("${po.userName}")
    private String userName;

    @Value("${po.password}")
    private String password;

    @Resource
    private InvoiceQueryUtil invoiceQueryUtil;

    @Resource
    private ApiUtils apiUtils;

    @Autowired
    private AreaDao areaDao;

    @Resource
    private BaseTDxTaxCurrentDao baseTDxTaxCurrentDao;

    @Resource
    private TDxInvoiceReimburseDao invoiceReimburseDao;

    @Resource
    private BaseTDxRecordInvoiceDao baseTDxRecordInvoiceDao;

    @Resource
    private TDxInvoiceReimburseService tDxInvoiceReimburseService;

    @Resource
    private SysDeptDao sysDeptDao;

    @Resource
    private SNPushCheckRecordService snPushCheckRecordService;

    @Resource
    private SignSaveInvoiceInfoService signSaveInvoiceInfoService;

    @Resource
    private TdxPlatformCheckLogService platformCheckLogService;

    public String pushCheckResultToSAP(String requestParam) {
        log.info("获取请求参数：{} , 请求地址：{}", requestParam, snYxUrl);
        String post = HttpUtils.sendPo(snYxUrl, requestParam, userName, password);
        log.info("获取返回信息：{}", post);

        return post;
    }

    public String pushInvoiceToRecordInvoice(SNInvoice snInvoice, String taxNo, String company, String imageId, String compCode)  {

        TDxInvoiceReimburse recordInvoice = new TDxInvoiceReimburse();
//        DynamicContextHolder.push(DbConstant.BASICS_READ);
//
//        SysDeptEntity orgByCompCode = sysDeptDao.getOrgByCompCode(compCode);
//        log.info("查询的组织信息为:{}",JSONObject.toJSONString(orgByCompCode));
//        recordInvoice.setGfTaxNo(orgByCompCode.getTaxno());
//        recordInvoice.setGfName(orgByCompCode.getTaxname());
//        recordInvoice.setGfAddressAndPhone(orgByCompCode.getAddress() + orgByCompCode.getPhone());
//        recordInvoice.setGfBankAndNo(orgByCompCode.getBank() + orgByCompCode.getAccount());

        QueryWrapper<BaseTDxTaxCurrent> currentWrapper = new QueryWrapper<>();
        currentWrapper.eq("taxno", taxNo);
        DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
        BaseTDxTaxCurrent current = baseTDxTaxCurrentDao.selectOne(currentWrapper);


        String fpdm = snInvoice.getInvoiceCode();
        String fphm = snInvoice.getInvoiceNumber();

        QueryWrapper<TDxInvoiceReimburse> recordWrapper = new QueryWrapper<>();
        String uuid = "";
        if (StringUtils.isNoneBlank(fpdm)) {
            uuid = fpdm + fphm;
        } else {
            uuid = fphm;
        }
        recordWrapper.eq("uuid", uuid);

        TDxInvoiceReimburse baseTDxRecordInvoice = invoiceReimburseDao.selectOne(recordWrapper);


        String kprq = snInvoice.getBillingDate();
        String je = snInvoice.getTotalAmount();
        String amountTax = snInvoice.getAmountTax();
        String xfsh = snInvoice.getSalesTaxNo();
        String se = snInvoice.getTotalTax();
        String gfsbh = snInvoice.getPurchaserTaxNo();
        String gfmc = snInvoice.getPurchaserName();
        String invoiceType = snInvoice.getInvoiceType();


        recordInvoice.setUuid(fpdm + fphm);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(new Date());
        if (kprq != null) {
            recordInvoice.setInvoiceDate(kprq);
        } else {
            recordInvoice.setInvoiceDate(format1);
            log.error("开票日期为空.请检查发票");
        }
        recordInvoice.setInvoiceCode(fpdm);
        recordInvoice.setInvoiceNo(fphm);
        String selectId = UUID.randomUUID().toString().replace("-", "");
        log.info("selectId={}", selectId);
        recordInvoice.setSelectId(selectId);

        if (je != null) {
            recordInvoice.setInvoiceAmount(new BigDecimal(je));
        }
        if (se != null) {
            recordInvoice.setTaxAmount(new BigDecimal(se));
        }
        if (amountTax != null) {
            recordInvoice.setTotalAmount(new BigDecimal(amountTax));
        }

        recordInvoice.setXfTaxNo(xfsh);
        recordInvoice.setGfTaxNo(gfsbh);
        recordInvoice.setGfName(gfmc);
        recordInvoice.setCreateDate(format1);
        recordInvoice.setSourceSystem("2");
        recordInvoice.setInvoiceStatus("0");
        recordInvoice.setInvoiceType(invoiceType);
        recordInvoice.setCompany(company);
        recordInvoice.setImageId(imageId);
        recordInvoice.setCompCode(compCode);

        if (baseTDxRecordInvoice != null) {
            invoiceReimburseDao.update(recordInvoice, recordWrapper);
        } else {
            invoiceReimburseDao.insert(recordInvoice);
        }

        return "";
    }

    public Integer pushInvoiceToRecordInvoice2(SNInvoice snInvoice, String imageId, String compCode) {
        DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);

        int update = 0;

        String fpdm = snInvoice.getInvoiceCode();
        String fphm = snInvoice.getInvoiceNumber();
        QueryWrapper<BaseTDxRecordInvoice> recordWrapper = new QueryWrapper<>();
        recordWrapper.eq("uuid", fpdm + fphm);
        BaseTDxRecordInvoice recordInvoice = new BaseTDxRecordInvoice();
        recordInvoice.setImageId(imageId);
        recordInvoice.setCompCode(compCode);
        recordInvoice.setGfTaxNo(snInvoice.getPurchaserTaxNo());
        recordInvoice.setGfName(snInvoice.getPurchaserName());

        update = baseTDxRecordInvoiceDao.update(recordInvoice, recordWrapper);

//        if (invoiceInfoList != null && invoiceInfoList.size() > 0) {
//            for (SNInvoice snInvoice : invoiceInfoList) {
//
//            }
//        } else {
//            String imageId = snRequestObject.getImageId();
//            QueryWrapper<BaseTDxRecordInvoice> recordWrapper = new QueryWrapper<>();
//            recordWrapper.eq("image_id", imageId);
//            BaseTDxRecordInvoice recordInvoice = new BaseTDxRecordInvoice();
//            recordInvoice.setImageId("");
//            recordInvoice.setCompCode("");
//
//            update = baseTDxRecordInvoiceDao.update(recordInvoice, recordWrapper);
//        }

        return update;
    }


    public JSONObject checkInvoice(Map<String, String> pramsMap, UserInfo userInfo) {

        // uuid = 发票代码+发票号码
        String uuid = (org.apache.commons.lang.StringUtils.isBlank(pramsMap.get("invoiceCode")) ? "" : pramsMap.get("invoiceCode")) + pramsMap.get("invoiceNo");

        DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);

//        List<String> gfshAll = UserInfoUtil.getGfshAll(userInfo.getOrg());
        String gfsh = "";
//        if (gfshAll.size() > 0) {
//            gfsh = gfshAll.get(0);
//        }

        gfsh = "91370000166120002R";


        JSONObject queryInvoiceResult = invoiceQueryUtil.queryInvoice(pramsMap.get("invoiceCode"),
                pramsMap.get("invoiceNumber"), pramsMap.get("billingDate"), pramsMap.get("totalAmount"), pramsMap.get("checkCode"),
                gfsh, pramsMap.get("invoiceType"));
        String resultCode = queryInvoiceResult.getString("resultCode");

        DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
        // 调用查验接口失败，将签收状态更新到扫描表中或者insert数据到扫描表，然后return；
        if (queryInvoiceResult.containsKey("returnCode") && !"0001".equals(resultCode)) {
            log.error("发票号码：" + pramsMap.get("invoiceNo") + "查验失败，失败原因:" + queryInvoiceResult.getString("returnMessage"));
            return queryInvoiceResult;
        }


        return queryInvoiceResult;
    }

    /**
     * 发票查验API
     * @param pramsMap
     * @param isInteger
     * @return
     * @throws Exception
     */
    public JSONObject singleCheckInvoice(Map<String, String> pramsMap, String isInteger) throws Exception {

        //1.封装查验参数
        ApiRequest apiRequest = new ApiRequest();
        apiRequest.setEntCode(entCode);

        InvoiceUtil iu = new InvoiceUtil(pramsMap.get("invoiceCode"));
        String fplxdm = iu.getFplxdm();

        String snIinvoiceType = pramsMap.get("invoiceType");

        ApiCheckInvoiceSingleRequest request = new ApiCheckInvoiceSingleRequest();
        request.setFphm(pramsMap.get("invoiceNumber"));
        request.setFpdm(pramsMap.get("invoiceCode"));
        request.setFpje(pramsMap.get("totalAmount"));
        request.setKprq(pramsMap.get("billingDate"));
        request.setJym(pramsMap.get("checkCode"));
        if ("21".equals(snIinvoiceType)) {
            request.setFpzl(snIinvoiceType);
        } else {
            request.setFpzl(fplxdm);
        }

        String check = JSONObject.toJSONString(request);

        //2.获取token
        TokenResponse token = apiUtils.getToken(appKey, appSecret);
        String access_token = token.getAccess_token();

        //3.调用开放平台查验接口
        ApiResponse apiResponse = apiUtils.callApi(invoiceCheckSingleUrl, entCode, request, access_token, apiRequest.getDataExchangeId());

        //4.封装返回参数
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNoneBlank(apiResponse.getContent())) {
            log.info("查验的结果为:{}", apiResponse.getContent());
            jsonObject = convertToSnObject(apiResponse.getContent(), jsonObject, fplxdm, isInteger);
        }
//        saveCheckRecord(pramsMap, apiResponse);

        return jsonObject;
    }

    @Async
    public void saveCheckRecord(Map<String, String> pramsMap, ApiResponse apiResponse) {
        //查验结果入库
        TdxPlatformCheckLog checkLog = new TdxPlatformCheckLog();
        checkLog.setCreateDate(new Date());
        checkLog.setInvoiceNo(pramsMap.get("invoiceNo"));
        checkLog.setInvoiceCode(pramsMap.get("invoiceCode"));
        checkLog.setCheckType("2");
        String params = JSONObject.toJSONString(pramsMap);
        String paramsEncode = Base64.encode(params.getBytes());
        checkLog.setRequesPrams(paramsEncode);
        String returnResult = JSONObject.toJSONString(apiResponse);
        String returnResultEncode = Base64.encode(returnResult.getBytes());
        checkLog.setReturnResult(returnResultEncode);
        log.info("封装的查验日志实体为{}", checkLog);
        platformCheckLogService.save(checkLog);
    }

    private JSONObject convertToSnObject(String content, JSONObject jsonObject, String invoiceType, String isInteger) throws ParseException {

        String con = new String(Base64.decode(content));
        HashMap contentMap = JSONObject.parseObject(con, HashMap.class);

        if ("0000".equals(contentMap.get("code"))) {
            HashMap<String, Object> invoiceData = JSONObject.parseObject(contentMap.get("data").toString(), HashMap.class);
            if ("0001".equals(invoiceData.get("cyjg"))) {
                invoiceType = invoiceData.get("fpzl").toString();
                if ("22".equals(invoiceType)) {
                    invoiceType = "32";
                }
                if ("21".equals(invoiceType)) {
                    invoiceType = "31";
                }

                jsonObject.put("invoiceType", invoiceType);
                jsonObject.put("administrativeDivisionNo", "");
                jsonObject.put("administrativeDivisionName", "");

                jsonObject.put("invoiceCode", invoiceData.get("fpdm"));
                jsonObject.put("invoiceNumber", invoiceData.get("fphm"));

                String kprq = invoiceData.get("kprq").toString();
                Date formatDat = new SimpleDateFormat("yyyyMMdd").parse(kprq);
                String str = new SimpleDateFormat("yyyy-MM-dd").format(formatDat);
                log.info("开票日期为:{} ", str);

                jsonObject.put("billingDate", str);
                jsonObject.put("purchaserName", invoiceData.get("gmfmc"));
                jsonObject.put("purchaserTaxNo", invoiceData.get("gmfsbh"));
                jsonObject.put("purchaserBank", invoiceData.get("gmfyhzh"));
                jsonObject.put("purchaserAddressPhone", invoiceData.get("gmfdzdh"));
                jsonObject.put("salesName", invoiceData.get("xhfmc"));
                jsonObject.put("salesTaxNo", invoiceData.get("xhfsbh"));
                jsonObject.put("salesAddressPhone", invoiceData.get("xhfdzdh"));
                if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
                    if (invoiceData.get("khyh") != null && invoiceData.get("khzh") != null) {
                        jsonObject.put("salesBank", invoiceData.get("khyh").toString() + invoiceData.get("khzh").toString());
                    }
                } else {
                    jsonObject.put("salesBank", invoiceData.get("xhfyhzh"));
                }
                jsonObject.put("totalAmount", invoiceData.get("fpje"));
                if ("11".equals(invoiceData.get("fpzl"))) {
                    jsonObject.put("totalTax", "0");
                    jsonObject.put("totalAmount", "0");
                } else {
                    jsonObject.put("totalTax", invoiceData.get("fpse"));
                    jsonObject.put("totalAmount", invoiceData.get("fpje"));
                }
                if ("15".equals(invoiceData.get("fpzl"))) {
                    jsonObject.put("amountTax", invoiceData.get("cjhj"));
                } else {
                    jsonObject.put("amountTax", invoiceData.get("jshj"));
                }


                jsonObject.put("amountTaxCN", "");


                jsonObject.put("checkCode", invoiceData.get("jym"));
                if ("N".equals(invoiceData.get("zfbz"))) {
                    jsonObject.put("state", "0");
                } else if ("H".equals(invoiceData.get("zfbz"))) {
                    jsonObject.put("state", "2");
                } else if ("Y".equals(invoiceData.get("zfbz"))) {
                    jsonObject.put("state", "1");
                }

                jsonObject.put("carrierName", invoiceData.get("cyrmc"));
                jsonObject.put("carrierTaxNo", invoiceData.get("cyrsbh"));
                jsonObject.put("draweeName", invoiceData.get("spfmc"));
                jsonObject.put("draweeTaxNo", invoiceData.get("spfsbh"));
                jsonObject.put("cargoInformation", invoiceData.get("ysgwxx"));
                jsonObject.put("transportRoute", invoiceData.get("qydjyddd"));
                jsonObject.put("machineCode", invoiceData.get("skph"));
                jsonObject.put("tonnage", invoiceData.get("ccdw"));
                jsonObject.put("taxAuthorityNo", invoiceData.get("zgswjgdm"));
                jsonObject.put("taxAuthorityName", invoiceData.get("zgswjgmc"));
                if ("03".equals(invoiceData.get("fpzl"))) {
                    jsonObject.put("administrativeDivisionNo", invoiceData.get("zgswjgdm"));
                    jsonObject.put("administrativeDivisionName", invoiceData.get("zgswjgmc"));
                }
                jsonObject.put("remarks", invoiceData.get("bz"));
                jsonObject.put("vehicleType", invoiceData.get("cllx"));
                jsonObject.put("brandModel", invoiceData.get("cpxh"));
                jsonObject.put("originPlace", invoiceData.get("cd"));
                jsonObject.put("certificateNo", invoiceData.get("hgzs"));
                jsonObject.put("inspectionListNo", invoiceData.get("sjdh"));
                jsonObject.put("engineNo", invoiceData.get("fdjhm"));
                jsonObject.put("vehicleNo", invoiceData.get("clsbh"));
                jsonObject.put("importCertificateNo", invoiceData.get("jszmsh"));
                jsonObject.put("paymentVoucherNo", invoiceData.get("wspzhm"));
                jsonObject.put("passengersLimited", invoiceData.get("xcrs"));
                if (invoiceData.get("txfbz") != null && "Y".equals(invoiceData.get("txfbz"))) {
                    jsonObject.put("tollSign", "06");
                } else {
                    jsonObject.put("tollSign", "07");
                }

                jsonObject.put("zeroTaxRateSign", invoiceData.get("lslbs"));
                log.info("零税率标识为:{}", invoiceData.get("lslbs"));
                jsonObject.put("source", "");
                jsonObject.put("idcardNo", invoiceData.get("sfzh"));

                if ("15".equals(invoiceData.get("fpzl"))) {
                    jsonObject.put("buyerIDNum", invoiceData.get("mfdwdmsfzh"));
                } else {
                    jsonObject.put("buyerIDNum", invoiceData.get("sfzh"));
                }

                jsonObject.put("vehicleType", invoiceData.get("cllx"));
                jsonObject.put("factoryModel", invoiceData.get("cpxh"));
                jsonObject.put("productPlace", invoiceData.get("cd"));
                jsonObject.put("certificate", invoiceData.get("hgzs"));
                jsonObject.put("certificateImport", invoiceData.get("jszmsh"));
                jsonObject.put("inspectionNum", invoiceData.get("sjdh"));
                jsonObject.put("engineNo", invoiceData.get("fdjhm"));
                jsonObject.put("vehicleNo", invoiceData.get("clsbh"));
                jsonObject.put("engineNo", invoiceData.get("fdjhm"));
                jsonObject.put("taxBureauCode", invoiceData.get("zgswjgdm"));
                jsonObject.put("taxBureauName", invoiceData.get("zgswjgmc"));
                jsonObject.put("taxBureauCode", invoiceData.get("zgswjgdm"));
                jsonObject.put("taxRecords", invoiceData.get("wspzhm"));
                jsonObject.put("tonnage", invoiceData.get("dw"));
                jsonObject.put("limitPeople", invoiceData.get("xcrs"));
                String taxRate = "";
                if (StringUtils.isBlank(invoiceData.get("sl").toString()) || "免税".equals(invoiceData.get("sl").toString()) || "不征税".equals(invoiceData.get("sl").toString()) || "***".equals(invoiceData.get("sl").toString())) {
                    taxRate = "0";
                    jsonObject.put("taxRate", taxRate);
                } else {
                    if (StringUtils.isNoneBlank(invoiceData.get("sl").toString())) {
                        taxRate = invoiceData.get("sl").toString();
                        if (taxRate.contains("%")) {
                            taxRate = taxRate.replace("%","");
                        }
                        //按照小数处理
                        if(StringUtils.isNotBlank(isInteger)){
                            BigDecimal bigDecimal = new BigDecimal(taxRate);
                            taxRate = bigDecimal.divide(new BigDecimal("100")).toPlainString();
                        }

                        if ("11".equals(invoiceType)) {
                            taxRate = "0";
                        }
                        log.info("明细-发票税率为:{}", taxRate);
                        jsonObject.put("taxRate", taxRate);
                    }
                }
                taxRate = "";
                jsonObject.put("limitPeople", invoiceData.get("xcrs"));
                jsonObject.put("machineNo", invoiceData.get("jqbh"));

                jsonObject.put("licensePlate", invoiceData.get("cpzh"));
                jsonObject.put("registrationNo", invoiceData.get("djzh"));
                jsonObject.put("vehicleIdentificationNo", invoiceData.get("clsbh"));
                jsonObject.put("vehicleAdminOffice", invoiceData.get("zrdcgsmc"));
                jsonObject.put("buyerUnitOrIndividual", invoiceData.get("mfdwgr"));
                jsonObject.put("buyerUnitOrIndividualAddress", invoiceData.get("mfdwgrdz"));
                jsonObject.put("buyerPhone", invoiceData.get("mfdh"));
                jsonObject.put("sellerUnitOrIndividual", invoiceData.get("smfdwgr"));
                jsonObject.put("sellerUnitCodeOrIdNo", invoiceData.get("smfdwdmsfzh"));
                jsonObject.put("sellerUnitOrIndividualAddress", invoiceData.get("smfdwgrzz"));
                jsonObject.put("sellerPhone", invoiceData.get("smfdh"));
                jsonObject.put("businessUnit", invoiceData.get("jypmdw"));
                jsonObject.put("businessUnitAddress", invoiceData.get("jypmdwdz"));
                jsonObject.put("businessUnitTaxNo", invoiceData.get("jypmdwzsbh"));
                jsonObject.put("businessUnitBankAndAccount", invoiceData.get("khyhjzh"));
                jsonObject.put("businessUnitPhone", invoiceData.get("jypmdwdh"));
                jsonObject.put("lemonMarket", invoiceData.get("escsc"));
                jsonObject.put("lemonMarketTaxNo", invoiceData.get("escscsbh"));
                jsonObject.put("lemonMarketAddress", invoiceData.get("escscdz"));
                jsonObject.put("lemonMarketBankAndAccount", invoiceData.get("escsckhyhzh"));
                jsonObject.put("lemonMarketPhone", invoiceData.get("escscdh"));

                List<Map<String, String>> returnDetailList = new ArrayList<>();
                JSONArray detailList = (JSONArray) invoiceData.get("detailList");

                for (int i = 0; i < detailList.size(); i++) {
                    String taxRateDetail = "";
                    JSONObject detail = (JSONObject) detailList.get(i);
                    Map<String, String> snDetailMap = new HashMap<String, String>();
                    snDetailMap.put("rowNo", i + 1 + "");
                    snDetailMap.put("commodityCode", detail.getString("ssflbm"));
                    snDetailMap.put("commodityName", detail.getString("hwmc"));
                    snDetailMap.put("specificationModel", detail.getString("ggxh"));
                    snDetailMap.put("unit", detail.getString("jldw"));
                    snDetailMap.put("detailNo", detail.getString("mxbh"));
                    String quantity = detail.getString("spsl");
//                        if (quantity.length() > 3) {
//                            int index = quantity.indexOf(".");
//                            quantity = quantity.substring(0, index + 2);
//                        }
                    snDetailMap.put("quantity", quantity);

                    String unitPrice = detail.getString("bhsdj");
//                        if (unitPrice.length() > 3) {
//                            int index = unitPrice.indexOf(".");
//                            unitPrice = unitPrice.substring(0, index + 3);
//                        }

                    snDetailMap.put("unitPrice", unitPrice);


                    if ("11".equals(invoiceType)) {
                        snDetailMap.put("tax", "0");

                        //如果是卷票计算合计金额
                        String hjje = null;
                        if (detail.getString("je") != null && detail.getString("se") != null) {
                            BigDecimal je = new BigDecimal(detail.getString("je"));
                            if (detail.getString("se") != null) {
                                hjje = je.add(new BigDecimal(detail.getString("se"))).toPlainString();
                            } else {
                                hjje = je.toPlainString();
                            }
                        }

                        if (StringUtils.isNotBlank(hjje))
                            snDetailMap.put("amount", hjje);
                    } else {
                        snDetailMap.put("tax", "***".equals(detail.getString("se")) ? "0.00" : detail.getString("se"));
                        snDetailMap.put("amount", detail.getString("je"));
                    }


                    if (StringUtils.isBlank(detail.get("sl").toString())) {
                        taxRateDetail = "0";
                        snDetailMap.put("taxRate", taxRateDetail);
                    } else {
                        if (StringUtils.isNoneBlank(detail.get("sl").toString())) {
                            taxRate = detail.get("sl").toString();
                            taxRate = taxRate.replace("%", "");
//                            if (!"0".equals(taxRate)) {
//                                taxRate = taxRate.substring(0, taxRate.length() - 1);
//                            }
                            //按照小数处理
                            if(StringUtils.isNotBlank(isInteger)){
                                if ("*".equals(taxRate) || "**".equals(taxRate) || "***".equals(taxRate) || "不征税".equals(taxRate) || "免税".equals(taxRate)) {
                                } else {
                                        BigDecimal bigDecimal = new BigDecimal(taxRate);
                                        taxRate = bigDecimal.divide(new BigDecimal("100")).toPlainString();
                                    }
                                }
                            if ("11".equals(invoiceType)) {
                                taxRate = "0";
                            }
                            log.info("明细-发票税率为:{}", taxRate);
                            snDetailMap.put("taxRate", taxRate);
                        }
                    }

                    log.info("明细-tax={}", detail.get("se"));
                    log.info("明细-commodityCode={}", detail.get("ssflbm"));
                    snDetailMap.put("currentDateEnd", detail.getString("txrqz"));
                    snDetailMap.put("currentDateStart", detail.getString("txrqq"));
                    snDetailMap.put("licensePlateNum", detail.getString("cph"));
                    snDetailMap.put("type", detail.getString("lx"));

                    returnDetailList.add(snDetailMap);
                }

                jsonObject.put("invoiceLineList", returnDetailList);

            } else {
                jsonObject.put("cyjg", invoiceData.get("cyjg"));
                jsonObject.put("cyjgxx", invoiceData.get("cyjgxx"));
            }

        } else {
            jsonObject.put("code", contentMap.get("code"));
            jsonObject.put("message", contentMap.get("message"));
        }

        return jsonObject;
    }

    public String updateInvoicePoll(String company, String taxNo, TDxInvoiceReimburse reimburse, SNInvoice invoice, String fplxdm, String imageId, String compCode) throws Exception {
        String result = "0000";

        //判断发票类型
        fplxdm = getFplx(invoice, fplxdm);

        //如果是可价税分离的票种,直接入报销库
        if (SNFplxEnum.HCP.getFplxDm().equals(fplxdm) || SNFplxEnum.KYQCP.getFplxDm().equals(fplxdm)
                || SNFplxEnum.JPXCD.getFplxDm().equals(fplxdm) || SNFplxEnum.CP.getFplxDm().equals(fplxdm)
                || SNFplxEnum.KYQCP.getFplxDm().equals(fplxdm)) {

            InvoiceInfo invoiceInfo = convertToInvoiceInfo(invoice);
            log.info("进行价税分离的发票信息为:{}", invoiceInfo);
            ServiceResult<InvoiceInfo> invoiceResult = new ServiceResult<>();

            boolean flag = false;
            //0523晚成伟提出新需求，客运汽车票必须实名才可以进行价税分离
            if (SNFplxEnum.KYQCP.getFplxDm().equals(fplxdm)) {
                if (StringUtils.isEmpty(invoice.getRiderName()) || StringUtils.isEmpty(invoice.getIdcardNo())) {
                    log.info("非实名的实名客票 不需要做价税分离");
                    flag = true;
                    invoiceResult.setMsg("ok");
                    invoiceResult.setResult(true);
                }
            }

            if(!flag) {
                invoiceResult = this.valoremTaxCount(invoiceInfo, "Y");
                InvoiceInfo data = invoiceResult.getData();
                if (data != null) {
                    invoice.setIsDeductible(data.getIsDeductible());
                    invoice.setTaxRate(data.getTaxRate());
                    if (data.getInvoiceAmount() != null) {
                        invoice.setTotalAmount(data.getInvoiceAmount().toString());
                    }
                    if (data.getTaxAmount() != null) {
                        invoice.setTotalTax(data.getTaxAmount().toString());
                    }
                }
            }


            if (!"ok".equals(invoiceResult.getMsg()) && !"0000".equals(invoiceResult.getMsg())) {
                log.info("价税分离失败:{}", invoiceResult.getMsg());
                return invoiceResult.getMsg();
            }
//            DynamicContextHolder.push(DbConstant.BASICS_READ);
//
//            SysDeptEntity orgByCompCode = sysDeptDao.getOrgByCompCode(compCode);
//            log.info("查询的组织信息为:{}",JSONObject.toJSONString(orgByCompCode));
//            if(orgByCompCode != null) {
//                reimburse.setGfTaxNo(orgByCompCode.getTaxno());
//                reimburse.setGfName(orgByCompCode.getTaxname());
//                reimburse.setGfAddressAndPhone(orgByCompCode.getAddress() + orgByCompCode.getPhone());
//                reimburse.setGfBankAndNo(orgByCompCode.getBank() + orgByCompCode.getAccount());
//            }

            reimburse = convertToReimburse(invoice, reimburse, fplxdm, company);

            log.info("插库的发票信息:{}", reimburse);

            DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
            int insert = 0;
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("uuid", reimburse.getUuid());
            TDxInvoiceReimburse reimburse1 = tDxInvoiceReimburseService.getBaseMapper().selectOne(wrapper);
            if (reimburse1 != null) {
//                insert = tDxInvoiceReimburseService.getBaseMapper().updateById(reimburse);
                insert = tDxInvoiceReimburseService.getBaseMapper().update(reimburse, wrapper);
            } else {
                insert = tDxInvoiceReimburseService.getBaseMapper().insert(reimburse);
            }
            if (insert > 0) {
                log.info("实名客票插入报销库成功");
            }
        } else {
            //如果是可查验类型，直接更新数据库
            if ("01".equals(fplxdm) || "02".equals(fplxdm) || "03".equals(fplxdm) || "04".equals(fplxdm)
                    || "08".equals(fplxdm) || "10".equals(fplxdm) || "11".equals(fplxdm) || "14".equals(fplxdm)
                    || "15".equals(fplxdm) || "31".equals(fplxdm) || "32".equals(fplxdm)) {
                DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
                String fpdm = invoice.getInvoiceCode();
                String fphm = invoice.getInvoiceNumber();

                QueryWrapper<BaseTDxRecordInvoice> recordWrapper = new QueryWrapper<>();
                if (StringUtils.isEmpty(fpdm)) {
                    recordWrapper.eq("uuid", fphm);
                } else {
                    recordWrapper.eq("uuid", fpdm + fphm);
                }

                BaseTDxRecordInvoice update = baseTDxRecordInvoiceDao.selectOne(recordWrapper);
                Map<String, String> pramsMap = new HashMap<>();
                JSONObject checkInvoiceResult = null;

                //如果提交的发票信息在底账库不存在，则重新补充查验，插入数据库中.
                if (update == null) {
                    try {
                        //传入的参数为:{billingDate=2023-04-24, totalAmount=9708.74, purchaserTaxNo=91370000MA3RD38A9Q, invoiceNumber=02014197, invoiceType=10100,
                        // invoiceCode=3700222130, checkCode=}
                        pramsMap.put("invoiceCode", fpdm);
                        pramsMap.put("invoiceNumber", fphm);
                        if (StringUtils.isNotEmpty(invoice.getBillingDate())) {
                            String billingDate = invoice.getBillingDate().replaceAll("-", "");
                            pramsMap.put("billingDate", billingDate);
                        }
                        if("31".equals(invoice.getInvoiceType()) || "32".equals(invoice.getInvoiceType())){
                            pramsMap.put("totalAmount", invoice.getAmountTax());
                        }else{
                            pramsMap.put("totalAmount", invoice.getTotalAmount());
                        }

                        pramsMap.put("purchaserTaxNo", invoice.getPurchaserTaxNo());
                        if("31".equals(invoice.getInvoiceType()) || "32".equals(invoice.getInvoiceType())){
                            pramsMap.put("invoiceType", "21");
                        }else {
                            pramsMap.put("invoiceType", invoice.getInvoiceType());
                        }

                        checkInvoiceResult = snPushCheckRecordService.singleCheckInvoice(pramsMap,null);
                        log.info("补充查验结果为:{}", checkInvoiceResult);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("补充查验失败，errormsg:{}", e.getMessage());
                    }

                    if (checkInvoiceResult != null && !checkInvoiceResult.containsKey("code")) {
                        if (!checkInvoiceResult.containsKey("cyjg")) {
                            checkInvoiceResult.put("invoiceNo", checkInvoiceResult.getString("invoiceNumber"));
                            log.info("补充查验的结果为:{}", checkInvoiceResult);
                            signSaveInvoiceInfoService.saveQueryInvoiceResult(checkInvoiceResult, "", "1", "business");
                        }
                    }
                }
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);

                //可查验发票,已入库,更新票池
                Integer integer = this.pushInvoiceToRecordInvoice2(invoice, imageId, compCode);
                log.info("可查验发票，更新底账库完成");
            } else {
                //不可查验发票,未入库,插入票池
                this.pushInvoiceToRecordInvoice(invoice, taxNo, company, imageId, compCode);
                log.info("不可查验发票，插入底账库成功");
            }

        }
        return result;
    }

    private TDxInvoiceReimburse convertToReimburse(SNInvoice invoice, TDxInvoiceReimburse reimburse, String fplxdm, String company) {
        reimburse.setId(IdUtils.nextId());
        reimburse.setInvoiceType(fplxdm);
        reimburse.setInvoiceCode(invoice.getInvoiceCode());
        reimburse.setInvoiceNo(invoice.getInvoiceNumber());
        reimburse.setInvoiceDate(invoice.getBillingDate());
        reimburse.setPassenger(invoice.getRiderName());
        if (invoice.getTotalAmount() != null) {
            reimburse.setInvoiceAmount(new BigDecimal(invoice.getTotalAmount()));
        }

        if (invoice.getAmountTax() != null) {
            reimburse.setTotalAmount(new BigDecimal(invoice.getAmountTax()));
        }

        if (invoice.getTotalTax() != null) {
            reimburse.setTaxAmount(new BigDecimal(invoice.getTotalTax()));
        }

        reimburse.setInvoiceStatus(invoice.getState());
        reimburse.setDepartureCity(invoice.getStationGetOn());
        reimburse.setReachingCity(invoice.getStationGetOff());
        reimburse.setTrainNumber(invoice.getTrainNumber());
        reimburse.setPassengerSFZH(invoice.getIdcardNo());
        reimburse.setXfName(invoice.getSalesName());
        reimburse.setXfTaxNo(invoice.getSalesTaxNo());
        reimburse.setXfAddressAndPhone(invoice.getSalesAddressPhone());
        reimburse.setXfBankAndNo(invoice.getSalesBank());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        log.info("uuid={}", uuid);
        reimburse.setSelectId(uuid);

        if (StringHelper.isNotBlank(invoice.getTaxRate())) {
            reimburse.setTaxRate(invoice.getTaxRate());
            reimburse.setTaxCode(getTaxCode(invoice.getTaxRate()));
        } else {
            reimburse.setTaxRate("0%");
            reimburse.setTaxCode(getTaxCode(reimburse.getTaxRate()));
        }

        reimburse.setIsDeduction(invoice.getIsDeductible());

        if (StringUtils.isNoneBlank(reimburse.getInvoiceCode())) {
            reimburse.setUuid(reimburse.getInvoiceCode() + reimburse.getInvoiceNo());
        } else {
            reimburse.setUuid(reimburse.getInvoiceNo());
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);

        reimburse.setCreateDate(format);
        reimburse.setUpdateDate(date);
        reimburse.setCheckCode(invoice.getCheckCode());

        reimburse.setFare(invoice.getNoTaxAmount());
        reimburse.setFuelSurcharge(invoice.getFuelSurcharge());
        reimburse.setCompany(company);
//        reimburse.setPostingTime(format);
        reimburse.setAccountPeriod("");

        return reimburse;
    }

    private String getTaxCode(String taxRate) {

        String sm = "J0";

        switch (taxRate) {
            // 发票采集
            case "0%":
                sm = "J0";
                break;
            case "0.00":
                sm = "J0";
                break;
            case "0.000":
                sm = "J0";
                break;
            case "免税":
                sm = "J0";
                break;
            case "16%":
                sm = "J1";
                break;
            case "13%":
                sm = "J2";
                break;
            case "10%":
                sm = "J3";
                break;
            case "9%":
                sm = "J4";
                break;
            case "6%":
                sm = "J5";
                break;
            case "5%":
                sm = "J6";
                break;
            case "3%":
                sm = "J7";
                break;
            case "2%":
                sm = "J8";
                break;
            case "1%":
                sm = "J9";
                break;
            case "17%":
                sm = "JC";
                break;
            default:
                sm = "J0";
                break;

        }
        return sm;

    }

    private InvoiceInfo convertToInvoiceInfo(SNInvoice snInvoice) {
        InvoiceInfo invoice = new InvoiceInfo();
        invoice.setInvoiceTypeCode(snInvoice.getInvoiceType());

        if (snInvoice.getBillingDate() != null) {
            Date date = new Date();
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = ft.parse(snInvoice.getBillingDate());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            invoice.setInvoiceDate(date);
        } else {
            log.error("开票日期为空");
        }

        invoice.setIdentityNumber(snInvoice.getIdcardNo());
        invoice.setPassenger(snInvoice.getRiderName());
        invoice.setDepartCity(snInvoice.getStationGetOn());
        invoice.setArriveCity(snInvoice.getStationGetOff());
        if ("92".equals(invoice.getInvoiceTypeCode()) || "89".equals(invoice.getInvoiceTypeCode()) || "88".equals(invoice.getInvoiceTypeCode())) {
            if (snInvoice.getAmountTax() != null)
                invoice.setInvoiceAmount(new BigDecimal(snInvoice.getAmountTax()));
        }
        if ("90".equals(invoice.getInvoiceTypeCode())) {
            invoice.setFare(snInvoice.getNoTaxAmount());
            invoice.setFuelSurcharge(snInvoice.getFuelSurcharge());
        }
        if (snInvoice.getNoTaxAmount() != null) {
            BigDecimal amount = new BigDecimal(snInvoice.getNoTaxAmount());
            invoice.setInvoiceAmount(amount);
        }

        return invoice;
    }

    private String getFplx(SNInvoice invoice, String fplxdm) {
        String snFplx = invoice.getInvoiceType();
        //可查验发票
        if (SNFplxEnum.ZP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "01";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.HWYSZP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "02";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.JDC.getSnFplxDm().equals(snFplx)) {
            fplxdm = "03";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.PP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "04";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.DZP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "10";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.JSP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "11";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.TXF.getSnFplxDm().equals(snFplx)) {
            fplxdm = "14";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.ESC.getSnFplxDm().equals(snFplx)) {
            fplxdm = "15";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.DZZP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "08";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.QDZP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "31";
            invoice.setInvoiceType(fplxdm);
        }

        if (SNFplxEnum.QDPP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "32";
            invoice.setInvoiceType(fplxdm);
        }

        //不可查验发票
        if (SNFplxEnum.HCP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "92";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.KYQCP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "94";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.JPXCD.getSnFplxDm().equals(snFplx)) {
            fplxdm = "90";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.DEFP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "95";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.JDFP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "97";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.CZCFP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "91";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.KYQCP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "89";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.GLF.getSnFplxDm().equals(snFplx)) {
            fplxdm = "101";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.CP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "88";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.GJXP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "99";
            invoice.setInvoiceType(fplxdm);
        }
        if (SNFplxEnum.QTFP.getSnFplxDm().equals(snFplx)) {
            fplxdm = "00";
            invoice.setInvoiceType(fplxdm);
        }
        return fplxdm;
    }


    /**
     * 客票价税计算
     *
     * @return
     * @throws ParseException
     */
    public ServiceResult<InvoiceInfo> valoremTaxCount(InvoiceInfo invoiceInfo, String isDeductible) {
        if (isDeductible == null || StringUtils.isEmpty(isDeductible)) {
            logger.error("客票价税计算失败：费用类别或可抵扣标识为空");
            return fail("费用类别或可抵扣标识为空");
        }
        if (invoiceInfo == null) {
            logger.error("客票价税计算失败：请求参数为空");
            return fail("请求参数为空");
        } else if (StringUtils.isBlank(isDeductible) || !CommonEnum.Y.equals(isDeductible)) {
            return fail("客票不抵扣");
            // 判断发票类型是否为客票
        } else if (!getPassengerInvoiceTypeList().contains(invoiceInfo.getInvoiceTypeCode())) {
            logger.error("客票价税计算失败：发票类型不为客票");
            return fail("发票类型不为客票");
        }

        // 校验客票可抵扣条件
//        ServiceResult<?> result = checkIsDeduction(invoiceInfo);
//        if (!result.getResult()) {
//            logger.error("客票价税计算失败：" + result.getMsg());
//            return fail(result.getMsg());
//        }
        // 设置可抵扣标识
        invoiceInfo.setIsDeductible(isDeductible);
        // 设置税率
        // 航空、铁路运输发票税率显示9%
        if (invoiceInfo.getInvoiceTypeCode().equals(Constant.AIR_PASSENGER_ELECTRONIC_TICKET_ITINERARY_CODE)
                || invoiceInfo.getInvoiceTypeCode().equals(Constant.RAILWAY_TICKET_CODE)) {
            invoiceInfo.setTaxRate("9%");
            // 公路、水路及其他显示3% 增值税电子普通发票显示税率字段
        } else if (!invoiceInfo.getInvoiceTypeCode().equals(Constant.VALUE_ADDED_TAX_INVOICE_ELECTRONIC_CODE)
                && !invoiceInfo.getInvoiceTypeCode().equals(Constant.VALUE_ADDED_TAX_INVOICE_ELECTRONIC_PASSENGER_CODE)) {
            invoiceInfo.setTaxRate("3%");
        }

        // 计算税额
        // 航空客票：税额=（票价+燃油附加费）÷（1+9%）×9%
        if (invoiceInfo.getInvoiceTypeCode().equals(Constant.AIR_PASSENGER_ELECTRONIC_TICKET_ITINERARY_CODE)) {
            if (StringUtils.isNotEmpty(invoiceInfo.getFare()) && isBigDecimal(invoiceInfo.getFare())
                    && StringUtils.isNotEmpty(invoiceInfo.getFuelSurcharge())
                    && isBigDecimal(invoiceInfo.getFuelSurcharge())) {
                // 票价
                BigDecimal fare = new BigDecimal(invoiceInfo.getFare());
                // 燃油附加费
                BigDecimal fuelSurcharge = new BigDecimal(invoiceInfo.getFuelSurcharge());
                invoiceInfo.setInvoiceAmount(fare.add(fuelSurcharge));
                invoiceInfo.setTaxAmount((fare.add(fuelSurcharge).divide(new BigDecimal("1.09"), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("0.09"))));
            } else {
                logger.error("客票价税计算失败：航空客票 票价或燃油附加费为空");
            }
            // 铁路客票：税额=票面金额÷（1+9%）×9%
        } else if (invoiceInfo.getInvoiceTypeCode().equals(Constant.RAILWAY_TICKET_CODE)) {
            if (invoiceInfo.getInvoiceAmount() != null)
                invoiceInfo.setTaxAmount(invoiceInfo.getInvoiceAmount()
                        .divide(new BigDecimal("1.09"), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("0.09")));
            // 公路、水路、其他客票：税额=票面金额÷（1+3%）×3%
        } else if (!invoiceInfo.getInvoiceTypeCode().equals(Constant.VALUE_ADDED_TAX_INVOICE_ELECTRONIC_CODE)
                && !invoiceInfo.getInvoiceTypeCode().equals(Constant.VALUE_ADDED_TAX_INVOICE_ELECTRONIC_PASSENGER_CODE)) {
            if (invoiceInfo.getInvoiceAmount() != null)
                invoiceInfo.setTaxAmount(invoiceInfo.getInvoiceAmount()
                        .divide(new BigDecimal("1.03"), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("0.03")));
        }
        // 税额保留两位小数(四舍五入)
        if (invoiceInfo.getInvoiceAmount() != null) {
            invoiceInfo.setTaxAmount(invoiceInfo.getTaxAmount().setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        if (!invoiceInfo.getInvoiceTypeCode().equals(Constant.AIR_PASSENGER_ELECTRONIC_TICKET_ITINERARY_CODE)) {
            // 不含税金额
            if (invoiceInfo.getInvoiceAmount() != null && invoiceInfo.getTaxAmount() != null) {
                invoiceInfo.setInvoiceAmount(invoiceInfo.getInvoiceAmount().subtract(invoiceInfo.getTaxAmount()));
            }
        } else {
            if (StringUtils.isNotEmpty(invoiceInfo.getFare()) && isBigDecimal(invoiceInfo.getFare())
                    && StringUtils.isNotEmpty(invoiceInfo.getFuelSurcharge())
                    && isBigDecimal(invoiceInfo.getFuelSurcharge())) {
                // 票价
                BigDecimal fare = new BigDecimal(invoiceInfo.getFare());
                // 燃油附加费
                BigDecimal fuelSurcharge = new BigDecimal(invoiceInfo.getFuelSurcharge());
                invoiceInfo.setInvoiceAmount(fare.add(fuelSurcharge).subtract(invoiceInfo.getTaxAmount()));
            } else {
                logger.error("客票不含税金额失败：航空客票 票价或燃油附加费为空");
            }
        }
        return ok(invoiceInfo);
    }

    public static List<String> getPassengerInvoiceTypeList() {
        // 客票类型
        List<String> typeList = new ArrayList<>();
        // 增值税电子普通发票
        typeList.add(Constant.VALUE_ADDED_TAX_INVOICE_ELECTRONIC_CODE);
        // 增值税电子普通发票(通行费)
        typeList.add(Constant.VALUE_ADDED_TAX_INVOICE_ELECTRONIC_PASSENGER_CODE);
        // 航空客运电子客票行程单
        typeList.add(Constant.AIR_PASSENGER_ELECTRONIC_TICKET_ITINERARY_CODE);
        // 公路运输客票(实名）
        typeList.add(Constant.ROAD_TRANSPORT_TICKET_REAL_NAME_CODE);
        // 水路运输客票(实名)
        typeList.add(Constant.WATER_TRANSPORT_TICKET_REAL_NAME_CODE);
        // 其他运输客票(实名)
        typeList.add(Constant.OTHER_TRANSPORT_TICKET_REAL_NAME_CODE);
        // 火车票
        typeList.add(Constant.RAILWAY_TICKET_CODE);
        return typeList;
    }

    public static boolean isBigDecimal(String str) {
        if (str == null || str.trim().length() == 0) {
            return false;
        }
        char[] chars = str.toCharArray();
        int sz = chars.length;
        int i = (chars[0] == '-') ? 1 : 0;
        if (i == sz) {
            return false;
        }

        // 除了负号，第一位不能为'小数点'
        if (chars[i] == CommonEnum.POINT_CHAR) {
            return false;
        }

        boolean radixPoint = false;
        for (; i < sz; i++) {
            if (chars[i] == '.') {
                if (radixPoint) {
                    return false;
                }
                radixPoint = true;
            } else if (!(chars[i] >= '0' && chars[i] <= '9')) {
                return false;
            }
        }
        return true;
    }

}
