package com.jianshui.income.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.utils.Base64Util;
import com.jianshui.common.utils.ElephantCommonUtils;
import com.jianshui.common.utils.InvoiceUtils;
import com.jianshui.common.utils.StringUtils;
import com.jianshui.income.constant.elephant.ElephantConstants;
import com.jianshui.income.domain.entity.*;
import com.jianshui.income.mapper.*;
import com.jianshui.income.service.ICheckInvoice;
import com.jianshui.income.utils.elephant.ElephantUtils;
import com.jianshui.queue.utils.RedisQueueUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description 大象的发票校验
 * @Author 巩权林
 * @Date 2021/4/15 14:25
 **/

@Component(value = "elephant_income") // 这里是后台字典的服务配置键值 配置的
public class EleCheckInvoiceImpl implements ICheckInvoice {

    private static final Logger log = LoggerFactory.getLogger(EleCheckInvoiceImpl.class);
    @Autowired
    private InvoiceCheckMapper invoiceCheckMapper;

    @Autowired
    private InvoiceCheckCarMapper invoiceCheckCarMapper;

    @Autowired
    private InvoiceCheckDetailMapper invoiceCheckDetailMapper;

    @Autowired
    private InvoiceCheckFreightMapper invoiceCheckFreightMapper;

    @Autowired
    private InvoiceCheckTollMapper invoiceCheckTollMapper;

    @Autowired
    private InvoiceCheckUsedCarMapper invoiceCheckUsedCarMapper;


