package com.jkcredit.invoice.credit.interserver;

import cn.com.taiji.sdk.model.comm.protocol.tts.vehicle.VehicleQueryResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jkcredit.invoice.common.DataResult;
import com.jkcredit.invoice.mapper.binvoce.BillInvoiceMapper;
import com.jkcredit.invoice.mapper.customer.CustomerCarRecMapper;
import com.jkcredit.invoice.mapper.customer.CustomerMapper;
import com.jkcredit.invoice.mapper.waybill.NoCarWaybillMapper;
import com.jkcredit.invoice.model.entity.customer.Customer;
import com.jkcredit.invoice.model.entity.customer.CustomerCarRec;
import com.jkcredit.invoice.model.entity.customer.CustomerRec;
import com.jkcredit.invoice.model.entity.invoice.BillInvoice;
import com.jkcredit.invoice.model.entity.manager.Param;
import com.jkcredit.invoice.model.entity.waybill.NoCarCompanyManger;
import com.jkcredit.invoice.model.entity.waybill.NoCarWayBill;
import com.jkcredit.invoice.model.entity.waybill.NoCarWayBillFileInfo;
import com.jkcredit.invoice.model.vo.OperatorEditConfirmVo;
import com.jkcredit.invoice.model.vo.OperatorEditVo;
import com.jkcredit.invoice.model.vo.OperatorEvidenceVo;
import com.jkcredit.invoice.model.vo.OperatorSendCodeVo;
import com.jkcredit.invoice.service.customer.CustomerRecService;
import com.jkcredit.invoice.service.lowerservice.NoCarService;
import com.jkcredit.invoice.service.lowerservice.vo.HcInvoiceQueryVo;
import com.jkcredit.invoice.service.manager.ParamService;
import com.jkcredit.invoice.service.nocar.NoCarBillWayImportService;
import com.jkcredit.invoice.service.nocar.NoCarCompanyMangerOper;
import com.jkcredit.invoice.service.nocar.WayBillFileService;
import com.jkcredit.invoice.util.DateUtil;
import com.jkcredit.invoice.util.RespR;
import com.jkcredit.invoice.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.jkcredit.invoice.common.CommonConst.COMPUTE;
import static com.jkcredit.invoice.common.CommonConst.NOT_FOUND;
import static com.jkcredit.invoice.common.CommonConst.ONE;
import static com.jkcredit.invoice.common.CommonConst.REC_STATUS_UN;
import static com.jkcredit.invoice.common.CommonConst.REC_STATUS_WAIT;
import static com.jkcredit.invoice.common.CommonConst.RESULT;
import static com.jkcredit.invoice.common.CommonConst.SELF_CAR;
import static com.jkcredit.invoice.common.CommonConst.XY_WAYBILL_HISTORY_END;
import static java.util.stream.Collectors.toList;

/**
 * 无车操作接口实现类
 * @author mumuxigua
 */
@Service("noCarInterService")
@Slf4j
public class NoCarInterServiceImpl implements NoCarInterService {

    private static final String PDF = "pdf";


    @Autowired
    NoCarBillWayImportService noCarWaybillMapperImprt;
    @Autowired
    CustomerCarRecMapper customerCarRecMapper;
    @Autowired
    NoCarWaybillMapper noCarWaybillMapper;
    @Autowired
    CustomerRecService customerRecMapper;
    @Autowired
    BillInvoiceMapper billInvoiceMapper;
    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    ParamService paramService;
    @Autowired
    private NoCarService noCarService;
    @Autowired
    private WayBillFileService wayBillFileService;

    public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        list1.add("1");
        list1.add("2");
        list1.add("3");
        list1.add("5");
        list1.add("6");

        List<String> list2 = new ArrayList<String>();
        list2.add("2");
        list2.add("3");
        list2.add("7");
        list2.add("8");

        // 交集
        List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
        System.out.println("---交集 intersection---");
        intersection.parallelStream().forEach(System.out::println);

        // 差集 (list1 - list2)
        List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
        System.out.println("---差集 reduce1 (list1 - list2)---");
        // 并集
        reduce1.parallelStream().forEach(System.out::println);
        List<String> listAll = list1.parallelStream().collect(toList());
        List<String> listAll2 = list2.parallelStream().collect(toList());
        listAll.addAll(listAll2);
        System.out.println("---并集 listAll---");
        listAll.parallelStream().forEachOrdered(System.out::println);

        // 去重并集
        List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
        System.out.println("---得到去重并集 listAllDistinct---");
        listAllDistinct.parallelStream().forEachOrdered(System.out::println);

