package com.jkcredit.invoice.hub.service.apiCarFree;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.tts.vehicle.VehicleQueryRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.vehicle.VehicleQueryResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.vehicle.VehicleRegisterRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.vehicle.VehicleRegisterResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jkcredit.invoice.hub.constant.CommonConstant;
import com.jkcredit.invoice.hub.enums.ApiResponseCodeEnum;
import com.jkcredit.invoice.hub.model.dto.apiCarFree.InvoiceResult;
import com.jkcredit.invoice.hub.model.dto.apiCarFree.InvoiceResultDto;
import com.jkcredit.invoice.hub.model.dto.apiCarFree.WayBillNumFindInvoiceDto;
import com.jkcredit.invoice.hub.model.dto.carFreeCarrierBillEnd.CarFreeCarrierBillEndDto;
import com.jkcredit.invoice.hub.model.dto.carFreeCarrierBillStart.CarFreeCarrierBillStartDto;
import com.jkcredit.invoice.hub.model.dto.apiCarFree.VehicleRegisterDto;
import com.jkcredit.invoice.hub.model.dto.searchInvoice.SearchInvoiceDto;
import com.jkcredit.invoice.hub.model.po.carFreeCarrierBillStart.CarFreeCarrierBillStartPo;
import com.jkcredit.invoice.hub.model.po.searchInvoice.SearchInvoicePo;
import com.jkcredit.invoice.hub.service.base.BaseService;
import com.jkcredit.invoice.hub.service.carFreeCarrierBillEnd.CarFreeCarrierBillEndService;
import com.jkcredit.invoice.hub.service.carFreeCarrierBillStart.CarFreeCarrierBillStartService;
import com.jkcredit.invoice.hub.service.searchInvoice.SearchInvoiceService;
import com.jkcredit.invoice.hub.service.searchInvoiceResult.SearchInvoiceResultService;
import com.jkcredit.invoice.hub.spi.lang.exception.ServiceException;
import com.jkcredit.invoice.hub.spi.rest.data.ApiResponseData;
import com.jkcredit.invoice.hub.util.BeanUtil;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @description: 无车api接口
 * @author: xusonglin
 * @create: 2020/1/16 21:52
 * @version: V1.0
 **/
@Service
@Slf4j
public class ApiCarFreeServiceImpl extends BaseService implements ApiCarFreeService {
    @Autowired
    CarFreeCarrierBillStartService wayBillStartService;
    @Autowired
    CarFreeCarrierBillEndService wayBillEndService;
    @Autowired
    SearchInvoiceResultService searchInvoiceResultService;
    @Autowired
    SearchInvoiceService searchInvoiceService;
    @Autowired
    ApiCarFreeChargeService apiCarFreeChargeService;

    @Override
    public ApiResponseData vehicleRegisterQuery(JSONObject param) {
        long costTimeStart = System.currentTimeMillis();
        String result;

        try {
            VehicleRegisterDto dto = JSON.toJavaObject(param, VehicleRegisterDto.class);
            validate(dto);

            VehicleQueryRequest request = new VehicleQueryRequest();
            request.setPlateNum(dto.getPlateNumber());
            request.setPlateColor(dto.getPlateColor());
            request.setCompanyNum(CommonConstant.COMPANY_NUMBER);
            request.setWaybillSource(CommonConstant.WAYBILL_SOURCE_1);
            String fileName = request.getFilename();

            // 调用upload 发送数据
            VehicleQueryResponse response = ETCCommHelper.upload(fileName, request, VehicleQueryResponse.class);

            result = response.toJson();
            long costTimeEnd = System.currentTimeMillis();
            log.info("[-vehicleRegisterQuery-] result is " + result.replaceAll("\r|\n", "") + " , request is "
                    + param + ",costtime=" + (costTimeEnd - costTimeStart) + ",startTime=" + costTimeStart
                    + ",endTime=" + costTimeEnd);
        } catch (IOException e) {
            log.error("[-vehicleRegisterQuery-] 网络异常 " + e);
            throw new ServiceException(CommonConstant.QUERY_FAILED);
        } catch (ApiRequestException apie) {
            log.error("[-vehicleRegisterQuery-] 错误信息：" + apie.getMessage());
            throw new com.jkcredit.invoice.hub.spi.lang.exception.ApiRequestException(apie.getMessage());
        } catch (ServiceException se) {
            log.error("[-vehicleRegisterQuery-] 错误信息：" + se.getMessage());
            throw new ServiceException(se.getMessage());
        }
        return analyzeApiResultItems(result);
    }

