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

import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.B2bContractQueryRequest;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.B2bContractQueryResponse;
import com.jkcredit.invoice.hub.mapper.ContractQueryMapper;
import com.jkcredit.invoice.hub.model.dto.contractQuery.ContractQueryDto;
import com.jkcredit.invoice.hub.model.po.contractQuery.ContractQueryPo;
import com.jkcredit.invoice.hub.model.vo.contractQuery.ContractQueryVo;
import com.jkcredit.invoice.hub.service.base.BaseService;
import com.jkcredit.invoice.hub.spi.lang.exception.ApiRequestException;
import com.jkcredit.invoice.hub.spi.lang.exception.ServiceException;
import com.jkcredit.invoice.hub.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @description:
 * @author: xusonglin
 * @create: 2020/3/3 11:16
 * @version: V1.0
 **/
@Slf4j
@Service
public class ContractQueryServiceImpl extends BaseService implements ContractQueryService {
    @Resource
    ContractQueryMapper mapper;

    @Override
    public ContractQueryVo queryContract(ContractQueryDto contractDto) {
        validate(contractDto);
        B2bContractQueryRequest request = new B2bContractQueryRequest();
        request.setCompanyNum(contractDto.getCompanyNum());
        request.setContractNum(contractDto.getContractNum());
        String fileName = request.getFilename();

        B2bContractQueryResponse response;
        try {
            response = ETCCommHelper.upload(fileName, request, B2bContractQueryResponse.class);
            log.info("[-queryContract-] 上游返回结果：" + response.toJson());
        } catch (IOException e) {
            log.error("[-queryContract-] 网络错误：" + e.getMessage());
            throw new ServiceException("协议查询失败");
        } catch (ApiRequestException apie) {
            log.error("[-queryContract-] 错误信息：" + apie.getMessage());
            throw new ServiceException("协议查询失败,失败原因：" + apie.getMessage());
        }
        try {
            ContractQueryPo contractQueryPo = new ContractQueryPo();
            BeanUtil.copyProperties(contractQueryPo, contractDto);
            BeanUtil.copyProperties(contractQueryPo, response);
            mapper.insert(contractQueryPo);

            ContractQueryVo contractQueryVo = new ContractQueryVo();
            BeanUtil.copyProperties(contractQueryVo, contractQueryPo);
            return contractQueryVo;
        } catch (Exception e) {
            log.error("协议查询失败，失败原因：{}", e.getMessage());
            throw new ServiceException("协议查询失败");
        }
    }
}