        System.out.println("---原来的List1---");
        list1.parallelStream().forEachOrdered(System.out::println);
        System.out.println("---原来的List2---");
        list2.parallelStream().forEachOrdered(System.out::println);

    }

    /**
     * 无车 车辆备案接口
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult customerCarRec(String appKey, String api, String data, String requestid) {

        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-NoCarInterServiceImpl.customerCarRec-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //企业名称 选输
            String companyName = jsonObject.getString("companyName");
            //plateNumber 必输
            String plateNumber = jsonObject.getString("plateNumber");
            //plateColor 必输
            String plateColor = jsonObject.getString("plateColor");
            if (StringUtils.isEmpty(data) || null == jsonObject || StringUtils.isEmpty(plateNumber)
                    || StringUtils.isEmpty(plateColor)

            ) {
                result.setMsg("必传参数有空值");
                return result;
            }


            List<CustomerCarRec> customerCarRecList = new ArrayList<CustomerCarRec>();
            CustomerCarRec customerCarRec = new CustomerCarRec();
            customerCarRec.setCustomerName(appKey);
            Customer cust = customerMapper.selectByCustomerName(appKey);

            CustomerRec customerRec = new CustomerRec();
            customerRec.setCustomerName(appKey);
            customerRec.setCompanyName(cust.getCompany());
            CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompany(customerRec);
            if (null == customerRec1) {
                result.setMsg("该客户: " + appKey + " 未备案企业");
                return result;
            }
            customerCarRec.setCompanyName(customerRec1.getCompanyName());
            customerCarRec.setCustomerName(customerRec1.getCustomerName());
            //无车
            customerCarRec.setBusinessType("2");
            customerCarRec.setCarColor(plateColor);
            customerCarRec.setCarNum(plateNumber);
            customerCarRec.setInterType(0);
            if (SELF_CAR.equals(customerCarRec.getCarColor())) {
                //默认运营车辆
                customerCarRec.setServiceOperation(1);
            }

            customerCarRecList.add(customerCarRec);

            return getDataResultss(data, costtimestart, result, noCarService.customerCarRec(customerCarRecList), "[-NoCarInterServiceImpl.customerCarRec-] result is ");
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.customerCarRec-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    /**
     * 无车 车辆备案查询接口
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult customeRecUpperQuery(String appKey, String api, String data, String requestid) {

        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-NoCarInterServiceImpl.customeRecUpperQuery-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //备案来源 选输
            String waybillSource = jsonObject.getString("waybillSource");
            //plateNumber 必输
            String plateNumber = jsonObject.getString("plateNumber");
            //plateColor 必输
            String plateColor = jsonObject.getString("plateColor");
            if (StringUtils.isEmpty(data) || null == jsonObject || StringUtils.isEmpty(plateNumber)
                    || StringUtils.isEmpty(plateColor)

            ) {
                result.setMsg("必传参数有空值");
                return result;
            }


            CustomerCarRec customerCarRec = new CustomerCarRec();
            Param param = paramService.getParamsByParamName("REQUEST_COMPANY_NUM");
            //无车，车辆备案，运单上传，运单查询都是统一用交科的企业编号;自有车用客户的企业编号
            customerCarRec.setCompanyNum(param.getParamValue());
            customerCarRec.setCarColor(plateColor);
            customerCarRec.setCarNum(plateNumber);
            customerCarRec.setCustomerName(appKey);
            //无车
            customerCarRec.setBusinessType("2");
            //此处代表仅查询上游接口，无任何处理逻辑
            customerCarRec.setInterType(8);

            RespR rs = noCarService.customerCarRecQueryUpper(customerCarRec);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.customeRecUpperQuery-] result is "
                    + rs.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != rs && rs.getCode() == 0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg(rs.getData().toString());
                JSONObject jb = JSONObject.parseObject(rs.getData().toString());
                result.setData(1);
                result.setMsg("车辆已备案");
                if (null == jb.getJSONArray(RESULT) || jb.getJSONArray(RESULT).size() == 0) {
                    result.setData(2);
                    result.setMsg("车辆未备案");
                }
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg("查询失败");
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.customeRecUpperQuery-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    /**
     * 无车 实时运单开始指令接口
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult noCarBillStart(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();
        DataResult result = new DataResult();
        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");
        try {
            log.info("[-NoCarInterServiceImpl.noCarBillStart-] request appKey=" + appKey + " ,api=" + api + " ,data=" + StringUtil.removeJSonField(data,"base64Str") + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //运单编号 必选
            String num = jsonObject.getString("num");
            //车牌号 必选
            String plateNumber = jsonObject.getString("plateNumber");
            //车牌颜色 必选
            String plateColor = jsonObject.getString("plateColor");
            //运单开始时间 必选
            String startTime = jsonObject.getString("startTime");
            //运单开始地址 必选
            String sourceAddr = jsonObject.getString("sourceAddr");
            //运单目的地址 必选
            String destAddr = jsonObject.getString("destAddr");
            //运单预计完成时间 必选
            String predictEndTime = jsonObject.getString("predictEndTime");
            //运单费用 必选
            Integer fee = jsonObject.getInteger("fee");
            //发票抬头类型 必选
            Integer titleType = jsonObject.getInteger("titleType");
            //税号 必选
            String taxplayerCode = jsonObject.getString("taxplayerCode");
             //base流文件 必选
            String base64Str = jsonObject.getString("base64Str");
            //运单协议名称 必选
            String waybillFileName = jsonObject.getString("waybillFileName");
            //运单类型 必选
            Integer contractType = jsonObject.getInteger("contractType");

            if (StringUtils.isEmpty(data) || null == jsonObject
                    || StringUtils.isEmpty(num)
                    || StringUtils.isEmpty(plateNumber)
                    || StringUtils.isEmpty(plateColor)
                    || StringUtils.isEmpty(startTime)
                    || StringUtils.isEmpty(sourceAddr)
                    || StringUtils.isEmpty(destAddr)
                    || StringUtils.isEmpty(predictEndTime)
                    || null == fee
                    || null == titleType
                    || StringUtils.isEmpty(taxplayerCode)
                    || StringUtils.isEmpty(base64Str)
                    || StringUtils.isEmpty(waybillFileName)
                    || null == contractType

            ) {
                result.setMsg("必传参数有空值");
                return result;
            }
            if (!DateUtil.isValidDate(startTime)) {
                result.setMsg("日期格式有误");
                return result;
            }
            if (!DateUtil.isValidDate(predictEndTime)) {
                result.setMsg("日期格式有误");
                return result;
            }

            if(StringUtils.isNotBlank(waybillFileName) && StringUtils.isNotBlank(base64Str) && null != contractType){
                String fileType = waybillFileName.substring(waybillFileName.lastIndexOf(".") + 1).toLowerCase();
                if (!PDF.equals(fileType)) {
                    result.setMsg("必须是pdf文件!");
                    return result;
                }
                int base64StrLength = base64Str.length();
                if (COMPUTE < base64StrLength) {
                    result.setMsg("pdf不可超过10M!");
                    return result;
                }
                base64Str = base64Str.replaceAll(" ", "+");
            }


            CustomerRec customerRec = new CustomerRec();
            customerRec.setCustomerName(appKey);
            customerRec.setCompanyReferencenum(taxplayerCode);
            customerRec = customerRecMapper.selectByCustomerNameAndCompanyReference(customerRec);
            if (customerRec == null || customerRec.getRecStatus() != 1) {
                result.setMsg("客户：" + appKey + ";税号" + taxplayerCode + "未在平台备案成功，请先做备案");
                return result;
            }
            NoCarWayBill noCarWayBill = getNoCarWayBill(appKey, num, plateNumber, plateColor, startTime, sourceAddr, destAddr, predictEndTime, fee, titleType, taxplayerCode, customerRec);
            noCarWayBill.setWaybillFileName(waybillFileName);
            noCarWayBill.setBase64Str(base64Str);
            noCarWayBill.setContractType(contractType);
           DataResult dataResult = getDataResult(appKey, data, costtimestart, result, customerRec, noCarWayBill);
            try {
                if(dataResult.getData() == 1 && dataResult.getCode()==200 && StringUtils.isNotBlank(waybillFileName) && StringUtils.isNotBlank(base64Str)){
                    NoCarWayBillFileInfo noCarWayBillFileInfo = new NoCarWayBillFileInfo();
                    noCarWayBillFileInfo.setBase64Str(base64Str);
                    noCarWayBillFileInfo.setFileName(waybillFileName);
                    noCarWayBillFileInfo.setBatchNum("接口运单");
                    noCarWayBillFileInfo.setWayBillNum(num);
                    noCarWayBillFileInfo.setCustomerId(appKey);
                    noCarWayBillFileInfo.setCompanyName(noCarWayBill.getCompanyName());
                    noCarWayBillFileInfo.setUpdateTime(DateUtil.getCurrentDateStr());
                    wayBillFileService.insert(noCarWayBillFileInfo);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.info("文件入表失败{}",noCarWayBill.getBillNum());
            }

            return dataResult;
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.noCarBillStart-] get httpclient exception is "
                    + e + ", request is " + StringUtil.removeJSonField(data,"base64Str"));
        }
        return result;
    }

    private DataResult getDataResult(String appKey, String data, long costtimestart, DataResult result, CustomerRec customerRec, NoCarWayBill noCarWayBill) {
        List<CustomerCarRec> customerCarRecs = new ArrayList<>();
        CustomerCarRec customerCarRec = new CustomerCarRec();
        customerCarRec.setCompanyName(noCarWayBill.getCompanyName());
        customerCarRec.setCarNum(noCarWayBill.getPlateNum());
        customerCarRec.setCarColor(noCarWayBill.getPlateColor());
        customerCarRec.setCustomerName(appKey);
        //接口
        customerCarRec.setInterType(0);
        customerCarRec.setCompanyNum(customerRec.getCompanyNum());
        customerCarRec.setBusinessType("2");
        //默认运营车辆
        customerCarRec.setServiceOperation(1);
        noCarWayBill.setTitleType(2);
        //接口
        noCarWayBill.setInterType(0);
        return getDataResult(data, costtimestart, result, noCarWayBill, customerCarRecs, customerCarRec);
    }

    private NoCarWayBill getNoCarWayBill(String appKey, String num, String plateNumber, String plateColor, String startTime, String sourceAddr, String destAddr, String predictEndTime, Integer fee, Integer titleType, String taxplayerCode, CustomerRec customerRec) {
        NoCarWayBill noCarWayBill = new NoCarWayBill();
        noCarWayBill.setCustomerName(appKey);
        noCarWayBill.setCompanyName(customerRec.getCompanyName());
        noCarWayBill.setPlateNum(plateNumber);
        noCarWayBill.setBillNum(num);
        noCarWayBill.setPlateColor(plateColor);
        noCarWayBill.setStartTime(DateUtil.getDistanceHoursFormat(startTime));
        noCarWayBill.setSourceAddr(sourceAddr);
        noCarWayBill.setDestAddr(destAddr);
        noCarWayBill.setPredictEndTime(DateUtil.getDistanceHoursFormat(predictEndTime));
        noCarWayBill.setFee(fee.longValue());
        noCarWayBill.setTitleType(titleType);
        noCarWayBill.setTaxplayerCode(taxplayerCode);
        noCarWayBill.setHisFlag(0);
        noCarWayBill.setIntfaceStartTime(DateUtil.getCurrentDateStr());
        return noCarWayBill;
    }

    private DataResult getDataResult(String data, long costtimestart, DataResult result, NoCarWayBill noCarWayBill, List<CustomerCarRec> customerCarRecs, CustomerCarRec customerCarRec) {
        //先查询上游是否已经备案
        RespR<VehicleQueryResponse> respRquery = noCarService.customerCarRecQueryUpper(customerCarRec);
        if (respRquery.getCode() == 1 || respRquery.getData() == null || respRquery.getData().getResult() == null || respRquery.getData().getResult().size() <= 0) {
            customerCarRecs.add(customerCarRec);
            RespR respR = noCarService.customerCarRec(customerCarRecs);
            if (respR.getCode() == 1) {
                noCarWayBill.setFailReason(respR.getMsg());
                noCarWayBill.setBillwayStatus(-2);
                insertOrUpdateBillStart(noCarWayBill);
                result.setMsg("车牌号备案失败，失败原因：" + respR.getMsg());
                return result;
            }
        }
        return getDataResultss(data, costtimestart, result, noCarService.noCarWaybillStart(noCarWayBill), "[-NoCarInterServiceImpl.noCarBillStart-] result is ");
    }

    /**
     * 无车 实时运单结束指令接口
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult noCarBillEnd(String appKey, String api, String data, String requestid) {

        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-NoCarInterServiceImpl.noCarBillEnd-] request appKey=" + appKey + " ,api=" + api + " ,data=" + StringUtil.removeJSonField(data,"base64Str") + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //运单号 必输
            String num = jsonObject.getString("num");
            //运单实际目的地址 必输
            String realDestAddr = jsonObject.getString("realDestAddr");
            //运单实际结束时间 必输
            String endTime = jsonObject.getString("endTime");
            if (StringUtils.isEmpty(data) || null == jsonObject || StringUtils.isEmpty(num)
                    || StringUtils.isEmpty(realDestAddr)
                    || StringUtils.isEmpty(endTime)

            ) {
                result.setMsg("必传参数有空值");
                return result;
            }

            if (!DateUtil.isValidDate(endTime)) {
                result.setMsg("日期格式有误");
                return result;
            }


            NoCarWayBill noCarWayBill = new NoCarWayBill();
            noCarWayBill.setCustomerName(appKey);
            noCarWayBill.setBillNum(num);
            noCarWayBill.setDestAddr(realDestAddr);
            noCarWayBill.setPredictEndTime(DateUtil.getDistanceHoursFormat(endTime));
            noCarWayBill.setHisFlag(0);
            //接口
            noCarWayBill.setInterType(0);
            return getDataResultss(data, costtimestart, result, noCarService.noCarWaybillEnd(noCarWayBill), "[-NoCarInterServiceImpl.noCarBillEnd-] result is ");
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.noCarBillEnd-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    /**
     * 无车 历史运单开始指令接口
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult noCarHisWaybillStart(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();
        DataResult result = new DataResult();
        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");
        try {
            log.info("[-NoCarInterServiceImpl.noCarHisWaybillStart-] request appKey=" + appKey + " ,api=" + api + " ,data=" + StringUtil.removeJSonField(data,"base64Str") + " ,requestid=" + requestid);

            String param = paramService.getParamsByParamName("NO_CAR_HISWAY_BILL_ON_OFF").getParamValue();
            if (StringUtils.isBlank(param) || !StringUtils.equals(ONE, param)) {
                result.setMsg("历史运单开始指令接口已关闭");
                return result;
            }

            JSONObject jsonObject = JSONObject.parseObject(data);
            //运单编号 必选
            String num = jsonObject.getString("num");
            //车牌号 必选
            String plateNumber = jsonObject.getString("plateNumber");
            //车牌颜色 必选
            String plateColor = jsonObject.getString("plateColor");
            //运单开始时间 必选
            String startTime = jsonObject.getString("startTime");
            //运单开始地址 必选
            String sourceAddr = jsonObject.getString("sourceAddr");
            //运单目的地址 必选
            String destAddr = jsonObject.getString("destAddr");
            //运单预计完成时间 必选
            String predictEndTime = jsonObject.getString("predictEndTime");
            //运单费用 必选
            Integer fee = jsonObject.getInteger("fee");
            //发票抬头类型 必选
            Integer titleType = jsonObject.getInteger("titleType");
            //税号 必选
            String taxplayerCode = jsonObject.getString("taxplayerCode");

            String base64Str = jsonObject.getString("base64Str");
            String waybillFileName = jsonObject.getString("waybillFileName");
            Integer contractType = jsonObject.getInteger("contractType");


            if (StringUtils.isEmpty(data) || null == jsonObject
                    || StringUtils.isEmpty(num)
                    || StringUtils.isEmpty(plateNumber)
                    || StringUtils.isEmpty(plateColor)
                    || StringUtils.isEmpty(startTime)
                    || StringUtils.isEmpty(sourceAddr)
                    || StringUtils.isEmpty(destAddr)
                    || StringUtils.isEmpty(predictEndTime)
                    || null == fee
                    || null == titleType
                    || StringUtils.isEmpty(taxplayerCode)
                    || StringUtils.isEmpty(base64Str)
                    || StringUtils.isEmpty(waybillFileName)
                    || null == contractType
            ) {
                result.setMsg("有空的必填运单要素，请检查");
                return result;
            }
            if (!DateUtil.isValidDate(startTime)) {
                result.setMsg("日期格式有误");
                return result;
            }
            if (!DateUtil.isValidDate(predictEndTime)) {
                result.setMsg("日期格式有误");
                return result;
            }
            CustomerRec customerRec = new CustomerRec();
            customerRec.setCustomerName(appKey);
            customerRec.setCompanyReferencenum(taxplayerCode);
            customerRec = customerRecMapper.selectByCustomerNameAndCompanyReference(customerRec);
            if (customerRec == null) {
                result.setMsg("客户：" + appKey + ";税号" + taxplayerCode + "未在平台备案成功，请先做备案");
                return result;
            }

            if(StringUtils.isNotBlank(waybillFileName) && StringUtils.isNotBlank(base64Str) && null != contractType){
                String fileType = waybillFileName.substring(waybillFileName.lastIndexOf(".") + 1).toLowerCase();
                if (!PDF.equals(fileType)) {
                    result.setMsg("必须是pdf文件!");
                    return result;
                }
                int base64StrLength = base64Str.length();
                if (COMPUTE < base64StrLength) {
                    result.setMsg("pdf不可超过10M!");
                    return result;
                }
                base64Str = base64Str.replaceAll(" ", "+");
            }


            NoCarWayBill noCarWayBill = getNoCarWayBills(appKey, num, plateNumber, plateColor, startTime, sourceAddr, destAddr, predictEndTime, fee, titleType, taxplayerCode, customerRec);

            noCarWayBill.setWaybillFileName(waybillFileName);
            noCarWayBill.setBase64Str(base64Str);
            noCarWayBill.setContractType(contractType);
            List<CustomerCarRec> customerCarRecs = new ArrayList<>();
            CustomerCarRec customerCarRec = new CustomerCarRec();
            customerCarRec.setCompanyName(noCarWayBill.getCompanyName());
            customerCarRec.setCarNum(noCarWayBill.getPlateNum());
            customerCarRec.setCarColor(noCarWayBill.getPlateColor());
            customerCarRec.setCustomerName(appKey);
            customerCarRec.setInterType(0);
            customerCarRec.setCompanyNum(customerRec.getCompanyNum());
            customerCarRec.setBusinessType("2");
            //默认运营车辆
            customerCarRec.setServiceOperation(1);
            noCarWayBill.setTitleType(2);
            if (checkCustomerCarRecQueryResult(result, noCarWayBill, customerCarRecs, customerCarRec)) {
                return result;
            }
            RespR respR = noCarService.noCarHisWaybillStart(noCarWayBill);
            try {
                if(respR.getCode() == 0 && StringUtils.isNotBlank(waybillFileName) && StringUtils.isNotBlank(base64Str) ){
                    //上传成功后文件入库
                    NoCarWayBillFileInfo noCarWayBillFileInfo = new NoCarWayBillFileInfo();
                    noCarWayBillFileInfo.setBase64Str(base64Str);
                    noCarWayBillFileInfo.setFileName(waybillFileName);
                    noCarWayBillFileInfo.setBatchNum("接口运单");
                    noCarWayBillFileInfo.setWayBillNum(num);
                    noCarWayBillFileInfo.setUpdateTime(DateUtil.getCurrentDateStr());
                    noCarWayBillFileInfo.setCustomerId(appKey);
                    noCarWayBillFileInfo.setCompanyName(noCarWayBill.getCompanyName());
                    wayBillFileService.insert(noCarWayBillFileInfo);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.info("文件入表失败{}",noCarWayBill.getBillNum());
            }

            return getDataResultss(data, costtimestart, result, respR, "[-NoCarInterServiceImpl.noCarHisWaybillStart-] result is ");
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.noCarHisWaybillStart-] get httpclient exception is "
                    + e + ", request is " + StringUtil.removeJSonField(data,"base64Str"));
        }
        return result;
    }

    private DataResult getDataResultss(String data, long costtimestart, DataResult result, RespR respR, String s) {
        RespR rs = respR;
        long costtimeend = System.currentTimeMillis();
        log.info(s
                + rs.toString() + ", request is " + StringUtil.removeJSonField(data,"base64Str") + " ,costtime="
                + (costtimeend - costtimestart));
        if (null != rs && rs.getCode() == 0) {
            result.setData(1);
            result.setCode(200);
            result.setMsg(rs.getData().toString());
            return result;
        } else {
            result.setData(3);
            result.setCode(200);
            result.setMsg(rs.getMsg());
            return result;
        }
    }

    private boolean checkCustomerCarRecQueryResult(DataResult result, NoCarWayBill noCarWayBill, List<CustomerCarRec> customerCarRecs, CustomerCarRec customerCarRec) {
        //先查询上游是否已经备案
        RespR<VehicleQueryResponse> respRquery = noCarService.customerCarRecQueryUpper(customerCarRec);
        if (respRquery.getCode() == 1 || respRquery.getData() == null || respRquery.getData().getResult() == null || respRquery.getData().getResult().size() <= 0) {
            customerCarRecs.add(customerCarRec);
            RespR respR = noCarService.customerCarRec(customerCarRecs);
            if (respR.getCode() == 1) {
                result.setMsg("车牌号备案失败，失败原因：" + respR.getMsg());
                noCarWayBill.setFailReason(respR.getMsg());
                noCarWayBill.setBillwayStatus(-2);
                insertOrUpdateBillStart(noCarWayBill);
                return true;
            }
        }
        return false;
    }

    private NoCarWayBill getNoCarWayBills(String appKey, String num, String plateNumber, String plateColor, String startTime, String sourceAddr, String destAddr, String predictEndTime, Integer fee, Integer titleType, String taxplayerCode, CustomerRec customerRec) {
        NoCarWayBill noCarWayBill = new NoCarWayBill();
        noCarWayBill.setCustomerName(appKey);
        noCarWayBill.setCompanyName(customerRec.getCompanyName());
        noCarWayBill.setPlateNum(plateNumber);
        noCarWayBill.setBillNum(num);
        noCarWayBill.setPlateColor(plateColor);
        noCarWayBill.setStartTime(DateUtil.getDistanceHoursFormat(startTime));
        noCarWayBill.setSourceAddr(sourceAddr);
        noCarWayBill.setDestAddr(destAddr);
        noCarWayBill.setPredictEndTime(DateUtil.getDistanceHoursFormat(predictEndTime));
        noCarWayBill.setFee(fee.longValue());
        noCarWayBill.setTitleType(titleType);
        noCarWayBill.setTaxplayerCode(taxplayerCode);
        noCarWayBill.setHisFlag(1);
        noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
        noCarWayBill.setIntfaceStartTime(DateUtil.getCurrentDateStr());
        //接口
        noCarWayBill.setInterType(0);
        return noCarWayBill;
    }

    /**
     * 插入或者更新运单
     * @param noCarWayBill
     */
    public void insertOrUpdateBillStart(NoCarWayBill noCarWayBill) {
        noCarWayBill.setIntfaceStartTime(DateUtil.getCurrentDateStr());
        noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
        NoCarWayBill curr = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
        if (null == curr) {
            noCarWaybillMapper.insert(noCarWayBill);
        } else {
            if (curr.getBillwayStatus() < 1) {
                noCarWaybillMapper.updateByBillNum(noCarWayBill);
            }
        }
    }

    /**
     * 无车 历史运单结束指令接口
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult noCarHisWaybillEnd(String appKey, String api, String data, String requestid) {

        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-NoCarInterServiceImpl.noCarHisWaybillEnd-] request appKey=" + appKey + " ,api=" + api + " ,data=" + StringUtil.removeJSonField(data,"base64Str") + " ,requestid=" + requestid);

            String param = paramService.getParamsByParamName("NO_CAR_HISWAY_BILL_ON_OFF").getParamValue();

            if (StringUtils.isBlank(param) || !StringUtils.equals(ONE, param)) {
                result.setMsg("历史运单结束指令接口已关闭");
                return result;
            }


            JSONObject jsonObject = JSONObject.parseObject(data);
            //运单号 必输
            String num = jsonObject.getString("num");
            //运单实际目的地址 必输
            String realDestAddr = jsonObject.getString("realDestAddr");
            //运单实际结束时间 必输
            String endTime = jsonObject.getString("endTime");
            if (StringUtils.isEmpty(data) || null == jsonObject || StringUtils.isEmpty(num)
                    || StringUtils.isEmpty(realDestAddr)
                    || StringUtils.isEmpty(endTime)

            ) {
                result.setMsg("有空的必填运单要素，请检查");
                return result;
            }


            if (!DateUtil.isValidDate(endTime)) {
                result.setMsg("日期格式有误");
                return result;
            }


            NoCarWayBill noCarWayBill = new NoCarWayBill();
            noCarWayBill.setBillNum(num);
            noCarWayBill.setDestAddr(realDestAddr);
            noCarWayBill.setPredictEndTime(DateUtil.getDistanceHoursFormat(endTime));
            noCarWayBill.setHisFlag(1);
            noCarWayBill.setCustomerName(appKey);
            //接口
            noCarWayBill.setInterType(0);
            return getDataResultss(data, costtimestart, result, noCarService.noCarHisWaybillEnd(noCarWayBill), "[-NoCarInterServiceImpl.noCarHisWaybillEnd-] result is ");
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.noCarHisWaybillEnd-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    /**
     * 无车 运单号查询发票数据
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult noCarVoiceQuery(String appKey, String api, String data, String requestid) {

        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-NoCarInterServiceImpl.noCarVoiceQuery-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //运单号 必输
            String num = jsonObject.getString("num");
            if (StringUtils.isEmpty(data) || null == jsonObject || StringUtils.isEmpty(num)

            ) {
                result.setMsg("有空的必填运单要素，请检查");
                return result;
            }

            NoCarWayBill noCarWayBill1 = null;
            try {
                noCarWayBill1 = noCarWaybillMapper.selectByBillNum(num);
            } catch (Exception e) {
                log.info("xuyaoshanchuyundan:" + num);
                result.setMsg("平台运单号存在多条，请联系管理员删除无效运单");
                return result;
            }
            if (null == noCarWayBill1) {
                noCarWayBill1 = new NoCarWayBill();
                noCarWayBill1.setBillNum(num);
                noCarWayBill1.setInterType(0);
                noCarWayBill1.setBillwayStatus(-5);
            }
            if (isaBoolean(noCarWayBill1)) {
                noCarWayBill1.setBillwayStatus(-5);
            }
            noCarWayBill1.setCustomerName(appKey);
            noCarWayBill1.setCompanyName(noCarWayBill1.getCompanyName());
            RespR rs = noCarService.getInvoiceByWayBillNumReal(noCarWayBill1, true);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.noCarVoiceQuery-] result is "
                    + rs.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != rs && rs.getCode() == 0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg(rs.getData().toString());
                return result;
            } else {
                result.setData(3);
                if (NOT_FOUND.equals(rs.getMsg())) {
                    result.setData(2);
                }
                result.setCode(200);
                result.setMsg(noCarWayBill1.getBillwayStatus()+","+rs.getMsg());
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.noCarVoiceQuery-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    private boolean isaBoolean(NoCarWayBill noCarWayBill1) {
        return noCarWayBill1.getInterType() == REC_STATUS_WAIT ||
                (noCarWayBill1.getBillwayStatus() < REC_STATUS_UN &&
                        noCarWayBill1.getFailReason() != null &&
                        noCarWayBill1.getFailReason().contains(XY_WAYBILL_HISTORY_END));
    }

    /**
     * 无车  获取未查询过发票的运单编号
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult noCarNoVoiceQuery(String appKey, String api, String data, String requestid) {

        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-NoCarInterServiceImpl.noCarNoVoiceQuery-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);

            String param = paramService.getParamsByParamName("FIND_NO_SEARCH_NUM_ON_OFF").getParamValue();

            if (!StringUtils.equals(ONE, param)) {
                result.setMsg("获取未查询过发票的运单编号接口已关闭");
                return result;
            }


            List<NoCarWayBill> noCarWayBills = noCarWaybillMapper.getNoCarNoVoiceQuery(appKey);
            List<String> list1 = new ArrayList<String>();

            for (NoCarWayBill noCarWayBill : noCarWayBills
            ) {
                list1.add(noCarWayBill.getBillNum());

            }
            List<BillInvoice> billInvoices = billInvoiceMapper.selectNoCarNoVoiceQuery(appKey);
            List<String> list2 = new ArrayList<String>();
            for (BillInvoice billInvoice : billInvoices
            ) {
                list2.add(billInvoice.getWaybillNum());

            }

            List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());

            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.noCarNoVoiceQuery-] result is "
                    + reduce1.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != reduce1 && reduce1.size() > 0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg(JSONArray.fromObject(reduce1).toString());
                return result;
            } else {
                result.setData(2);
                result.setCode(200);
                result.setMsg("未查得");
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.noCarNoVoiceQuery-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    /**
     * 无车  账户余额查询接口
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult balanceQuery(String appKey, String api, String data, String requestid) {

        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-NoCarInterServiceImpl.balanceQuery-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);


            Customer customer = customerMapper.selectByCustomerName(appKey);


            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.balanceQuery-] result is "
                    + customer.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != customer) {
                result.setData(1);
                result.setCode(200);
                JSONObject jb = new JSONObject();
                jb.put("balance", customer.getAccountBalance());
                jb.put("lastDeductionTime", customer.getInvoiceTime());
                result.setMsg(jb.toString());
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg("无法认证");
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.balanceQuery-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    /**
     * 无车  红冲发票查询接口
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult redInkInvoiceQuery(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-NoCarInterServiceImpl.redInkInvoiceQuery-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //企业税号 必输
            String taxplayerCode = jsonObject.getString("taxplayerCode");
            //开票月份 样例：yyyy-MM   必输
            String month = jsonObject.getString("month");
            //查询第几页  示例1,2,3,4…
            Long pageNo = jsonObject.getLong("pageNo");
            //查询第几页  示例1,2,3,4… 没有就默认1000
            Long pageSize = jsonObject.getLong("pageSize");

            if (StringUtils.isEmpty(data) || null == jsonObject) {
                return result;
            }
            if (StringUtils.isEmpty(taxplayerCode) || StringUtils.isEmpty(month) || null == pageNo || pageNo < 1) {
                return result;
            }


            if (null == DateUtil.parseDate(month)) {
                result.setMsg("日期格式不正确！");
                return result;
            }
            HcInvoiceQueryVo hcInvoiceQueryVo = new HcInvoiceQueryVo();
            hcInvoiceQueryVo.setBuyerTaxpayerCode(taxplayerCode);
            hcInvoiceQueryVo.setMonth(month);
            hcInvoiceQueryVo.setPageSize(pageSize);
            hcInvoiceQueryVo.setPageNo(pageNo);
            RespR rs = noCarService.hcinvoicequeryinter(hcInvoiceQueryVo);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.redInkInvoiceQuery-] result is "
                    + rs.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != rs && rs.getCode() == 0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg(JSON.toJSONString(rs.getData()));
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg("查询失败");
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.redInkInvoiceQuery-] get httpclient exception is "
                    + e + ", request is " + data);
        }

        return result;
    }

    /**
     * 无车 运单号查询发票数据
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult noCarVoiceOwnerQuery(String appKey, String api, String data, String requestid) {

        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-NoCarInterServiceImpl.noCarVoiceOwnerQuery-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //运单号 必输
            String num = jsonObject.getString("num");
            if (StringUtils.isEmpty(data) || null == jsonObject || StringUtils.isEmpty(num)

            ) {
                result.setMsg("有空的必填运单要素，请检查");
                return result;
            }

            NoCarWayBill noCarWayBill1 = null;
            try {
                noCarWayBill1 = noCarWaybillMapper.selectByBillNum(num);
            } catch (Exception e) {
                log.info("xuyaoshanchuyundannoCarVoiceOwnerQuery:" + num);
                result.setMsg("平台运单号存在多条，请联系管理员删除无效运单");
                return result;
            }
            if (null == noCarWayBill1) {
                noCarWayBill1 = new NoCarWayBill();
                noCarWayBill1.setBillNum(num);
            }
            noCarWayBill1.setInterType(0);

            RespR rs = noCarService.getInvoiceByWayBillOwnerNumReal(noCarWayBill1, false);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.noCarVoiceOwnerQuery-] result is "
                    + rs.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != rs && rs.getCode() == 0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg(rs.getData().toString());
                return result;
            } else {
                result.setData(3);
                if (NOT_FOUND.equals(rs.getMsg())) {
                    result.setData(2);
                }
                result.setCode(200);
                result.setMsg(rs.getMsg());
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.noCarVoiceOwnerQuery-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }
    @Autowired
    NoCarCompanyMangerOper noCarCompanyMangerOper;
    @Override
    public DataResult companyDetailAdd(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (StringUtils.isEmpty(data) || null == jsonObject) {
            result.setMsg("有空的必填运单要素，请检查");
            return result;
        }
        //税号 必输
        String taxplayerCode = jsonObject.getString("taxplayerCode");
        String operatorName = jsonObject.getString("operatorName");
        String operatorMobile = jsonObject.getString("operatorMobile");
        String identificationId = jsonObject.getString("identificationId");
        String contractFileName = jsonObject.getString("contractFileName");
        String base64Str = jsonObject.getString("base64Str");
        if(StringUtils.isEmpty(taxplayerCode) || StringUtils.isEmpty(operatorName)
                ||StringUtils.isEmpty(operatorMobile) ||StringUtils.isEmpty(contractFileName)
                ||StringUtils.isEmpty(base64Str)  ){
            result.setMsg("有空的必填运单要素，请检查");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(appKey);
        customerRec.setCompanyReferencenum(taxplayerCode);
        customerRec = customerRecMapper.selectByCustomerNameAndCompanyReference(customerRec);
        if (customerRec == null) {
            result.setMsg("客户：" + appKey + ";税号" + taxplayerCode + "未在平台备案成功，请先做备案");
            return result;
        }
        try {
            log.info("[-NoCarInterServiceImpl.companyDetailAdd-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            NoCarCompanyManger noCarCompanyManger = new NoCarCompanyManger();
            noCarCompanyManger.setCompanyNum(customerRec.getCompanyNum());
            noCarCompanyManger.setOperatorName(operatorName);
            noCarCompanyManger.setOperatorMobile(operatorMobile);
            noCarCompanyManger.setIdentificationId(identificationId);
            noCarCompanyManger.setContractFileName(contractFileName);
            noCarCompanyManger.setBase64Str(base64Str);
            noCarCompanyManger.setCustId(customerRec.getCustomerName());
            noCarCompanyManger.setCompanyName(customerRec.getCompanyName());
            RespR re = noCarCompanyMangerOper.companyDetailAdd(noCarCompanyManger);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.companyDetailAdd-] result is "
                    + re.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != re && re.getCode()==0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg("success");
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg(re.getMsg());
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.companyDetailAdd-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    @Override
    public DataResult operatorEdit(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (StringUtils.isEmpty(data) || null == jsonObject) {
            result.setMsg("有空的必填运单要素，请检查");
            return result;
        }
        //税号 必输
        String taxplayerCode = jsonObject.getString("taxplayerCode");
        String sourceOperatorMobile = jsonObject.getString("sourceOperatorMobile");
        String targetOperatorName = jsonObject.getString("targetOperatorName");
        String targetOperatorMobile = jsonObject.getString("targetOperatorMobile");
        String targetIdentificationId = jsonObject.getString("targetIdentificationId");
        if(StringUtils.isEmpty(taxplayerCode) || StringUtils.isEmpty(targetOperatorName)
                ||StringUtils.isEmpty(targetOperatorMobile) ||StringUtils.isEmpty(sourceOperatorMobile)){
            result.setMsg("有空的必填运单要素，请检查");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(appKey);
        customerRec.setCompanyReferencenum(taxplayerCode);
        customerRec = customerRecMapper.selectByCustomerNameAndCompanyReference(customerRec);
        if (customerRec == null) {
            result.setMsg("客户：" + appKey + ";税号" + taxplayerCode + "未在平台备案成功，请先做备案");
            return result;
        }
        try {
            log.info("[-NoCarInterServiceImpl.operatorEdit-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            OperatorEditVo operatorEditVo = new OperatorEditVo();
            operatorEditVo.setCompanyNum(customerRec.getCompanyNum());
            operatorEditVo.setSourceOperatorMobile(sourceOperatorMobile);
            operatorEditVo.setTargetOperatorName(targetOperatorName);
            operatorEditVo.setTargetOperatorMobile(targetOperatorMobile);
            operatorEditVo.setTargetIdentificationId(targetIdentificationId);
            RespR re = noCarCompanyMangerOper.operatorEdit(operatorEditVo);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.operatorEdit-] result is "
                    + re.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != re && re.getCode()==0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg("success");
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg(re.getMsg());
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.operatorEdit-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    @Override
    public DataResult operatorEditConfirm(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (StringUtils.isEmpty(data) || null == jsonObject) {
            result.setMsg("有空的必填运单要素，请检查");
            return result;
        }
        //税号 必输
        String taxplayerCode = jsonObject.getString("taxplayerCode");
        String targetOperatorMobile = jsonObject.getString("targetOperatorMobile");
        String validCode = jsonObject.getString("validCode");
        if(StringUtils.isEmpty(taxplayerCode) || StringUtils.isEmpty(targetOperatorMobile)
                ||StringUtils.isEmpty(validCode)){
            result.setMsg("有空的必填运单要素，请检查");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(appKey);
        customerRec.setCompanyReferencenum(taxplayerCode);
        customerRec = customerRecMapper.selectByCustomerNameAndCompanyReference(customerRec);
        if (customerRec == null) {
            result.setMsg("客户：" + appKey + ";税号" + taxplayerCode + "未在平台备案成功，请先做备案");
            return result;
        }
        try {
            log.info("[-NoCarInterServiceImpl.operatorEditConfirm-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            OperatorEditConfirmVo operatorEditConfirmVo = new OperatorEditConfirmVo();
            operatorEditConfirmVo.setCompanyNum(customerRec.getCompanyNum());
            operatorEditConfirmVo.setTargetOperatorMobile(targetOperatorMobile);
            operatorEditConfirmVo.setValidCode(validCode);
            RespR re = noCarCompanyMangerOper.operatorEditConfirm(operatorEditConfirmVo);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.operatorEditConfirm-] result is "
                    + re.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != re && re.getCode()==0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg("success");
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg(re.getMsg());
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.operatorEditConfirm-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    @Override
    public DataResult operatorEvidence(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (StringUtils.isEmpty(data) || null == jsonObject) {
            result.setMsg("有空的必填运单要素，请检查");
            return result;
        }
        //税号 必输
        String taxplayerCode = jsonObject.getString("taxplayerCode");
        String operatorMobile = jsonObject.getString("operatorMobile");
        String contractFileName = jsonObject.getString("contractFileName");
        String base64Str = jsonObject.getString("base64Str");
        if(StringUtils.isEmpty(taxplayerCode)
                ||StringUtils.isEmpty(operatorMobile) ||StringUtils.isEmpty(contractFileName)
                ||StringUtils.isEmpty(base64Str)  ){
            result.setMsg("有空的必填运单要素，请检查");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(appKey);
        customerRec.setCompanyReferencenum(taxplayerCode);
        customerRec = customerRecMapper.selectByCustomerNameAndCompanyReference(customerRec);
        if (customerRec == null) {
            result.setMsg("客户：" + appKey + ";税号" + taxplayerCode + "未在平台备案成功，请先做备案");
            return result;
        }
        try {
            log.info("[-NoCarInterServiceImpl.operatorEvidence-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            OperatorEvidenceVo operatorEvidenceVo = new OperatorEvidenceVo();
            operatorEvidenceVo.setCompanyNum(customerRec.getCompanyNum());
            operatorEvidenceVo.setOperatorMobile(operatorMobile);
            operatorEvidenceVo.setContractFileName(contractFileName);
            operatorEvidenceVo.setBase64Str(base64Str);
            RespR re = noCarCompanyMangerOper.operatorEvidence(operatorEvidenceVo);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.operatorEvidence-] result is "
                    + re.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != re && re.getCode()==0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg("success");
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg(re.getMsg());
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.operatorEvidence-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    @Override
    public DataResult operatorSendCode(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (StringUtils.isEmpty(data) || null == jsonObject) {
            result.setMsg("有空的必填运单要素，请检查");
            return result;
        }
        //税号 必输
        String taxplayerCode = jsonObject.getString("taxplayerCode");
        if(StringUtils.isEmpty(taxplayerCode)){
            result.setMsg("有空的必填运单要素，请检查");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(appKey);
        customerRec.setCompanyReferencenum(taxplayerCode);
        customerRec = customerRecMapper.selectByCustomerNameAndCompanyReference(customerRec);
        if (customerRec == null) {
            result.setMsg("客户：" + appKey + ";税号" + taxplayerCode + "未在平台备案成功，请先做备案");
            return result;
        }
        try {
            log.info("[-NoCarInterServiceImpl.operatorSendCode-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            OperatorSendCodeVo operatorSendCodeVo = new OperatorSendCodeVo();
            operatorSendCodeVo.setBuyerCode(taxplayerCode);
            RespR re = noCarCompanyMangerOper.operatorSendCode(operatorSendCodeVo, customerRec);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.operatorSendCode-] result is "
                    + re.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != re && re.getCode()==0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg("success");
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg(re.getMsg());
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.operatorSendCode-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    @Override
    public DataResult operatorValidCode(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (StringUtils.isEmpty(data) || null == jsonObject) {
            result.setMsg("有空的必填运单要素，请检查");
            return result;
        }
        //税号 必输
        String taxplayerCode = jsonObject.getString("taxplayerCode");
        String validCode = jsonObject.getString("validCode");
        if(StringUtils.isEmpty(taxplayerCode)||StringUtils.isEmpty(validCode)){
            result.setMsg("有空的必填运单要素，请检查");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(appKey);
        customerRec.setCompanyReferencenum(taxplayerCode);
        customerRec = customerRecMapper.selectByCustomerNameAndCompanyReference(customerRec);
        if (customerRec == null) {
            result.setMsg("客户：" + appKey + ";税号" + taxplayerCode + "未在平台备案成功，请先做备案");
            return result;
        }
        try {
            log.info("[-NoCarInterServiceImpl.operatorValidCode-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            OperatorSendCodeVo operatorSendCodeVo = new OperatorSendCodeVo();
            operatorSendCodeVo.setBuyerCode(taxplayerCode);
            operatorSendCodeVo.setValidCode(validCode);
            RespR re = noCarCompanyMangerOper.operatorValidCode(operatorSendCodeVo, customerRec);
            long costtimeend = System.currentTimeMillis();
            log.info("[-NoCarInterServiceImpl.operatorValidCode-] result is "
                    + re.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != re && re.getCode()==0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg("success");
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg(re.getMsg());
                return result;
            }
        } catch (Exception e) {
            log.error("[-NoCarInterServiceImpl.operatorValidCode-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }
}