    @Override
    public ApiResponseData vehicleRegister(JSONObject param) {
        long costTimeStart = System.currentTimeMillis();
        String result;

        try {
            VehicleRegisterDto dto = JSON.toJavaObject(param, VehicleRegisterDto.class);
            validate(dto);

            VehicleRegisterRequest request = new VehicleRegisterRequest();
            request.setPlateNum(dto.getPlateNumber());
            request.setPlateColor(dto.getPlateColor());
            request.setCompanyNum(CommonConstant.COMPANY_NUMBER);
            String fileName = request.getFilename();

            // 调用upload 发送数据
            VehicleRegisterResponse response = ETCCommHelper.upload(fileName, request, VehicleRegisterResponse.class);

            result = response.toJson();
            long costTimeEnd = System.currentTimeMillis();
            log.info("[-apiVehicleRegister-] result is " + result.replaceAll("\r|\n", "") + " , request is "
                    + param + ",costtime=" + (costTimeEnd - costTimeStart) + ",startTime=" + costTimeStart
                    + ",endTime=" + costTimeEnd);
        } catch (IOException e) {
            log.error("[-apiVehicleRegister-] 网络异常 " + e);
            throw new ServiceException(CommonConstant.QUERY_FAILED);
        } catch (ApiRequestException apie) {
            log.error("[-apiVehicleRegister-] 错误信息：" + apie.getMessage());
            throw new com.jkcredit.invoice.hub.spi.lang.exception.ApiRequestException(apie.getMessage());
        } catch (ServiceException se) {
            log.error("[-apiVehicleRegister-] 错误信息：" + se.getMessage());
            throw new ServiceException(se.getMessage());
        }
        return analyzeApiResultItems(result);
    }

