package com.jianshui.api.controller.webservice.income.v1.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
// import com.jianshui.api.controller.webservice.income.v1.InvoiceCheckWebService;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jianshui.api.exception.JianshuiExceptionHandler;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.exception.jianshui.JianshuiServiceException;
import com.jianshui.common.utils.DateUtils;
import com.jianshui.common.utils.StringUtils;
import com.jianshui.common.utils.ToLowerBeanUtil;
import com.jianshui.income.domain.entity.InvoiceCheck;
import com.jianshui.income.domain.entity.InvoiceCheckDetail;
import com.jianshui.income.domain.vo.render.*;
import com.jianshui.income.factory.ICheckServiceFactory;
import com.jianshui.income.service.ICheckInvoice;
import com.jianshui.income.service.impl.EleCheckInvoiceImpl;
import com.jianshui.platform.enums.InvoiceType;
import com.jianshui.system.domain.CompanyserviceProp;
import com.jianshui.system.service.ICompanyservicePropService;
import com.jianshui.system.service.ICompanyserviceService;
import com.jianshui.system.service.IServiceManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.JAXBElement;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jianshui.income.constant.WebServiceConstant.NAMESPACE;

@Component
@Slf4j
@WebService(targetNamespace = NAMESPACE)
// public class InvoiceCheckWebServiceImpl implements InvoiceCheckWebService {
public class InvoiceCheckWebServiceImpl {

    @Autowired
    private ICheckServiceFactory incomeServiceFactory;

    @Autowired
    private IServiceManageService serviceManageService;

    @Autowired
    private ICompanyserviceService companyserviceService;

    @Autowired
    private ICompanyservicePropService companyservicePropService;