    /**
     * @return
     * @Title 单个发票校验
     * @Author Gongquanlin
     * @Description
     * @Param
     * @Date 2021/4/15 14:26
     **/
    @Override
    public AjaxResult checkInvoiceSingle(Companyservice companyservice, JSONObject data) {
        String companyId = Long.toString(companyservice.getCompanyid());
        int robUserMoney = 0; // 是否扣用户的钱
        // 先判断一下是否符合传入的规定
        log.info("单个发票校验入参：companyId=" + companyId + ",data=" + data);
        AjaxResult validateResult = validateInvoiceCheck(data);
        if (validateResult.isSuccess() == false) {
            return validateResult;
        }

//        2021年5月11日,teh:考虑到发票会冲红、作废，每次都获取最新状态
//        开始向数据库查询数据是否正确
//        AjaxResult myTempResult = handleSelectedInvoiceCheck(companyId, data);
//        if (myTempResult.isSuccess() == true) {
//            return myTempResult;
//        }

        AjaxResult insResult = insertInvoice(companyId, data); // 只能分开插入，否则下面回滚会出现事务还没有提交，但是更新外表没有这个键导致外键约束失败
        if (insResult.isSuccess() == false) {
            return insResult;
        }

        InvoiceCheck invoiceCheck = (InvoiceCheck) insResult.getData();

        // 请求类实现
        String uri = ElephantConstants.CHECK_INVOICE_SINGLE;
        // boolean devMode = StringUtils.equals(companyservice.getSellertax(), "91370102MA3UD2FG21");
        boolean devMode = false;

        JSONObject resp = ElephantUtils.sendRequest(uri, data, devMode);
//        //2021年5月9日：tianenhui 添加使用次数统计-------暂时不用这种方式，采用调一次接口就算一次
//        iServicemanagerService.updateSurplus(companyId,"check",1);
        // 获得返回数据，看下结果

        JSONObject returnStateInfo = resp.getJSONObject("returnStateInfo");
        if ("0000".equals(returnStateInfo.getString("returnCode")) == false) { // 如果返回值不是0000，说明有错误
            String errorString = Base64Util.decrypt(returnStateInfo.getString("returnMessage"));
            int errorCode = returnStateInfo.getInteger("returnCode");
            log.info("单个发票校验错误结果：companyId=" + companyId + ",data=" + data + ",errorCode=" + errorCode + ",returnMessage=" + errorString);
            return AjaxResult.error(errorCode, errorString);
        }

        // 否则成功
        String resultStr = resp.getString("content");
        JSONObject resultJson = JSONObject.parseObject(Base64Util.decrypt(resultStr)); // 获得返回的数据
        log.info("单个发票校验成功结果：companyId=" + companyId + ",data=" + data + ",resultJson=" + resultJson);
        // 处理返回的数据
        // 处理invoice_check
        JSONObject resultContent = resultJson.getJSONObject("data");
        if (resultContent == null) { // 如果这里为null，可能出现查验失败，大象报错有可能在最外层的returnCode里报错，也可能在data里的code报错，巨坑
            String checkResult = resultJson.getString("code");
            if ("0001".equals(checkResult) || "0006".equals(checkResult) || "0009".equals(checkResult) || "1005".equals(checkResult) ) {
                // 如果需要扣费
                robUserMoney += 1;
            }

            String errorMsg = resultJson.getString("message");
            JSONObject result = new JSONObject();
            result.put("robUserMoney", robUserMoney);
            return new AjaxResult(Integer.parseInt(checkResult), errorMsg, result);
        }
        invoiceCheck = this.handelCheckResult(invoiceCheck, resultContent); // 批量处理一把
        invoiceCheckMapper.updateInoviceById(invoiceCheck);

        List<String> cyjgList = Arrays.asList("9999", "0002", "0005",  "1004", "1006", "1007", "1008", "1009","1010", "1011", "1012", "1013", "1014", "1015", "1020", "1021");
        if (cyjgList.contains(invoiceCheck.getCyjg())) {
            log.info("单个发票校验错误结果：companyId=" + companyId + ",errorCode=" + invoiceCheck.getCyjg() + ",returnMessage=" + invoiceCheck.getCyjgxx());
            return new AjaxResult(5,invoiceCheck.getCyjgxx());
        }

        // note-gong 2021/6/17 9:20 查询下数据库中是否存在相同发票；存在就判断下状态是否一致，不一致扣款；不存在就直接扣款
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) - 7);
        Date date = cal.getTime();
        String nowDate = df.format(date);
        List<InvoiceCheck> queryInvs = new ArrayList<>();
        queryInvs.add(invoiceCheck);
        List<InvoiceCheck> oldInvoiceCheckList = invoiceCheckMapper.selectInvoiceCheckByFpdmAndFphmWithouPch(queryInvs, nowDate, companyId);
        if (oldInvoiceCheckList != null && oldInvoiceCheckList.size() > 0) {
            // 如果存在发票数据，处理一把，判断下黄台是否更改
            // 因为是根据日期倒叙，所以取最后一条created_at
            InvoiceCheck tempInv = oldInvoiceCheckList.get(0);
            String zfbz = tempInv.getZfbz(); // 作废标志
            String cyjg = tempInv.getCyjg(); // 查验结果
            String resultZfbz = invoiceCheck.getZfbz();
            String resultCyjg = invoiceCheck.getCyjg();
            if (zfbz != null && cyjg != null) { // 如果查询均不为null
                // 必须保证这两个值不为空，那边才查验成功
                if ((resultZfbz != null && !"".equals(resultZfbz)) && (resultCyjg != null && !"".equals(resultCyjg))) {
                    // 这时候再判断下要不要扣用户的钱
                    if (!resultZfbz.equals(zfbz)) { // 如果作废标志变了，说明已经冲红/作废了，扣钱；查验结果可能有多种，比如超时，不能作为判断依据。
                        robUserMoney += 1;
                    }
                }
            }
        } else {
            // 如果不存在用户数据，判断下状态，如果查验结果属于成功，则扣钱
            String checkResult = invoiceCheck.getCyjg();
            if ("0001".equals(checkResult) || "0006".equals(checkResult) || "0009".equals(checkResult) || "1005".equals(checkResult)) {
                // 如果需要扣费
                robUserMoney += 1;
            }
        }
        JSONObject result = new JSONObject();
        String xhfdh = invoiceCheck.getXhfdh();
        resultContent.put("xhfdh", xhfdh);
        String xhfdz = invoiceCheck.getXhfdz();
        resultContent.put("xhfdz", xhfdz);
        result.put("robUserMoney", robUserMoney);
        result.put("resultContent", resultContent);
        // 开始批量更新数据库 老田加的队列。这里没有。他写的队列也不对，上面已经插入过了这里还插入。SB
        // RedisQueueUtil.build().setData(invoiceCheck).onQueue("income_result_save_consumer").retry(0).dispatch();

        if (!"0001".equals(invoiceCheck.getCyjg()) ) {
            log.info("单个发票校验错误结果：companyId=" + companyId + ",data=" + data + ",errorCode=" + invoiceCheck.getCyjg() + ",returnMessage=" + invoiceCheck.getCyjgxx());
            return new AjaxResult(Integer.parseInt(invoiceCheck.getCyjg()),invoiceCheck.getCyjgxx());
        }

        // TODO: 2023/6/7 测试关闭
        // ：校验是否查询本企业发票
        /*String xhfsbh = StrUtil.blankToDefault(invoiceCheck.getXhfsbh(), "");
        String xhfmc = StrUtil.blankToDefault(invoiceCheck.getXhfmc(), "");
        String sellerTax = companyservice.getSellertax();
        String sellerName = companyservice.getSellername();
        if (!sellerTax.equals(xhfsbh) || !StrUtil.equalsIgnoreCase(sellerName, xhfmc)) {
            log.info("单个发票校验非本企业发票：companyId=" + companyId + ",errorCode=" + invoiceCheck.getCyjg() + ",returnMessage=" + invoiceCheck.getCyjgxx());
            return new AjaxResult(34,"授权企业与所查询发票的购方不一致，请进行核实");
        }*/

        // 更新成功处理返回数据
        return AjaxResult.success(result);
    }

    /**
     * 批量查询发票
     *
     * @param companyservice
     * @param data
     * @return
     */
    @Override
    public AjaxResult checkInvoiceMultil(Companyservice companyservice, JSONObject data) {
        // 开始判断是否该有的都有
        JSONArray invoiceList = data.getJSONArray("invoiceList");
        if (invoiceList == null) {
            return AjaxResult.error(1022, "查询批次不能为空！");
        }
        String pch = data.getString("pch");
        if (pch == null) {
            return AjaxResult.error(1023, "批次号不能为空！");
        }
        // 如果批次号长度不为32，则补0
        int pchLength = pch.length();
        if (pchLength != 32) {
            for (int i = 0; i < 32 - pchLength; i++) {
                pch = "0" + pch;
            }
        }
        data.put("pch", pch);
        int pchResult = invoiceCheckMapper.isPchExist(Long.toString(companyservice.getCompanyid()), pch);
        if (pchResult != 0) {
            return AjaxResult.error(1024, "批次号重复！");
        }
        List<InvoiceCheck> invoiceCheckList = new ArrayList<>();
        for (Object tempInvoice : invoiceList) { // 判断一下invoice check中的数据是否都全
            JSONObject tempData = (JSONObject) tempInvoice;
            AjaxResult tempResult = validateInvoiceCheck(tempData);
            if (tempResult.isSuccess() == false) {
                return tempResult;
            }
            String jym = "";
            String fpje = "";
            String fpdm = "";
            String kprq = "";
            String fphm = "";
            String fpzl = "";
            jym = (String) tempData.get("jym");
            if (jym != null && jym.length() >= 6) {
                jym = jym.substring(jym.length() - 6, jym.length());
            }
            fpje = (String) tempData.get("fpje");
            fpdm = (String) tempData.get("fpdm");
            fpzl = (String) tempData.get("fpzl");
            if (StringUtils.isNotEmpty(fpdm) && StringUtils.equalsAny(fpzl, "21", "22")) {
                fpdm = "";
            }
            kprq = (String) tempData.get("kprq");
            fphm = (String) tempData.get("fphm");
            String[] fpzlList = {"01", "02", "03", "04", "10", "11", "14", "15", "08", "21", "22","61","83"};
            if (!Arrays.asList(fpzlList).contains(fpzl)) { // 如果不存发票种类，则挂掉
                return AjaxResult.error(1025, "发票种类非法！");
            }

            // 现在用大象的发票种类，诺诺的不全
            //fpzl = FpzlCoverUtil.ele ToNuonuo(fpzl);

            // 保存invoiceCheck
            InvoiceCheck invoiceCheck = new InvoiceCheck();
            invoiceCheck.setCompany_id(Long.toString(companyservice.getCompanyid()));
            invoiceCheck.setPch(pch);
            invoiceCheck.setJym(jym);
            invoiceCheck.setFpje(fpje);
            invoiceCheck.setFpdm(fpdm);
            invoiceCheck.setKprq(kprq);
            invoiceCheck.setFphm(fphm);
            invoiceCheck.setFpzl(fpzl);
            invoiceCheckList.add(invoiceCheck);
        }

        // 开始批量插入
        invoiceCheckMapper.insertInvoiceBatch(invoiceCheckList);

        // 开始批量请求接口
        // 请求类实现
        data.remove("taxNo");
        log.info("批量查验发票报文：" + data);
        boolean devMode = StringUtils.equals(companyservice.getSellertax(), "91370102MA3UD2FG21");
        JSONObject resp = ElephantUtils.sendRequest(ElephantConstants.MULTIL_CHECK_INVOICE, data, devMode);
        // 获得返回数据，看下结果
        JSONObject returnStateInfo = resp.getJSONObject("returnStateInfo");
        log.info("批量查验发票结果：" + resp.toJSONString());
        if ("0000".equals(returnStateInfo.getString("returnCode")) == false) { // 如果返回值不是0000，说明有错误
            String errorString = Base64Util.decrypt(returnStateInfo.getString("returnMessage"));
            int errorCode = returnStateInfo.getInteger("returnCode");
            return AjaxResult.error(errorCode, errorString);
        }

        // 还得获取一把content
        String resultStr = resp.getString("content");
        JSONObject resultJson = JSONObject.parseObject(Base64Util.decrypt(resultStr)); // 获得返回的数据
        if (!StringUtils.equals(resultJson.getString("code"), "0000")) {
            String errorString = resultJson.getString("message");
            int errorCode = resultJson.getInteger("code");
            return AjaxResult.error(errorCode, errorString);
        }

        // 处理结果
        JSONObject resultContent = resultJson.getJSONObject("data");
        log.info("批量查询结果:resultContent=" + resultContent);
        if (!StringUtils.equals(resultContent.getString("returnCode"), "0000")) {
            String errorString = resultContent.getString("returnMessage");
            int errorCode = resultContent.getInteger("returnCode");
            return AjaxResult.error(errorCode, errorString);
        }


        return AjaxResult.success("批次接收成功！");
    }

    /**
     * 批量查询结果
     *
     * @param companyservice
     * @param data
     * @return
     */
    @Override
    @Transactional
    public AjaxResult checkInvoiceMultilResult(Companyservice companyservice, JSONObject data) {
        String companyId = Long.toString(companyservice.getCompanyid());
        // 先获取批次号
        String pch = data.getString("pch");
        JSONObject returnJson = new JSONObject();
        // returnJson.put("success", true); // 如果success为true，控制器可以根据此参数对调用次数进行扣费
        // returnJson.put("data", null); //
        if (pch == null) {
            returnJson.put("success", false);
            returnJson.put("data", null);
            returnJson.put("msg", "查询批次不能为空！");
            return AjaxResult.error(1022, returnJson);
        }
        // 如果批次号长度不为32，则补0
        int pchLength = pch.length();
        if (pchLength != 32) {
            for (int i = 0; i < 32 - pchLength; i++) {
                pch = "0" + pch;
            }
        }
        data.put("pch", pch);
        data.remove("taxNo");
        // 开始批量拉回结果
        String uri = ElephantConstants.BATCH_GET_INVOICE;
        log.info("报文：" + data);
        boolean devMode = StringUtils.equals(companyservice.getSellertax(), "91370102MA3UD2FG21");
        JSONObject resp = ElephantUtils.sendRequest(uri, data, devMode);

        // 判断下是否成功
        JSONObject returnStateInfo = resp.getJSONObject("returnStateInfo");
        if ("0000".equals(returnStateInfo.getString("returnCode")) == false) { // 如果返回值不是0000，说明有错误
            String errorString = Base64Util.decrypt(returnStateInfo.getString("returnMessage"));
            int errorCode = returnStateInfo.getInteger("returnCode");
            returnJson.put("success", false);
            returnJson.put("data", null);
            returnJson.put("msg", errorString);
            return AjaxResult.error(errorCode, returnJson);
        }

        String resultStr = resp.getString("content");
        JSONObject resultJson = JSONObject.parseObject(Base64Util.decrypt(resultStr)); // 获得返回的数据

        // 处理结果
        JSONObject resultContent = resultJson.getJSONObject("data");
        log.info("批量查询结果:resultContent=" + resultContent);
        if (resultContent.getString("returnMessage") != null) {
            String errorString = resultContent.getString("returnMessage");
            int errorCode = resultContent.getInteger("returnCode");
            returnJson.put("success", false);
            returnJson.put("data", null);
            returnJson.put("msg", errorString);
            return AjaxResult.error(errorCode, returnJson);
        }

        AjaxResult queryResult = handleMultilQuery(companyId, resultContent);

        JSONArray invoiceJsonList = resultContent.getJSONArray("invoiceInfo");
        invoiceJsonList = ElephantCommonUtils.changeEleKeyToLower(invoiceJsonList); // 将key的大写字母全部转为小写。大象非常坑，返回的key全部都是第一个字母小写后面的大写。
        for (int i = 0; i < invoiceJsonList.size(); i++) {
            JSONObject tempInv = invoiceJsonList.getJSONObject(i);
            String xhfdzdh = tempInv.getString("xhfdzdh");
            if (StringUtils.isNotEmpty(xhfdzdh)) {
                String dh = InvoiceUtils.getMobile(xhfdzdh);
                if (StringUtils.isEmpty(dh)) {
                    dh = InvoiceUtils.getPhone(xhfdzdh);
                }
                if (StringUtils.isNotEmpty(dh)) {
                    tempInv.put("xhfdz", xhfdzdh.replace(dh, ""));
                    tempInv.put("xhfdh", dh);
                }
            }

        }
        resultContent.put("invoiceInfo", invoiceJsonList);
        // 开始计算查验成功的发票数量
        // int successNum = 0; // 查验成功的发票数量
        // if (invoiceJsonList != null && invoiceJsonList.size() > 0) {
        //     for (int i = 0; i < invoiceJsonList.size(); i++) {
        //         JSONObject tempJson = invoiceJsonList.getJSONObject(i);
        //         String checkResult = tempJson.getString("cyjg");
        //         if ("0001".equals(checkResult) || "0006".equals(checkResult) || "0009".equals(checkResult)) {
        //             // 如果需要扣费
        //             successNum += 1;
        //         }
        //     }
        // }

        if (queryResult.isSuccess() == false) {
            returnJson.put("success", false);
            returnJson.put("data", null);
            returnJson.put("msg", queryResult.getMsg());
            return AjaxResult.error(returnJson);
        }
        JSONObject result = (JSONObject) queryResult.get("data");
        Integer successNum = result.getInteger("robUserMoney"); // 查验成功的发票数量
        returnJson.put("success", false);
        if (successNum != null && successNum > 0) {
            returnJson.put("success", true);
            returnJson.put("successNum", successNum);
        }
        // String errorCodeString = returnStateInfo.getString("returnCode");
        returnJson.put("data", resultContent);
        returnJson.put("msg", "success");
        return AjaxResult.success(returnJson);
    }

    /**
     * 处理批量查询的结果
     *
     * @param companyId
     * @param data
     * @return
     */
    @Transactional
    public AjaxResult handleMultilQuery(String companyId, JSONObject data) {
        int robUserMoney = 0; // 用户成功计费的发票条数
        // 开始批量处理数据
        JSONArray invoiceJsonList = data.getJSONArray("invoiceInfo");
        invoiceJsonList = ElephantCommonUtils.changeEleKeyToLower(invoiceJsonList); // 将key的大写字母全部转为小写。大象非常坑，返回的key全部都是第一个字母小写后面的大写。
        String pch = data.getString("pch");
        List<InvoiceCheck> invoiceCheckList = new ArrayList<>();
        List<InvoiceCheckCar> invoiceCheckCars = new ArrayList<>();
        List<InvoiceCheckFreight> invoiceCheckFreights = new ArrayList<>();
        List<InvoiceCheckToll> invoiceCheckTolls = new ArrayList<>();
        List<InvoiceCheckUsedCar> invoiceCheckUsedCars = new ArrayList<>();
        List<InvoiceCheckDetail> invoiceCheckDetailList = new ArrayList<>();
        // 先根据批次号批量查出我们的数据
        List<InvoiceCheck> myInvoiceCheckList = invoiceCheckMapper.selectInvoiceCheckByPchAndCompanyId(companyId, pch);
        // 再根据fpdm、fphm取出批次号不在这一批中的数据。这样去判断的时候，优先判断withoutPchInvCheckList然后没有的再去myInvoiceCheckList判断
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        //减少7天
        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) - 7);
        //Calendar转为Date类型
        Date date = cal.getTime();
        String nowDate = df.format(date);
        // List<InvoiceCheck> withoutPchInvCheckList = invoiceCheckMapper.selectInvoiceCheckByFpdmAndFphmWithouPch(myInvoiceCheckList, nowDate, companyId);
        List<Integer> invoiceIds = new ArrayList<>();
        for (Object tempInvoiceJson : invoiceJsonList) {
            JSONObject tempInvoiceJsonObj = (JSONObject) tempInvoiceJson;
            InvoiceCheck tempInvoiceCheck = new InvoiceCheck();
            tempInvoiceCheck.setCompany_id(companyId);
            tempInvoiceCheck.setPch(pch);
            // String jym = tempInvoiceJsonObj.getString("jym");
            // String fpje = tempInvoiceJsonObj.getString("fpje");
            String fpdm = tempInvoiceJsonObj.getString("fpdm");
            String kprq = tempInvoiceJsonObj.getString("kprq");
            String fphm = tempInvoiceJsonObj.getString("fphm");
            // String fpzl = tempInvoiceJsonObj.getString("fpzl");
            // 开始遍历寻找id

            // 2022.03.03 巩权林：这里有点问题，不应该查找不同批次号的内容；应该直接查同批次号的数据
            // FIXME 这里需要仔细考虑下扣费逻辑
            String checkResult = tempInvoiceJsonObj.getString("cyjg");
            if ("0001".equals(checkResult) || "0006".equals(checkResult) || "0009".equals(checkResult)) {
                // 如果需要扣费
                robUserMoney += 1;
            }
            Optional<InvoiceCheck> myInvoiceCheckOpt = myInvoiceCheckList.stream().filter(i -> {
                String myfpdm = i.getFpdm();
                String mykprq = i.getKprq();
                String myfphm = i.getFphm();
                // String myfpzl = i.getFpzl();
                //if (jym == myjym && fpje == myfpje && fpdm == myfpdm && kprq == mykprq && fphm == myfphm && fpzl == myfpzl) { // 大象返回的校验码是空的，醉了
                if (fpdm.equals(myfpdm) && kprq.equals(mykprq) && fphm.equals(myfphm)) {
                    return true;
                } else {
                    return false;
                }
            }).findFirst();
            InvoiceCheck myInvoiceCheck = myInvoiceCheckOpt.isPresent() ? myInvoiceCheckOpt.get() : null;
            // 如果不存在数据库，则跳过
            if (myInvoiceCheck != null) {
                // 数据已经有，判断下状态是否改变
                // myInvoiceCheck 数据库中的发票信息；tempInvoiceJsonObj 接口返回的发票信息
                // 首先得确定数据库中的发票是已经查过的，因此作废标志、查验结果均不能为Null
                String zfbz = myInvoiceCheck.getZfbz(); // 作废标志
                String cyjg = myInvoiceCheck.getCyjg(); // 查验结果
                if (zfbz != null && cyjg != null) { // 如果查询均不为null
                    String resultZfbz = tempInvoiceJsonObj.getString("zfbz"); // 接口返回的作废标志
                    String resultCyjg = tempInvoiceJsonObj.getString("cyjg"); // 接口返回的查验结果
                    // 必须保证这两个值不为空，那边才查验成功
                    if ((resultZfbz != null && !"".equals(resultZfbz)) && (resultCyjg != null && !"".equals(resultCyjg))) {
                        // 这时候再判断下要不要扣用户的钱
                        if (!resultZfbz.equals(zfbz)) { // 如果作废标志变了，说明已经冲红/作废了，扣钱；查验结果可能有多种，比如超时，不能作为判断依据。
                            robUserMoney += 1;
                        }
                    }
                }
            }
            // 下面这段注释是2022年3月3日之前的逻辑，因为可能会出现，同一张票多次查，会把最新的结果更新到以前的批次号上的问题
            /**
             // 先寻找withoutPchInvCheckList里的数据，如果为空，再去寻找myinvoiceCheckList，因为这样的话，就能先取到没有过期的数据
             Optional<InvoiceCheck> myInvoiceCheckOpt = withoutPchInvCheckList.stream().filter(i -> {
             // String myjym = i.getJym();
             // String myfpje = i.getFpje();
             String myfpdm = i.getFpdm();
             String mykprq = i.getKprq();
             String myfphm = i.getFphm();
             // String myfpzl = i.getFpzl(); // 大象不限制发票种类
             if (fpdm.equals(myfpdm) && kprq.equals(mykprq) && fphm.equals(myfphm)) {
             return true;
             } else {
             return false;
             }
             }).findFirst();
             InvoiceCheck myInvoiceCheck = myInvoiceCheckOpt.isPresent() ? myInvoiceCheckOpt.get() : null;
             // 如果没有取到未过期的数据，则去取批次号中的数据
             if (myInvoiceCheck == null) {
             // robUserMoney += 1; // 给用户扣钱
             // FIXME 这里需要仔细考虑下扣费逻辑
             String checkResult = tempInvoiceJsonObj.getString("cyjg");
             if ("0001".equals(checkResult) || "0006".equals(checkResult) || "0009".equals(checkResult)) {
             // 如果需要扣费
             robUserMoney += 1;
             }
             // 否则如果为空，再去寻找myInvoiceCheckList中的数据
             myInvoiceCheckOpt = myInvoiceCheckList.stream().filter(i -> {
             // String myjym = i.getJym();
             // String myfpje = i.getFpje();
             String myfpdm = i.getFpdm();
             String mykprq = i.getKprq();
             String myfphm = i.getFphm();
             // String myfpzl = i.getFpzl();
             //if (jym == myjym && fpje == myfpje && fpdm == myfpdm && kprq == mykprq && fphm == myfphm && fpzl == myfpzl) { // 大象返回的校验码是空的，醉了
             if (fpdm.equals(myfpdm) && kprq.equals(mykprq) && fphm.equals(myfphm)) {
             return true;
             } else {
             return false;
             }
             }).findFirst();
             myInvoiceCheck = myInvoiceCheckOpt.isPresent() ? myInvoiceCheckOpt.get() : null;
             // 如果不存在数据库，则跳过
             if (myInvoiceCheck == null) {
             continue;
             }
             } else {
             // 数据已经没有，判断下状态是否改变
             // myInvoiceCheck 数据库中的发票信息；tempInvoiceJsonObj 接口返回的发票信息
             // 首先得确定数据库中的发票是已经查过的，因此作废标志、查验结果均不能为Null
             String zfbz = myInvoiceCheck.getZfbz(); // 作废标志
             String cyjg = myInvoiceCheck.getCyjg(); // 查验结果
             if (zfbz != null && cyjg != null) { // 如果查询均不为null
             String resultZfbz = tempInvoiceJsonObj.getString("zfbz"); // 接口返回的作废标志
             String resultCyjg = tempInvoiceJsonObj.getString("cyjg"); // 接口返回的查验结果
             // 必须保证这两个值不为空，那边才查验成功
             if ((resultZfbz != null && !"".equals(resultZfbz)) && (resultCyjg != null && !"".equals(resultCyjg))) {
             // 这时候再判断下要不要扣用户的钱
             if (!resultZfbz.equals(zfbz)) { // 如果作废标志变了，说明已经冲红/作废了，扣钱；查验结果可能有多种，比如超时，不能作为判断依据。
             robUserMoney += 1;
             }
             }
             }
             }
             */

            // 更新id
            tempInvoiceCheck.setId(myInvoiceCheck.getId());
            tempInvoiceCheck = handelCheckResult(tempInvoiceCheck, tempInvoiceJsonObj);
            invoiceIds.add(myInvoiceCheck.getId());
            invoiceCheckList.add(tempInvoiceCheck);
            String fpzlInvoice = tempInvoiceCheck.getFpzl();
            // 根据发票种类进行分别插入
            // 货运运输业增值税专用发票：02
            if ("02".equals(fpzlInvoice)) {
                invoiceCheckFreights.add(tempInvoiceCheck.getInvoiceCheckFreight());
            }
            // 机动车销售统一发票：03
            if ("03".equals(fpzlInvoice)) {
                invoiceCheckCars.add(tempInvoiceCheck.getInvoiceCheckCar());
            }
            // 通行费发票：14
            if ("14".equals(fpzlInvoice)) {
                invoiceCheckTolls.add(tempInvoiceCheck.getInvoiceCheckToll());
            }
            // 二手车发票：15
            if ("15".equals(fpzlInvoice)) {
                invoiceCheckUsedCars.add(tempInvoiceCheck.getInvoiceCheckUsedCar());
            }
            List<InvoiceCheckDetail> tempInvoiceCheckDetail = tempInvoiceCheck.getInvoiceCheckDetail();
            if (tempInvoiceCheckDetail != null && tempInvoiceCheckDetail.size() > 0) {
                tempInvoiceCheckDetail.stream().forEach(i -> invoiceCheckDetailList.add(i));
            } else if (tempInvoiceCheckDetail == null) { // 如果tempInvoiceCheck为null，那么后面就会插入的时候报错
                tempInvoiceCheck.setInvoiceCheckDetail(tempInvoiceCheckDetail);
            }
        }


        // 开始批量更新数据
        // 先更新invoiceCheck
        try {
            log.info("结果列表：" + invoiceCheckList.toString());
            invoiceCheckMapper.updateInvoiceCheckBatch(invoiceCheckList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 再插入他们的子表们
        if (invoiceCheckCars != null && invoiceCheckCars.size() > 0) {
            invoiceCheckCarMapper.replaceBatch(invoiceCheckCars);
        }
        if (invoiceCheckFreights != null && invoiceCheckFreights.size() > 0) {
            invoiceCheckFreightMapper.replaceBatch(invoiceCheckFreights);
        }
        if (invoiceCheckTolls != null && invoiceCheckTolls.size() > 0) {
            invoiceCheckTollMapper.replaceBatch(invoiceCheckTolls);
        }
        if (invoiceCheckUsedCars != null && invoiceCheckUsedCars.size() > 0) {
            invoiceCheckUsedCarMapper.replaceBatch(invoiceCheckUsedCars);
        }
        if (invoiceIds.size() > 0) {
            invoiceCheckDetailMapper.batchDelete(invoiceIds);
        }
        if (invoiceCheckDetailList != null && invoiceCheckDetailList.size() > 0) {
            invoiceCheckDetailMapper.batchInsert(invoiceCheckDetailList);
        }
        // 这他妈写的什么鸡巴代码
        // List<FileMatchPch> fileMatchPch = batchcheckfilesMapper.selectFileIdByPch(pch);
        // for (int i = 0; i < invoiceCheckList.size(); i++) {
        //     BatchUncheck uncheck = new BatchUncheck();
        //     InvoiceCheck invoiceCheck = invoiceCheckList.get(i);
        //     if (invoiceCheck.getCycs() == null || "".equals(invoiceCheck.getCycs())) {
        //         invoiceCheck.setCycs("1");
        //     }
        //     uncheck.setCycs(Long.parseLong(invoiceCheck.getCycs()));
        //     uncheck.setLasttime(new Date());
        //     uncheck.setCheckresult(invoiceCheck.getCyjgxx());
        //     uncheck.setInvoicecheckid(String.valueOf(invoiceCheck.getId()));
        //     uncheck.setFpdm(invoiceCheck.getFpdm());
        //     uncheck.setFphm(invoiceCheck.getFphm());
        //     if (fileMatchPch.size() > 0) {
        //         uncheck.setFileid(fileMatchPch.get(0).getFileid());
        //     }
        //     batchUncheckMapper.updateBatchUncheckByFphmFpdm(uncheck);
        // }

        JSONObject resultObj = new JSONObject();
        resultObj.put("robUserMoney", robUserMoney);
        return AjaxResult.success(resultObj);
    }

    /**
     * 插入invoice
     *
     * @param companyId
     * @param data
     * @return
     */
    public AjaxResult insertInvoice(String companyId, JSONObject data) {
        String jym = "";
        String fpje = "";
        String fpdm = "";
        String kprq = "";
        String fphm = "";
        String fpzl = "";
        jym = (String) data.get("jym");
        if (jym != null && jym.length() >= 6) {
            jym = jym.substring(jym.length() - 6, jym.length());
        }
        fpzl = (String) data.get("fpzl");
        String[] fpzlList = {"01", "02", "03", "04", "10", "11", "14", "15", "08", "21", "22","61","83"};
        if (!Arrays.asList(fpzlList).contains(fpzl)) { // 如果不存发票种类，则挂掉
            return AjaxResult.error(1025, "发票种类非法！");
        }
        fpje = (String) data.get("fpje");
        fpdm = (String) data.get("fpdm");
        if (StringUtils.isNotEmpty(fpdm) && StringUtils.equalsAny(fpzl, "21", "22")) {
            fpdm = "";
        }
        kprq = (String) data.get("kprq");
        fphm = (String) data.get("fphm");

        // 现在用大象的发票种类，诺诺的不全
        //fpzl = FpzlCoverUtil.eleToNuonuo(fpzl);

        // 保存invoiceCheck
        InvoiceCheck invoiceCheck = new InvoiceCheck();
        invoiceCheck.setCompany_id(companyId);
        invoiceCheck.setJym(jym);
        invoiceCheck.setFpje(fpje);
        invoiceCheck.setFpdm(fpdm);
        invoiceCheck.setKprq(kprq);
        invoiceCheck.setFphm(fphm);
        invoiceCheck.setFpzl(fpzl);
        invoiceCheckMapper.insertInvoice(invoiceCheck);

        return AjaxResult.success(invoiceCheck);
    }

    /**
     * 将大象返回的invoiceCheck进行处理
     *
     * @param invoiceCheck
     * @return
     */
    public static InvoiceCheck handelCheckResult(InvoiceCheck invoiceCheck, JSONObject resultContent) {
        // 先处理invoi_date表
        invoiceCheck.setCyjg(resultContent.getString("cyjg"));
        invoiceCheck.setCyjgxx(resultContent.getString("cyjgxx"));
        invoiceCheck.setFpzl(resultContent.getString("fpzl"));
        invoiceCheck.setFpdm(resultContent.getString("fpdm"));
        invoiceCheck.setFphm(resultContent.getString("fphm"));
        invoiceCheck.setCycs(resultContent.getString("cycs"));
        invoiceCheck.setXhfmc(resultContent.getString("xhfmc"));
        invoiceCheck.setXhfsbh(resultContent.getString("xhfsbh"));
        invoiceCheck.setXhfdzdh(resultContent.getString("xhfdzdh"));
        invoiceCheck.setXhfyhzh(resultContent.getString("xhfyhzh"));
        invoiceCheck.setGmfsbh(resultContent.getString("gmfsbh"));
        invoiceCheck.setGmfmc(resultContent.getString("gmfmc"));
        invoiceCheck.setGmfdzdh(resultContent.getString("gmfdzdh"));
        invoiceCheck.setGmfyhzh(resultContent.getString("gmfyhzh"));
        invoiceCheck.setKprq(resultContent.getString("kprq"));
        invoiceCheck.setFpje(resultContent.getString("fpje"));
        invoiceCheck.setFpse(resultContent.getString("fpse"));
        invoiceCheck.setJshj(resultContent.getString("jshj"));
        invoiceCheck.setBz(resultContent.getString("bz"));
        invoiceCheck.setJqbh(resultContent.getString("jqbh"));
        invoiceCheck.setKpr(resultContent.getString("kpr"));
        invoiceCheck.setSkr(resultContent.getString("skr"));
        invoiceCheck.setFhr(resultContent.getString("fhr"));
        String jym = resultContent.getString("jym");
        if (jym != null && jym.length() >= 6) {
            jym = jym.substring(jym.length() - 6, jym.length());
        }
        invoiceCheck.setJym(jym);
        invoiceCheck.setZfbz(resultContent.getString("zfbz"));
        invoiceCheck.setStatus("1");

        // 2022.09.16 浪潮新增需求，新增销货方地址电话拆分为两个字段
        String xhfdzdh = invoiceCheck.getXhfdzdh();
        if (StringUtils.isNotEmpty(xhfdzdh)) {
            String dh = InvoiceUtils.getPhoneNew(xhfdzdh);
            if (StringUtils.isNotEmpty(dh)) {
                invoiceCheck.setXhfdz(xhfdzdh.replace(dh, ""));
                invoiceCheck.setXhfdh(dh);
            }
        }

        // 处理机动车子类
        InvoiceCheckCar invoiceCheckCar = new InvoiceCheckCar();
        invoiceCheckCar.setInvoice_check_id(invoiceCheck.getId());
        invoiceCheckCar.setSfzh(resultContent.getString("sfzh"));
        invoiceCheckCar.setCllx(resultContent.getString("cllx"));
        invoiceCheckCar.setCpxh(resultContent.getString("cpxh"));
        invoiceCheckCar.setCd(resultContent.getString("cd"));
        invoiceCheckCar.setHgzs(resultContent.getString("hgzs"));
        invoiceCheckCar.setSjdh(resultContent.getString("sjdh"));
        invoiceCheckCar.setFdjhm(resultContent.getString("fdjhm"));
        invoiceCheckCar.setClsbh(resultContent.getString("clsbh"));
        invoiceCheckCar.setJszmsh(resultContent.getString("jszmsh"));
        invoiceCheckCar.setZgswjgdm(resultContent.getString("zgswjgdm"));
        invoiceCheckCar.setWspzhm(resultContent.getString("wspzhm"));
        invoiceCheckCar.setXcrs(resultContent.getString("xcrs"));
        invoiceCheckCar.setZgswjgmc(resultContent.getString("zgswjgmc"));
        invoiceCheckCar.setDw(resultContent.getString("dw"));
        invoiceCheckCar.setSl(resultContent.getString("sl"));
        invoiceCheckCar.setKhyh(resultContent.getString("khyh"));
        invoiceCheckCar.setKhzh(resultContent.getString("khzh"));
        invoiceCheckCar.setSmfdh(resultContent.getString("smfdh"));

        // 处理货运子类
        InvoiceCheckFreight invoiceCheckFreight = new InvoiceCheckFreight();
        invoiceCheckFreight.setInvoice_check_id(invoiceCheck.getId());
        invoiceCheckFreight.setCyrmc(resultContent.getString("cyrmc"));
        invoiceCheckFreight.setCyrsbh(resultContent.getString("cyrsbh"));
        invoiceCheckFreight.setSpfmc(resultContent.getString("spfmc"));
        invoiceCheckFreight.setSpfsbh(resultContent.getString("spfsbh"));
        invoiceCheckFreight.setShrmc(resultContent.getString("shrmc"));
        invoiceCheckFreight.setShrsbh(resultContent.getString("shrsbh"));
        invoiceCheckFreight.setFhrmc(resultContent.getString("fhrmc"));
        invoiceCheckFreight.setFhrsbh(resultContent.getString("fhrsbh"));
        invoiceCheckFreight.setYsgwxx(resultContent.getString("ysgwxx"));
        invoiceCheckFreight.setQydjyddd(resultContent.getString("qydjyddd"));
        invoiceCheckFreight.setSkph(resultContent.getString("skph"));
        invoiceCheckFreight.setCzch(resultContent.getString("czch"));
        invoiceCheckFreight.setCcdw(resultContent.getString("ccdw"));

        // 处理通行费子类
        InvoiceCheckToll invoiceCheckToll = new InvoiceCheckToll();
        invoiceCheckToll.setInvoice_check_id(invoiceCheck.getId());
        invoiceCheckToll.setTxfbz(resultContent.getString("txfbz"));
        invoiceCheckToll.setLslbs(resultContent.getString("lslbs"));

        // 处理二手车子类
        InvoiceCheckUsedCar invoiceCheckUsedCar = new InvoiceCheckUsedCar();
        invoiceCheckUsedCar.setInvoice_check_id(invoiceCheck.getId());
        invoiceCheckUsedCar.setCpzh(resultContent.getString("cpzh"));
        invoiceCheckUsedCar.setDjzh(resultContent.getString("djzh"));
        invoiceCheckUsedCar.setCjhj(resultContent.getString("cjhj"));
        invoiceCheckUsedCar.setZrdcgsmc(resultContent.getString("zrdcgsmc"));
        invoiceCheckUsedCar.setMfdwgr(resultContent.getString("mfdwgr"));
        invoiceCheckUsedCar.setMfdwdmsfzh(resultContent.getString("mfdwdmsfzh"));
        invoiceCheckUsedCar.setMfdwgrdz(resultContent.getString("mfdwgrdz"));
        invoiceCheckUsedCar.setMfdh(resultContent.getString("mfdh"));
        invoiceCheckUsedCar.setSmfdwgr(resultContent.getString("smfdwgr"));
        invoiceCheckUsedCar.setSmfdwdmsfzh(resultContent.getString("smfdwdmsfzh"));
        invoiceCheckUsedCar.setSmfdwgrzz(resultContent.getString("smfdwgrzz"));
        invoiceCheckUsedCar.setSmfdh(resultContent.getString("smfdh"));
        invoiceCheckUsedCar.setJypmdw(resultContent.getString("jypmdw"));
        invoiceCheckUsedCar.setJypmdwdz(resultContent.getString("jypmdwdz"));
        invoiceCheckUsedCar.setJypmdwzsbh(resultContent.getString("jypmdwzsbh"));
        invoiceCheckUsedCar.setKhyhjzh(resultContent.getString("khyhjzh"));
        invoiceCheckUsedCar.setJypmdwdh(resultContent.getString("jypmdwdh"));
        invoiceCheckUsedCar.setEscsc(resultContent.getString("escsc"));
        invoiceCheckUsedCar.setEscscsbh(resultContent.getString("escscsbh"));
        invoiceCheckUsedCar.setEscscdz(resultContent.getString("escscdz"));
        invoiceCheckUsedCar.setEscsckhyhzh(resultContent.getString("escsckhyhzh"));
        invoiceCheckUsedCar.setEscscdh(resultContent.getString("escscdh"));
        invoiceCheckUsedCar.setClsbh(resultContent.getString("clsbh"));
        invoiceCheckUsedCar.setCllx(resultContent.getString("cllx"));
        invoiceCheckUsedCar.setCpxh(resultContent.getString("cpxh"));

        // 处理电子发票（航空运输电子客票行程单）
        InvoiceCheckHangkong hangkong = BeanUtil.copyProperties(JSONUtil.parse(resultContent),InvoiceCheckHangkong.class);

        // 处理电子发票（铁路电子客票）
        InvoiceCheckTielu tielu = BeanUtil.copyProperties(JSONUtil.parse(resultContent),InvoiceCheckTielu.class);

        // 获取详情子类
        int invoiceId = invoiceCheck.getId();
        JSONArray detailsJsonArray = resultContent.getJSONArray("detailList");
        List<InvoiceCheckDetail> detailList = new ArrayList<>();
        if (detailsJsonArray != null) {
            for (Object detail : detailsJsonArray) {
                InvoiceCheckDetail tempDetail = new InvoiceCheckDetail();
                JSONObject detailData = (JSONObject) detail;
                tempDetail.setInvoice_check_id(invoiceId);
                tempDetail.setMxbh(detailData.getString("mxbh"));
                tempDetail.setHwmc(detailData.getString("hwmc"));
                tempDetail.setJe(detailData.getString("je"));
                tempDetail.setSpsl(detailData.getString("spsl"));
                tempDetail.setSl(detailData.getString("sl"));
                tempDetail.setSe(detailData.getString("se"));
                tempDetail.setHsdj(detailData.getString("hsdj"));
                tempDetail.setHsje(detailData.getString("hsje"));
                tempDetail.setBhsdj(detailData.getString("bhsdj"));
                tempDetail.setGgxh(detailData.getString("ggxh"));
                tempDetail.setJldw(detailData.getString("jldw"));
                tempDetail.setFyxm(detailData.getString("fyxm"));
                tempDetail.setCph(detailData.getString("cph"));
                tempDetail.setLx(detailData.getString("lx"));
                tempDetail.setTxrqq(detailData.getString("txrqq"));
                tempDetail.setTxrqz(detailData.getString("txrqz"));


                // 处理电子发票（航空运输电子客票行程单）
                // 处理电子发票（铁路电子客票）
                BeanUtil.copyProperties(detailData,tempDetail);


                detailList.add(tempDetail);
            }
        }

        // 开始归类
        if (invoiceCheckCar != null) {
            invoiceCheck.setInvoiceCheckCar(invoiceCheckCar);
        }
        if (invoiceCheckFreight != null) {
            invoiceCheck.setInvoiceCheckFreight(invoiceCheckFreight);
        }
        if (invoiceCheckToll != null) {
            invoiceCheck.setInvoiceCheckToll(invoiceCheckToll);
        }
        if (invoiceCheckUsedCar != null) {
            invoiceCheck.setInvoiceCheckUsedCar(invoiceCheckUsedCar);
        }
        if (hangkong != null) {
            invoiceCheck.setInvoiceCheckHangkong(hangkong);
        }
        if (tielu != null) {
            invoiceCheck.setInvoiceCheckTielu(tielu);
        }
        if (detailList != null && detailList.size() > 0) {
            invoiceCheck.setInvoiceCheckDetail(detailList);
        }

        return invoiceCheck;
    }

    /**
     * 批量插入invoiceCheck及其关联表
     *
     * @return
     */
    public AjaxResult insertInvoice(InvoiceCheck invoiceCheck) {
        // 更新invoice_check
        try {
            log.info("查验结果=" + invoiceCheck.toString());
            invoiceCheckMapper.updateInoviceById(invoiceCheck);
            String fpzl = invoiceCheck.getFpzl();
            // 根据发票种类进行分别插入
            // 货运运输业增值税专用发票：02
            if ("02".equals(fpzl)) {
                invoiceCheckFreightMapper.insertData(invoiceCheck.getInvoiceCheckFreight());
            }
            // 机动车销售统一发票：03
            if ("03".equals(fpzl)) {
                invoiceCheckCarMapper.insertData(invoiceCheck.getInvoiceCheckCar());
            }
            // 通行费发票：14
            if ("14".equals(fpzl)) {
                invoiceCheckTollMapper.insertData(invoiceCheck.getInvoiceCheckToll());
            }
            // 二手车发票：15
            log.info("二手车发票：15");
            if ("15".equals(fpzl)) {
                invoiceCheckUsedCarMapper.insertData(invoiceCheck.getInvoiceCheckUsedCar());
            }

            List<InvoiceCheckDetail> detailLists = invoiceCheck.getInvoiceCheckDetail();
            if (detailLists != null && !detailLists.isEmpty()) {
                log.info("如果detaillist存在，先删除一下");
                // 如果detaillist存在，先删除一下。因为如果插入一个数据，会出现detail重复的问题
                invoiceCheckDetailMapper.delete(invoiceCheck.getId());
                invoiceCheckDetailMapper.batchInsert(invoiceCheck.getInvoiceCheckDetail());
            }
            log.info("invoiceCheck.setCycs");
            // 注释狗屎代码
            // BatchUncheck uncheck = new BatchUncheck();
            // if (invoiceCheck.getCycs() == null || "".equals(invoiceCheck.getCycs())) {
            //     log.info("cycs为空");
            //     invoiceCheck.setCycs("1");
            // }
            // uncheck.setCycs(Long.parseLong(invoiceCheck.getCycs()));
            // uncheck.setLasttime(new Date());
            // uncheck.setCheckresult(invoiceCheck.getCyjgxx());
            // uncheck.setInvoicecheckid(String.valueOf(invoiceCheck.getId()));
            // uncheck.setFpdm(invoiceCheck.getFpdm());
            // uncheck.setFphm(invoiceCheck.getFphm());
            // batchUncheckMapper.updateBatchUncheckByFphmFpdm(uncheck);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 校验invoice_check字段是否齐全
     *
     * @return
     */
    private AjaxResult validateInvoiceCheck(JSONObject data) {
        if ((String) data.get("fpzl") == null) {
            return AjaxResult.error("发票种类不能为空！");
        }
        String fpzl = (String) data.get("fpzl");
        if (
                "01".equals(fpzl) || // 增值税专用发票
                        "02".equals(fpzl) || // 货运运输业增值税专用发票：02
                        "03".equals(fpzl) || // 机动车销售统一发票：03
                        "15".equals(fpzl) || // 二手车发票：15
                        "08".equals(fpzl) || // 增值税电子专用发票：08
                        "61".equals(fpzl) || // 电子发票（航空运输电子客票行程单）：61
                        "83".equals(fpzl) // 电子发票（铁路电子客票）：08
        ) {
            if ((String) data.get("fpje") == null) {
                return AjaxResult.error("不含税金额不能为空！");
            }
        }
        if ((String) data.get("fpdm") == null) {
            return AjaxResult.error("发票代码不能为空！");
        }
        if ((String) data.get("kprq") == null) {
            return AjaxResult.error("开票日期不能为空！");
        }
        if ((String) data.get("fphm") == null) {
            return AjaxResult.error("发票号码不能为空！");
        }
        if (
                "04".equals(fpzl) || // 增值税普通发票
                        "10".equals(fpzl) || // 增值税普通发票（电子）
                        "11".equals(fpzl) || //  增值税普通发票（卷式）
                        "14".equals(fpzl)    // 通行费发票
        ) {
            if ((String) data.get("jym") == null) {
                return AjaxResult.error("发票校验码不能为空！");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询invoiceCheck并处理相关实例
     *
     * @param companyId
     * @param data
     * @return
     */
    private AjaxResult handleSelectedInvoiceCheck(String companyId, JSONObject data) {
        String fpdm = data.getString("fpdm");
        String fphm = data.getString("fphm");
        InvoiceCheck tempInvoiceCheck = invoiceCheckMapper.selectInvoiceCheckByFpdmAndFphm(companyId, fpdm, fphm);
        if (tempInvoiceCheck == null) { // 如果没有查到，就返回空
            return AjaxResult.error();
        }
        InvoiceCheckFreight invoiceCheckFreight = invoiceCheckFreightMapper.selectOne(tempInvoiceCheck.getId());
        InvoiceCheckCar invoiceCheckCar = invoiceCheckCarMapper.selectOne(tempInvoiceCheck.getId());
        InvoiceCheckToll invoiceCheckToll = invoiceCheckTollMapper.selectOne(tempInvoiceCheck.getId());
        InvoiceCheckUsedCar invoiceCheckUsedCar = invoiceCheckUsedCarMapper.selectOne(tempInvoiceCheck.getId());
        List<InvoiceCheckDetail> invoiceCheckDetail = invoiceCheckDetailMapper.select(tempInvoiceCheck.getId());
        // 开始合并
        // 先都转为jsonobject
        JSONObject invoiceCheckJson = (JSONObject) JSONObject.toJSON(tempInvoiceCheck);
        JSONObject invoiceCheckFreightJson = (JSONObject) JSONObject.toJSON(invoiceCheckFreight);
        JSONObject invoiceCheckCarJson = (JSONObject) JSONObject.toJSON(invoiceCheckCar);
        JSONObject invoiceCheckTollJson = (JSONObject) JSONObject.toJSON(invoiceCheckToll);
        JSONObject invoiceCheckUsedCarJson = (JSONObject) JSONObject.toJSON(invoiceCheckUsedCar);

        if (invoiceCheckFreightJson != null) {
            Set<String> invoiceCheckFreightKeySet = invoiceCheckFreightJson.keySet();
            for (String key : invoiceCheckFreightKeySet) {
                if ("invoice_check_id".equals(key)) {
                    continue;
                }
                invoiceCheckJson.put(key, invoiceCheckFreightJson.getString(key));
            }
        }

        if (invoiceCheckCarJson != null) {
            Set<String> invoiceCheckCarJsonKeySet = invoiceCheckCarJson.keySet();
            for (String key : invoiceCheckCarJsonKeySet) {
                if ("invoice_check_id".equals(key)) {
                    continue;
                }
                invoiceCheckJson.put(key, invoiceCheckCarJson.getString(key));
            }

        }

        if (invoiceCheckTollJson != null) {
            Set<String> invoiceCheckTollJsonKeySet = invoiceCheckTollJson.keySet();
            for (String key : invoiceCheckTollJsonKeySet) {
                if ("invoice_check_id".equals(key)) {
                    continue;
                }
                invoiceCheckJson.put(key, invoiceCheckTollJson.getString(key));
            }

        }

        if (invoiceCheckUsedCarJson != null) {
            Set<String> invoiceCheckUsedCarJsonKeySet = invoiceCheckUsedCarJson.keySet();
            for (String key : invoiceCheckUsedCarJsonKeySet) {
                if ("invoice_check_id".equals(key)) {
                    continue;
                }
                invoiceCheckJson.put(key, invoiceCheckUsedCarJson.getString(key));
            }

        }

        JSONObject returnJson = new JSONObject();
        Set<String> invoiceCheckJsonKeySet = invoiceCheckJson.keySet();
        String[] tempKeys = {"id", "company_id", "created_at", "status", "invoiceCheckCar", "invoiceCheckDetail", "invoiceCheckFreight", "invoiceCheckToll", "invoiceCheckUsedCar"};
        List<String> tempKeyArrays = Arrays.asList(tempKeys);
        for (String key : invoiceCheckJsonKeySet) {
            if (tempKeyArrays.contains(key)) {
                continue;
            }
            String tempString = invoiceCheckJson.getString(key);
            tempString = tempString != null ? tempString : "";
            returnJson.put(key, tempString);
        }


        // 开始处理detail
        JSONArray detailJson = JSONObject.parseArray(JSONObject.toJSONString(invoiceCheckDetail));
        returnJson.put("detailList", detailJson);

        return AjaxResult.success(returnJson);
    }


}