    @Override
    public ApiResponseData wayBillStart(JSONObject param) {
        long costTimeStart = System.currentTimeMillis();
        String result;

        try {
            CarFreeCarrierBillStartDto dto = JSONObject.toJavaObject(param, CarFreeCarrierBillStartDto.class);
            validate(dto);

            WaybillStartRequest request = new WaybillStartRequest();
            request.setCompanyNum(CommonConstant.COMPANY_NUMBER);
            request.setNum(dto.getNum());
            request.setPlateNum(dto.getPlateNumber());
            request.setPlateColor(dto.getPlateColor());
            request.setStartTime(dto.getStartTime());
            request.setSourceAddr(dto.getSourceAddr());
            request.setDestAddr(dto.getDestAddr());
            request.setPredictEndTime(dto.getPredictEndTime());
            request.setFee(dto.getFee());
            request.setTitleType(dto.getTitleType());

            if (!StringUtil.isNullOrEmpty(dto.getTaxPlayerCode())) {
                request.setTaxplayerCode(dto.getTaxPlayerCode());
            }
            String fileName = request.getFilename();

            // 调用upload 发送数据
            WaybillStartResponse response = ETCCommHelper.upload(fileName, request, WaybillStartResponse.class);

            dto.setIsHistory(CommonConstant.REALTIME_WAY_BILL);
            wayBillStartService.saveBillStart(dto);

            result = response.toJson();
            long costTimeEnd = System.currentTimeMillis();
            log.info("[-wayBillStart-] result is " + result.replaceAll("\r|\n", "") + " , request is "
                    + param + ",costtime=" + (costTimeEnd - costTimeStart) + ",startTime=" + costTimeStart
                    + ",endTime=" + costTimeEnd);
        } catch (IOException e) {
            log.error("[-wayBillStart-] 网络异常 " + e);
            throw new ServiceException(CommonConstant.QUERY_FAILED);
        } catch (ApiRequestException apie) {
            log.error("[-wayBillStart-] 错误信息：" + apie.getMessage());
            throw new com.jkcredit.invoice.hub.spi.lang.exception.ApiRequestException(apie.getMessage());
        } catch (ServiceException se) {
            log.error("[-wayBillStart-] 错误信息：" + se.getMessage());
            throw new ServiceException(se.getMessage());
        }
        return analyzeApiResultItems(result);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public ApiResponseData wayBillEnd(JSONObject param) {
        long costTimeStart = System.currentTimeMillis();
        String result;

        try {
            CarFreeCarrierBillEndDto dto = JSONObject.toJavaObject(param, CarFreeCarrierBillEndDto.class);
            validate(dto);

            WaybillEndRequest request = new WaybillEndRequest();
            request.setCompanyNum(CommonConstant.COMPANY_NUMBER);
            request.setNum(dto.getNum());
            request.setRealDestAddr(dto.getRealDestAddr());
            request.setEndTime(dto.getEndTime());
            String fileName = request.getFilename();

            // 调用upload 发送数据
            WaybillEndResponse response = ETCCommHelper.upload(fileName, request, WaybillEndResponse.class);

            dto.setIsHistory(CommonConstant.REALTIME_WAY_BILL);
            wayBillEndService.saveBillEnd(dto);
            wayBillStartService.updateBillStartStatus(dto.getNum(), CommonConstant.STATUS_OVER);

            result = response.toJson();
            long costTimeEnd = System.currentTimeMillis();
            log.info("[-waybillEnd-] result is " + result.replaceAll("\r|\n", "") + " , request is "
                    + param + ",costtime=" + (costTimeEnd - costTimeStart) + ",startTime=" + costTimeStart
                    + ",endTime=" + costTimeEnd);
        } catch (IOException e) {
            log.error("[-wayBillEnd-] 网络异常 " + e);
            throw new ServiceException(CommonConstant.QUERY_FAILED);
        } catch (ApiRequestException apie) {
            log.error("[-wayBillEnd-] 错误信息：" + apie.getMessage());
            throw new com.jkcredit.invoice.hub.spi.lang.exception.ApiRequestException(apie.getMessage());
        } catch (ServiceException se) {
            log.error("[-wayBillEnd-] 错误信息：" + se.getMessage());
            throw new ServiceException(se.getMessage());
        }
        return analyzeApiResultItems(result);
    }

    @Override
    public ApiResponseData wayBillHistoryStart(JSONObject param) {
        long costTimeStart = System.currentTimeMillis();
        String result;

        try {
            CarFreeCarrierBillStartDto dto = JSONObject.toJavaObject(param, CarFreeCarrierBillStartDto.class);
            validate(dto);

            WaybillHistoryStartRequest request = new WaybillHistoryStartRequest();
            request.setCompanyNum(CommonConstant.COMPANY_NUMBER);
            request.setNum(dto.getNum());
            request.setPlateNum(dto.getPlateNumber());
            request.setPlateColor(dto.getPlateColor());
            request.setStartTime(dto.getStartTime());
            request.setSourceAddr(dto.getSourceAddr());
            request.setDestAddr(dto.getDestAddr());
            request.setPredictEndTime(dto.getPredictEndTime());
            request.setFee(dto.getFee());
            request.setTitleType(dto.getTitleType());

            if (!StringUtil.isNullOrEmpty(dto.getTaxPlayerCode())) {
                request.setTaxplayerCode(dto.getTaxPlayerCode());
            }
            String fileName = request.getFilename();

            // 调用upload 发送数据
            WaybillHistoryStartResponse response = ETCCommHelper.upload(fileName, request, WaybillHistoryStartResponse.class);

            dto.setIsHistory(CommonConstant.HISTORY_WAY_BILL);
            wayBillStartService.saveBillStart(dto);

            result = response.toJson();
            long costTimeEnd = System.currentTimeMillis();
            log.info("[-wayBillHistoryStart-] result is " + result.replaceAll("\r|\n", "") + " , request is "
                    + param + ",costtime=" + (costTimeEnd - costTimeStart) + ",startTime=" + costTimeStart
                    + ",endTime=" + costTimeEnd);
        } catch (IOException e) {
            log.error("[-wayBillHistoryStart-] 网络异常 " + e);
            throw new ServiceException(CommonConstant.QUERY_FAILED);
        } catch (ApiRequestException apie) {
            log.error("[-wayBillHistoryStart-] 错误信息：" + apie.getMessage());
            throw new com.jkcredit.invoice.hub.spi.lang.exception.ApiRequestException(apie.getMessage());
        } catch (ServiceException se) {
            log.error("[-wayBillHistoryStart-] 错误信息：" + se.getMessage());
            throw new ServiceException(se.getMessage());
        }
        return analyzeApiResultItems(result);
    }

    @Override
    public ApiResponseData wayBillHistoryEnd(JSONObject param) {
        long costTimeStart = System.currentTimeMillis();
        String result;

        try {
            CarFreeCarrierBillEndDto dto = JSONObject.toJavaObject(param, CarFreeCarrierBillEndDto.class);
            validate(dto);

            WaybillHistoryEndRequest request = new WaybillHistoryEndRequest();
            request.setCompanyNum(CommonConstant.COMPANY_NUMBER);
            request.setNum(dto.getNum());
            request.setRealDestAddr(dto.getRealDestAddr());
            request.setEndTime(dto.getEndTime());
            String fileName = request.getFilename();

            // 调用upload 发送数据
            WaybillHistoryEndResponse response = ETCCommHelper.upload(fileName, request, WaybillHistoryEndResponse.class);

            dto.setIsHistory(CommonConstant.HISTORY_WAY_BILL);
            wayBillEndService.saveBillEnd(dto);
            wayBillStartService.updateBillStartStatus(dto.getNum(), CommonConstant.STATUS_OVER);

            result = response.toJson();
            long costTimeEnd = System.currentTimeMillis();
            log.info("[-wayBillHistoryEnd-] result is " + result.replaceAll("\r|\n", "") + " , request is "
                    + param + ",costtime=" + (costTimeEnd - costTimeStart) + ",startTime=" + costTimeStart
                    + ",endTime=" + costTimeEnd);
        } catch (IOException e) {
            log.error("[-wayBillHistoryEnd-] 网络异常 " + e);
            throw new ServiceException(CommonConstant.QUERY_FAILED);
        } catch (ApiRequestException apie) {
            log.error("[-wayBillHistoryEnd-] 错误信息：" + apie.getMessage());
            throw new com.jkcredit.invoice.hub.spi.lang.exception.ApiRequestException(apie.getMessage());
        } catch (ServiceException se) {
            log.error("[-wayBillHistoryEnd-] 错误信息：" + se.getMessage());
            throw new ServiceException(se.getMessage());
        }
        return analyzeApiResultItems(result);
    }

    @Override
    public ApiResponseData wayBillNumFindInvoice(JSONObject param) {
        long costTimeStart = System.currentTimeMillis();
        String result;

        try {
            WayBillNumFindInvoiceDto dto = JSONObject.toJavaObject(param, WayBillNumFindInvoiceDto.class);
            validate(dto);

            WaybillNumFindInvoiceRequest request = new WaybillNumFindInvoiceRequest();
            request.setCompanyNum(CommonConstant.COMPANY_NUMBER);
            request.setWaybillNum(dto.getNum());
            String fileName = request.getFilename();

            // 调用upload 发送数据
            WaybillNumFindInvoiceResponse response = ETCCommHelper.upload(fileName, request, WaybillNumFindInvoiceResponse.class);

            result = response.toJson();
            long costTimeEnd = System.currentTimeMillis();
            log.info("[-waiBillNumFindInvoice-] result is " + result.replaceAll("\r|\n", "") + " , request is "
                    + param + ",costtime=" + (costTimeEnd - costTimeStart) + ",startTime=" + costTimeStart
                    + ",endTime=" + costTimeEnd);
        } catch (IOException e) {
            log.error("[-waiBillNumFindInvoice-] 网络异常 " + e);
            throw new ServiceException(CommonConstant.QUERY_FAILED);
        } catch (ApiRequestException apie) {
            log.error("[-waiBillNumFindInvoice-] 错误信息：" + apie.getMessage());
            throw new com.jkcredit.invoice.hub.spi.lang.exception.ApiRequestException(apie.getMessage());
        } catch (ServiceException se) {
            log.error("[-waiBillNumFindInvoice-] 错误信息：" + se.getMessage());
            throw new ServiceException(se.getMessage());
        }
        return ApiResponseData.success(ApiResponseCodeEnum.CODE_200.getValue(), result);
    }

    @Override
    public ApiResponseData findInvoice(JSONObject param) {
        try {
            CarFreeCarrierBillStartPo po = wayBillStartService.getBillStartByNum(param.getString("num"));
            if (po != null) {
                wayBillStartService.updateBillStartIsSearch(param.getString("num"));
            } else {
                po = new CarFreeCarrierBillStartPo();
                po.setUserId(param.getLong("userId"));
                po.setNum(param.getString("num"));
            }
            return apiCarFreeChargeService.charge(po);
        } catch (ServiceException se) {
            log.error("[-findInvoice-] 错误信息：" + se.getMessage());
            throw new ServiceException(se.getMessage());
        }
    }

    @Override
    public ApiResponseData findNoSearchNums(JSONObject param) {
        try {
            List<String> nums = wayBillStartService.getNoSearchNums(param.getString("userId"));
            return ApiResponseData.success(ApiResponseCodeEnum.CODE_200.getValue(), JSON.toJSONString(nums));
        } catch (ServiceException e) {
            log.error("[-findNoSearchNums-] 错误信息：" + e.getMessage());
            throw new ServiceException(e.getMessage());
        }
    }
}