    @WebMethod
    public ResponseCheckVO getInvoice(String order) {
        DocumentBuilder resultBuilder = XmlUtil.createDocumentBuilder();
        Document result = resultBuilder.newDocument();

        log.info("【webservice接到请求】order:{}", order);
        Document xml = XmlUtil.parseXml(order);
        Element element = xml.getDocumentElement();
        // 获得xml虾的InvData
        Element invData = XmlUtil.getElement(element, "InvData");
        Node invDataNode = invData == null ? null : invData.getFirstChild();
        Element TaxCodeElement = XmlUtil.getElement(invData, "TaxCode");
        Node TaxCodeElementNode = TaxCodeElement == null ? null : TaxCodeElement.getFirstChild();
        Element PasswordElement = XmlUtil.getElement(invData, "Password");
        Node PasswordElementNode = PasswordElement == null ? null : PasswordElement.getFirstChild();
        Element InvCodeElement = XmlUtil.getElement(invData, "InvCode");
        Node InvCodeElementNode = InvCodeElement == null ? null : InvCodeElement.getFirstChild();
        Element InvNoElement = XmlUtil.getElement(invData, "InvNo");
        Node InvNoElementNode = InvNoElement == null ? null : InvNoElement.getFirstChild();
        Element InvTimeElement = XmlUtil.getElement(invData, "InvTime");
        Node InvTimeElementNode = InvTimeElement == null ? null : InvTimeElement.getFirstChild();
        Element InvOtherElement = XmlUtil.getElement(invData, "InvOther");
        Node InvOtherElementNode = InvOtherElement == null ? null : InvOtherElement.getFirstChild();

        String InvOther = InvOtherElementNode != null ? InvOtherElementNode.getNodeValue() : "";
        if (StringUtils.isEmpty(InvOther)) {
            return buildResult(result, "1", "不含税金额/校验码不能为空", null);
        }
        String Kpje = InvOtherElementNode != null ? InvOtherElementNode.getNodeValue() : "";
        if (StringUtils.isEmpty(Kpje)) {
            Kpje = InvOther;
//            return buildResult(result, "1", "开票金额不能为空", null);
        }
        // 获得value
        String TaxCode = TaxCodeElementNode != null ? TaxCodeElementNode.getNodeValue() : "";
        if (StringUtils.isEmpty(TaxCode)) {
            return buildResult(result, "1", "税号不能为空", null);
        }

        // 根据税号获得companyService
        Companyservice companyservice = companyserviceService.selectCompanyserviceByTaxcode(TaxCode);
        if (companyservice == null) {
            return buildResult(result, "1", "税号不存在", null);
        }

        String Password = PasswordElementNode != null ? PasswordElementNode.getNodeValue() : "";
        if (StringUtils.isEmpty(Password)) {
            return buildResult(result, "036", "查验交互密码为空，不能进行查验", null);
        }

        // 全电发票没有发票代码
        String InvCode = InvCodeElementNode != null ? InvCodeElementNode.getNodeValue() : "";
        /*
        if (StringUtils.isEmpty(InvCode)) {
            return buildResult(result, "1", "发票代码不能为空", null);
        }*/
        String InvNo = InvNoElementNode != null ? InvNoElementNode.getNodeValue() : "";
        if (StringUtils.isEmpty(InvNo)) {
            return buildResult(result, "1", "发票号码不能为空", null);
        }
        String InvTime = InvTimeElementNode != null ? InvTimeElementNode.getNodeValue() : "";
        if (StringUtils.isEmpty(InvTime)) {
            return buildResult(result, "1", "开票日期不能为空", null);
        }
        boolean isMatch = ReUtil.isMatch("^\\d{4}-\\d{2}-\\d{2}$", InvTime);
        if (!isMatch) {
            return buildResult(result, "1", "开票日期格式错误 yyyy-MM-dd", null);
        }
        // 如果Jym这个参数为空，我就去判断InvOther是否为6位且不带小数点，如果确实如此，那就直接将InvOther作为校验码传给大象
        // 2023.03.09 如果InvOtherNode是6位且不到小数点，那么就直接将InvOtherNode作为校验码传给大象
        String Jym = InvOtherElementNode != null ? InvOtherElementNode.getNodeValue() : "";
        if (StringUtils.isNotEmpty(Jym)) {
            // 判断InvOther是否为6位且不带小数点
            if (!(Jym.length() == 6 && !Jym.contains("."))) {
                Jym = "";
            }

            // return buildResult(result, "1", "校验码不能为空", null);
        }

        // String Fpzl = TaxCodeElementNode != null ? TaxCodeElementNode.getNodeValue() : "";
        String Fpzl = "";
        // 如果发票号码位数为20位，则fpzl为21,否则为01，中举在2022-12-06 20:08给巩权林说的解决方案，是大象那边提的，可以用来适配远得
        if (InvNo.length() == 20) {
            Fpzl = "21";
        } else {
            Fpzl = "01";
        }

        CompanyserviceProp keyProp = companyservicePropService.selectPropByKey(companyservice.getCompanyid(), "webservice_password");
        if (keyProp == null || !StringUtils.equals(keyProp.getValue(), Password)) {
            return buildResult(result, "035", "交互密码错误，请确认密码是否输入正确！", null);
        }

        // 调用发票查询接口
        String serviceKey = "";
        try {
            serviceKey = serviceManageService.getCompanyServiceSupplier("income", companyservice.getCompanyid());
        } catch (Exception e) {
            e.printStackTrace();
            return buildResult(result, "1", "发票查询失败", null);
        }
        if (StringUtils.isEmpty(serviceKey)) {
            log.error("【发票查询失败】companyid:{}，serviceKey为空", companyservice.getCompanyid());
            return buildResult(result, "1", "发票查询失败", null);
        }

        ICheckInvoice incomeService = incomeServiceFactory.getService(serviceKey);
        if (incomeService == null) {
            log.error("【发票查询失败】companyid:{}，serviceKey:{}，incomeService为空", companyservice.getCompanyid(), serviceKey);
            return buildResult(result, "1", "发票查询失败", null);
        }

        // 调用发票查询接口
        JSONObject request = new JSONObject();
        request.put("fpzl", Fpzl);
        request.put("fpje", Kpje);
        request.put("fpdm", InvCode);
        Date kprqDate = null;
        try {
            kprqDate = DateUtils.parseDate(InvTime, "yyyy-MM-dd");
        } catch (ParseException e) {
            log.error("【发票查询失败】companyid:{}，serviceKey:{}，kprqDate解析失败", companyservice.getCompanyid(), serviceKey);
        }
        String kprq = InvTime;
        if (kprqDate != null) {
            kprq = DateUtils.parseDateToStr("yyyyMMdd", kprqDate);
        }
        request.put("kprq", kprq);
        request.put("fphm", InvNo);
        request.put("jym", Jym);
        AjaxResult invoiceResult = incomeService.checkInvoiceSingle(companyservice, request);
        log.info("【发票查询结果】companyid:{}，serviceKey:{}，param:{},invoiceResult:{}", companyservice.getCompanyid(), serviceKey, request, JSONObject.toJSONString(invoiceResult));
        // JSONObject data = JSONObject.parseObject("{\n" +
        //         "        \"robUserMoney\": 0,\n" +
        //         "        \"resultContent\": {\n" +
        //         "            \"cjhj\": \"\",\n" +
        //         "            \"dzzfbs\": \"\",\n" +
        //         "            \"gmfmc\": \"\",\n" +
        //         "            \"zgswjgmc\": \"\",\n" +
        //         "            \"qydjyddd\": \"\",\n" +
        //         "            \"dw\": \"\",\n" +
        //         "            \"bswjurl\": \"\",\n" +
        //         "            \"shrmc\": \"\",\n" +
        //         "            \"jypmdwdzsbh\": \"\",\n" +
        //         "            \"skr\": \"\",\n" +
        //         "            \"cllx\": \"\",\n" +
        //         "            \"djzh\": \"\",\n" +
        //         "            \"mfdwgr\": \"\",\n" +
        //         "            \"cyjg\": \"1005\",\n" +
        //         "            \"khyh\": \"\",\n" +
        //         "            \"qdbz\": \"\",\n" +
        //         "            \"xhfdzdh\": \"\",\n" +
        //         "            \"txfbz\": \"\",\n" +
        //         "            \"jypmdw\": \"\",\n" +
        //         "            \"zrdcgsmc\": \"\",\n" +
        //         "            \"jypmdwdz\": \"\",\n" +
        //         "            \"fpse\": \"\",\n" +
        //         "            \"kpr\": \"\",\n" +
        //         "            \"sjdh\": \"\",\n" +
        //         "            \"shrsbh\": \"\",\n" +
        //         "            \"czch\": \"\",\n" +
        //         "            \"cpxh\": \"\",\n" +
        //         "            \"smfdwgr\": \"\",\n" +
        //         "            \"gmfdzdh\": \"\",\n" +
        //         "            \"fpje\": \"1403016L1NN5336\",\n" +
        //         "            \"detailList\": [],\n" +
        //         "            \"cyjgxx\": \"查询发票不规范\",\n" +
        //         "            \"jshj\": \"\",\n" +
        //         "            \"zgswjgdm\": \"\",\n" +
        //         "            \"zfbz\": \"\",\n" +
        //         "            \"fdjhm\": \"\",\n" +
        //         "            \"jypmdwdh\": \"\",\n" +
        //         "            \"escsc\": \"\",\n" +
        //         "            \"gmfyhzh\": \"\",\n" +
        //         "            \"xhfmc\": \"\",\n" +
        //         "            \"cycs\": \"\",\n" +
        //         "            \"hgzs\": \"\",\n" +
        //         "            \"fhrmc\": \"\",\n" +
        //         "            \"xhfyhzh\": \"\",\n" +
        //         "            \"gmfsbh\": \"\",\n" +
        //         "            \"fpzl\": \"01\",\n" +
        //         "            \"mfdwgrdz\": \"\",\n" +
        //         "            \"xcrs\": \"\",\n" +
        //         "            \"clsbh\": \"\",\n" +
        //         "            \"kprq\": \"2022-08-31\",\n" +
        //         "            \"smfdh\": \"\",\n" +
        //         "            \"bz\": \"\",\n" +
        //         "            \"sl\": \"\",\n" +
        //         "            \"ccdw\": \"\",\n" +
        //         "            \"khyhjzh\": \"\",\n" +
        //         "            \"escscdz\": \"\",\n" +
        //         "            \"cd\": \"\",\n" +
        //         "            \"escscsbh\": \"\",\n" +
        //         "            \"fpdm\": \"2200214130\",\n" +
        //         "            \"skph\": \"\",\n" +
        //         "            \"mfdwdmsfzh\": \"\",\n" +
        //         "            \"yshwxx\": \"\",\n" +
        //         "            \"xhfsbh\": \"\",\n" +
        //         "            \"mfdh\": \"\",\n" +
        //         "            \"fhr\": \"\",\n" +
        //         "            \"wspzhm\": \"\",\n" +
        //         "            \"lslbs\": \"\",\n" +
        //         "            \"smfdwgrzz\": \"\",\n" +
        //         "            \"smfdwdmsfzh\": \"\",\n" +
        //         "            \"escscdh\": \"\",\n" +
        //         "            \"cyrsbh\": \"\",\n" +
        //         "            \"spfshb\": \"\",\n" +
        //         "            \"sfzh\": \"\",\n" +
        //         "            \"fhrsbh\": \"\",\n" +
        //         "            \"cpzh\": \"\",\n" +
        //         "            \"spfmc\": \"\",\n" +
        //         "            \"jkzmsh\": \"\",\n" +
        //         "            \"escsckhyhzh\": \"\",\n" +
        //         "            \"khzh\": \"\",\n" +
        //         "            \"cyrmc\": \"\",\n" +
        //         "            \"jqbh\": \"\",\n" +
        //         "            \"fphm\": \"01779700\",\n" +
        //         "            \"jym\": \"1403016L1NN5336\"\n" +
        //         "        }\n" +
        //         "    }");
        // AjaxResult invoiceResult = AjaxResult.success(data);
        if (invoiceResult.isError()) {
            if ("超过该张票当天查验次数".equals(invoiceResult.getMsg())) {
                return buildResult(result, "002", "超过该张发票当日查验次数(请于次日再次查验)！", null);
            } else if ("查验异常".equals(invoiceResult.getMsg())) {
                return buildResult(result, "084", "开票金额或校验码不合法！", null);
            } else if ("请求不合法".equals(invoiceResult.getMsg())) {
                return buildResult(result, "005", "请求不合法！", null);
            } else if ("发票不存在".equals(invoiceResult.getMsg())) {
                return buildResult(result, "009", "查无此票！", null);
            } else {
                return buildResult(result, StrUtil.padPre(String.valueOf(invoiceResult.getCode()), 3, '0'), invoiceResult.getMsg(), null);
            }

        }

        if (invoiceResult.isSuccess()) {
            JSONObject resp = invoiceResult.getJsonData();
            Integer robUser = resp.getInteger("robUserMoney");
            if (robUser != null && robUser >= 1) {
                serviceManageService.companyConsume("income", companyservice.getCompanyid());
            }
        }

        // 如果开票成功
        JSONObject invoiceJsonResult = invoiceResult.getJsonData();
        JSONObject resultContent = invoiceJsonResult.getJSONObject("resultContent");
        InvoiceCheck invoiceCheck = new InvoiceCheck();
        invoiceCheck = EleCheckInvoiceImpl.handelCheckResult(invoiceCheck, resultContent);
        GetInvoiceVO getInvoiceVO = new GetInvoiceVO();
        // 远得日期格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String newKprq = "";
        try {
            Date parseKprq = simpleDateFormat.parse(invoiceCheck.getKprq());
            simpleDateFormat.applyPattern("yyyy-MM-dd");
            newKprq = simpleDateFormat.format(parseKprq);
        } catch (ParseException e) {
            new JianshuiServiceException("日期转换错误");
        }
        // 远得结果集
        String zfbz = invoiceCheck.getZfbz();
        if (StringUtils.equals(zfbz, "Y")) {
            getInvoiceVO.setZfbz("Y");
            getInvoiceVO.setHcbz("N");
        }
        if (StringUtils.equals(zfbz, "H")) {
            getInvoiceVO.setZfbz("N");
            getInvoiceVO.setHcbz("Y");
        }
        if (StringUtils.equals(zfbz, "N")) {
            getInvoiceVO.setZfbz("N");
            getInvoiceVO.setHcbz("N");
        }
        // 远得返回信息封装
        LinkedHashMap<String,String> getInvoiceMap = new LinkedHashMap();
        getInvoiceMap.put("fpdm",invoiceCheck.getFpdm());
        getInvoiceMap.put("fphm",invoiceCheck.getFphm());
        getInvoiceMap.put("kprq",newKprq);
        // 远得返回信息封装
        if (!InvoiceType.ER_SHOU_CHE_PIAO.getCode().equals(invoiceCheck.getFpzl()) &&
                !InvoiceType.JI_DONG_CHE_PIAO.getCode().equals(invoiceCheck.getFpzl())){
            getInvoiceMap.put("gfmc",invoiceCheck.getGmfmc());
            getInvoiceMap.put("gfsh",invoiceCheck.getGmfsbh());
            getInvoiceMap.put("gfdzdh",invoiceCheck.getGmfdzdh());
            getInvoiceMap.put("Gfyhzh",invoiceCheck.getGmfyhzh());
            getInvoiceMap.put("Xfmc",invoiceCheck.getXhfmc());
            getInvoiceMap.put("Xfsh",invoiceCheck.getXhfsbh());
            getInvoiceMap.put("Xfdzdh",invoiceCheck.getXhfdzdh());
            getInvoiceMap.put("Xfyhzh",invoiceCheck.getXhfyhzh());
        }
        // 远得类型返回信息封装
        if (InvoiceType.ER_SHOU_CHE_PIAO.getCode().equals(invoiceCheck.getFpzl())) {
            // 二手车相关结果
            getInvoiceMap.put("gfmc",invoiceCheck.getInvoiceCheckUsedCar().getMfdwgr());
            getInvoiceMap.put("gfsh",invoiceCheck.getInvoiceCheckUsedCar().getMfdwdmsfzh());
            String gfdzdh = invoiceCheck.getInvoiceCheckUsedCar().getMfdwgrdz() + " " +
                    invoiceCheck.getInvoiceCheckUsedCar().getMfdh();
            getInvoiceMap.put("gfdzdh",gfdzdh);
            getInvoiceMap.put("Gfyhzh",invoiceCheck.getInvoiceCheckUsedCar().getKhyhjzh());
            getInvoiceMap.put("Xfmc",invoiceCheck.getInvoiceCheckUsedCar().getSmfdwgr());
            getInvoiceMap.put("Xfsh",invoiceCheck.getInvoiceCheckUsedCar().getSmfdwdmsfzh());
            String xfdzdh = invoiceCheck.getInvoiceCheckUsedCar().getSmfdwgrzz() + " " +
                    invoiceCheck.getInvoiceCheckCar().getSmfdh();
            getInvoiceMap.put("Xfdzdh",xfdzdh);
            getInvoiceMap.put("Xfyhzh",invoiceCheck.getInvoiceCheckUsedCar().getKhyhjzh());
            getInvoiceMap.put("Jqbm",invoiceCheck.getJqbh());
            getInvoiceMap.put("cpzh",invoiceCheck.getInvoiceCheckUsedCar().getCpzh());
            getInvoiceMap.put("djzh",invoiceCheck.getInvoiceCheckUsedCar().getDjzh());
            getInvoiceMap.put("cllx",invoiceCheck.getInvoiceCheckUsedCar().getCllx());
            getInvoiceMap.put("Cjh",invoiceCheck.getInvoiceCheckUsedCar().getClsbh());
            getInvoiceMap.put("cpxh",invoiceCheck.getInvoiceCheckUsedCar().getCpxh());
            getInvoiceMap.put("Zrdclglsmc",invoiceCheck.getInvoiceCheckUsedCar().getZrdcgsmc());
            getInvoiceMap.put("Cjhj",invoiceCheck.getInvoiceCheckUsedCar().getCjhj());
            getInvoiceMap.put("escsc",invoiceCheck.getInvoiceCheckUsedCar().getEscsc());
            getInvoiceMap.put("Nsrsbh",invoiceCheck.getInvoiceCheckUsedCar().getEscscsbh());
            getInvoiceMap.put("Escscdz",invoiceCheck.getInvoiceCheckUsedCar().getEscscdz());
            getInvoiceMap.put("Khyh",invoiceCheck.getInvoiceCheckUsedCar().getEscsckhyhzh());
            getInvoiceMap.put("escscdh",invoiceCheck.getInvoiceCheckUsedCar().getEscscdh());
            getInvoiceMap.put("Fplx",invoiceCheck.getFpzl());
            getInvoiceMap.put("ZFBZ",invoiceCheck.getZfbz());
            getInvoiceMap.put("bz",invoiceCheck.getBz());
        } else if (InvoiceType.JI_DONG_CHE_PIAO.getCode().equals(invoiceCheck.getFpzl())) {
            // 机动车相关结果
            getInvoiceMap.put("gfmc",invoiceCheck.getGmfmc());
            getInvoiceMap.put("gfsh",invoiceCheck.getGmfsbh());
            getInvoiceMap.put("Jqbm",invoiceCheck.getJqbh());
            getInvoiceMap.put("cllx",invoiceCheck.getInvoiceCheckCar().getCllx());
            getInvoiceMap.put("cpxh",invoiceCheck.getInvoiceCheckCar().getCpxh());
            getInvoiceMap.put("cd",invoiceCheck.getInvoiceCheckCar().getCd());
            getInvoiceMap.put("Hgzh",invoiceCheck.getInvoiceCheckCar().getHgzs());
            getInvoiceMap.put("Sjdh",invoiceCheck.getInvoiceCheckCar().getSjdh());
            getInvoiceMap.put("Fdjhm",invoiceCheck.getInvoiceCheckCar().getFdjhm());
            getInvoiceMap.put("Clsbdh",invoiceCheck.getInvoiceCheckCar().getClsbh());
            if (invoiceCheck.getInvoiceCheckCar().getJszmsh() == null) {
                getInvoiceMap.put("Jkzmsh","");
            } else {
                getInvoiceMap.put("Jkzmsh",invoiceCheck.getInvoiceCheckCar().getJszmsh());
            }
            getInvoiceMap.put("Xfmc",invoiceCheck.getXhfmc());
            getInvoiceMap.put("Xfsh",invoiceCheck.getXhfsbh());
            getInvoiceMap.put("Dz",invoiceCheck.getGmfdzdh());
            getInvoiceMap.put("Dh",invoiceCheck.getInvoiceCheckCar().getSmfdh());
            getInvoiceMap.put("Khyh",invoiceCheck.getInvoiceCheckCar().getKhyh());
            getInvoiceMap.put("Zh",invoiceCheck.getInvoiceCheckCar().getKhzh());
            getInvoiceMap.put("zgswjg",invoiceCheck.getInvoiceCheckCar().getZgswjgdm());
            getInvoiceMap.put("zgswjgmc",invoiceCheck.getInvoiceCheckCar().getZgswjgmc());
            getInvoiceMap.put("Wspzhm",invoiceCheck.getInvoiceCheckCar().getWspzhm());
            getInvoiceMap.put("Dw",invoiceCheck.getInvoiceCheckCar().getDw());
            getInvoiceMap.put("xcrs",invoiceCheck.getInvoiceCheckCar().getXcrs());;
            getInvoiceMap.put("Fplx",invoiceCheck.getFpzl());
            getInvoiceMap.put("ZFBZ",invoiceCheck.getZfbz());
            getInvoiceMap.put("sl",invoiceCheck.getInvoiceCheckCar().getSl());
        }else if (InvoiceType.ZHUAN_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                InvoiceType.ZHENG_ZHI_SHUI_PU_TONG_FA_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                InvoiceType.DIAN_ZI_ZHUAN_YONG_FA_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                InvoiceType.QUAN_DIAN_ZHUAN_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                InvoiceType.QUAN_DIAN_PU_PIAO.getCode().equals(invoiceCheck.getFpzl())) {
            // 专票 增值税普通发票 电子专用发票结果
            getInvoiceMap.put("bz",invoiceCheck.getBz());
            getInvoiceMap.put("Jqbm",invoiceCheck.getJqbh());
            getInvoiceMap.put("Fplx",invoiceCheck.getFpzl());
            getInvoiceMap.put("jym",invoiceCheck.getJym());
            getInvoiceMap.put("HCBZ",getInvoiceVO.getHcbz());
            getInvoiceMap.put("ZFBZ",getInvoiceVO.getZfbz());
        }else if (InvoiceType.TONG_XING_FEI_FA_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                InvoiceType.JUAN_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                InvoiceType.DIAN_ZI_PU_PIAO.getCode().equals(invoiceCheck.getFpzl())){
            getInvoiceMap.put("bz",invoiceCheck.getBz());
            getInvoiceMap.put("Jqbm",invoiceCheck.getJqbh());
            getInvoiceMap.put("Fplx",invoiceCheck.getFpzl());
            getInvoiceMap.put("jym",invoiceCheck.getJym());
            getInvoiceMap.put("ZFBZ",getInvoiceVO.getZfbz());
            getInvoiceMap.put("HCBZ",getInvoiceVO.getHcbz());
        }
        Set<Map.Entry<String, String>> entries = getInvoiceMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String value = entry.getValue();
            if ("".equals(value)){
                entry.setValue("00");
            }
        }
        Element getInvoiceDoc = json2Element(result, "Fp", getInvoiceMap);
        // 详情获取
        List<InvoiceCheckDetail> details = invoiceCheck.getInvoiceCheckDetail();
        LinkedHashMap<String, String> getInvoiceSphVOMap = new LinkedHashMap<>();
        if (CollectionUtil.isNotEmpty(details)) {
            int count = 1;
            for (InvoiceCheckDetail detail : details) {
                GetInvoiceSphVO getInvoiceSphVO = new GetInvoiceSphVO();
                getInvoiceSphVO.setId(getInvoiceSphVO.getId() + count);
                // 远得详情封装
                if (!InvoiceType.JI_DONG_CHE_PIAO.getCode().equals(invoiceCheck.getFpzl()) &&
                        !InvoiceType.ER_SHOU_CHE_PIAO.getCode().equals(invoiceCheck.getFpzl())){
                    getInvoiceSphVOMap.put("xh",String.valueOf(getInvoiceSphVO.getId()));
                    getInvoiceSphVOMap.put("Spmc",detail.getHwmc());
                }
                // 远得详情封装
                if (InvoiceType.JUAN_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                        InvoiceType.DIAN_ZI_PU_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                        InvoiceType.ZHENG_ZHI_SHUI_PU_TONG_FA_PIAO.getCode().equals(invoiceCheck.getFpzl())) {
                    // 卷票 电普 增值税普通发票 电子专用发票详情
                    getInvoiceSphVOMap.put("Ggxh",detail.getGgxh());
                    getInvoiceSphVOMap.put("Jldw",detail.getJldw());
                    getInvoiceSphVOMap.put("Sl",detail.getSpsl());
                    getInvoiceSphVOMap.put("Dj",detail.getBhsdj());
                    getInvoiceSphVOMap.put("Je",detail.getJe());
                    getInvoiceSphVOMap.put("Se",detail.getSe());
                    getInvoiceSphVOMap.put("Slv",detail.getSl());
                    getInvoiceSphVOMap.put("Taxcode",detail.getSsflbm());
                } else if (InvoiceType.QUAN_DIAN_ZHUAN_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                        InvoiceType.QUAN_DIAN_PU_PIAO.getCode().equals(invoiceCheck.getFpzl()) ||
                        InvoiceType.ZHUAN_PIAO.getCode().equals(invoiceCheck.getFpzl())||
                        InvoiceType.DIAN_ZI_ZHUAN_YONG_FA_PIAO.getCode().equals(invoiceCheck.getFpzl())) {
                    // 全电专票 全电普票 专票详情
                    getInvoiceSphVOMap.put("Ggxh",detail.getGgxh());
                    getInvoiceSphVOMap.put("Jldw",detail.getJldw());
                    getInvoiceSphVOMap.put("Sl",detail.getSpsl());
                    getInvoiceSphVOMap.put("Dj",detail.getBhsdj());
                    getInvoiceSphVOMap.put("Je",detail.getJe());
                    getInvoiceSphVOMap.put("Slv",detail.getSl());
                    getInvoiceSphVOMap.put("Se",detail.getSe());
                    getInvoiceSphVOMap.put("Taxcode",detail.getSsflbm());
                } else if (InvoiceType.TONG_XING_FEI_FA_PIAO.getCode().equals(invoiceCheck.getFpzl())) {
                    // 通行发票
                    getInvoiceSphVOMap.put("cph",detail.getCph());
                    getInvoiceSphVOMap.put("cllx",detail.getLx());
                    getInvoiceSphVOMap.put("txrqq",detail.getTxrqq());
                    getInvoiceSphVOMap.put("txrqz",detail.getTxrqz());
                    getInvoiceSphVOMap.put("Je",detail.getJe());
                    getInvoiceSphVOMap.put("Se",detail.getSe());
                    getInvoiceSphVOMap.put("Slv",detail.getSl());
                    getInvoiceSphVOMap.put("Taxcode",detail.getSsflbm());
                }
                if (!InvoiceType.JI_DONG_CHE_PIAO.getCode().equals(invoiceCheck.getFpzl()) &&
                        !InvoiceType.ER_SHOU_CHE_PIAO.getCode().equals(invoiceCheck.getFpzl())){
                    Set<Map.Entry<String, String>> entries1 = getInvoiceSphVOMap.entrySet();
                    for (Map.Entry<String, String> stringStringEntry : entries1) {
                        String value = stringStringEntry.getValue();
                        if ("".equals(value)){
                            stringStringEntry.setValue("00");
                        }
                    }
                    Element sphElement = json2Element(result, "Sph", getInvoiceSphVOMap);
                    getInvoiceDoc.appendChild(sphElement);
                    count++;
                }
            }
        }
        // 尾部标签添加
        if (!InvoiceType.ER_SHOU_CHE_PIAO.getCode().equals(invoiceCheck.getFpzl())){
            // je标签添加
            LinkedHashMap<String, String> jeLinkedHashMap = new LinkedHashMap<>();
            jeLinkedHashMap.put("je",StringUtils.isEmpty(invoiceCheck.getFpje())? "00" :invoiceCheck.getFpje());
            Element je = jsonElement(result, "je", jeLinkedHashMap);
            getInvoiceDoc.appendChild(je);

            // se标签添加
            LinkedHashMap<String, String> seLinkedHashMap = new LinkedHashMap<>();
            seLinkedHashMap.put("se",StringUtils.isEmpty(invoiceCheck.getFpse())? "00" :invoiceCheck.getFpse());
            Element se = jsonElement(result, "se", seLinkedHashMap);
            getInvoiceDoc.appendChild(se);

            // jshj标签添加
            LinkedHashMap<String, String> jshjLinkedHashMap = new LinkedHashMap<>();
            jshjLinkedHashMap.put("jshj",StringUtils.isEmpty(invoiceCheck.getJshj())? "00" :invoiceCheck.getJshj());
            Element jshj = jsonElement(result, "jshj", jshjLinkedHashMap);
            getInvoiceDoc.appendChild(jshj);
        }
        return buildResult(result, "1", "查验成功", getInvoiceDoc);
    }

    private Element json2Element(Document result, String elementName, Map<String,String> jsonObject) {
        Element parent = result.createElement(elementName);
        jsonObject.keySet().forEach(key -> {
            String value = jsonObject.get(key);
            // 转为全小写
            String firstKey = key.substring(0, 1);
            String upperKey = firstKey.toUpperCase();
            String endKey = key.substring(1, key.length());
            key = upperKey + endKey.toLowerCase();
            Element element = result.createElement(key);
            element.setTextContent(value);
            parent.appendChild(element);
        });
        return parent;
    }


    // 尾部标签添加
    private Element jsonElement(Document result,String key,Map<String,String> map) {
        String value = map.get(key);
        // 转为全小写
        String firstKey = key.substring(0, 1);
        String upperKey = firstKey.toUpperCase();
        String endKey = key.substring(1, key.length());
        key = upperKey + endKey.toLowerCase();
        Element element = result.createElement(key);
        element.setTextContent(value);
        return element;
    }

    private ResponseCheckVO buildResult(Document result, String code, String message, Element fp) {
        Element Data = result.createElement("Data");
        Element Result = result.createElement("Result");
        Element Code = result.createElement("Code");
        Code.setTextContent(code);  //1:查验成功 其余失败
        Element Message = result.createElement("Message");
        Message.setTextContent(message);
        Result.appendChild(Code);
        Result.appendChild(Message);
        if (fp == null) {
            fp = result.createElement("Fp");
        }
        Data.appendChild(Result);
        Data.appendChild(fp);

        ResponseCheckVO resp = new ResponseCheckVO();
        ResponseCheckDataVO vo = new ResponseCheckDataVO();
        ResponseCheckResultVO responseCheckResultVO = new ResponseCheckResultVO();
        responseCheckResultVO.setCode(Code.getTextContent());
        responseCheckResultVO.setMessage(Message.getTextContent());
        Object myFp = fp;
        vo.setResult(responseCheckResultVO);
        vo.setFp(myFp);
        resp.setDATA(vo);

        return resp;
    }

    // private WebServiceRespVO buildResult(Document result, String code, String message, Element fp) {
    //     WebServiceRespVO webServiceRespVO = new WebServiceRespVO();
    //     WebServiceRespVO.Result respResult = new WebServiceRespVO.Result();
    //     respResult.setCode(code);
    //     respResult.setMessage(message);
    //     webServiceRespVO.setResult(respResult);
    //     if (fp != null) {
    //         webServiceRespVO.setFp(XmlUtil.toStr(fp, "GBK", false, true));
    //     }
    //     return webServiceRespVO;
    // }
}