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

import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.B2bContractAddRequest;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.B2bContractAddResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jkcredit.invoice.hub.mapper.ContractMapper;
import com.jkcredit.invoice.hub.model.dto.contract.ContractDto;
import com.jkcredit.invoice.hub.model.po.contract.ContractPo;
import com.jkcredit.invoice.hub.model.vo.contract.ContractVo;
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 sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;

/**
 * @description:
 * @author: xusonglin
 * @create: 2020/3/3 9:24
 * @version: V1.0
 **/
@Slf4j
@Service
public class ContractServiceImpl extends BaseService implements ContractService {
    @Resource
    ContractMapper contractMapper;

    @Override
    public void uploadContract(ContractDto contractDto) {
        String filename = contractDto.getContract().getOriginalFilename();
        String[] args = filename.split("\\.");
        if (!args[args.length - 1].equals("pdf")) {
            throw new ServiceException("协议转换失败");
        }
        // 参数设置
        validate(contractDto);
        B2bContractAddRequest request = new B2bContractAddRequest();
        request.setCompanyNum(contractDto.getCompanyNum());
        request.setServiceType(contractDto.getServiceType());
        request.setServiceStartTime(contractDto.getServiceStartTime());
        request.setServiceEndTime(contractDto.getServiceEndTime());
        request.setContractFileName(filename);

        String base64Str;
        try {
            base64Str = Base64.getEncoder().encodeToString(contractDto.getContract().getBytes());
            request.setBase64Str(base64Str);
        } catch (IOException ioe) {
            log.error("上传协议转base64失败，失败原因：{}", ioe.getMessage());
            throw new ServiceException("协议转换失败");
        }
        String fileName = request.getFilename();

        // 接口调用
        B2bContractAddResponse response;
        try {
            // 调用upload 发送数据
            response = ETCCommHelper.upload(fileName, request, B2bContractAddResponse.class);
            log.info("[-uploadContract-] 上游返回结果：" + response.toJson());
        } catch (IOException e) {
            log.error("[-uploadContract-] 网络错误：" + e.getMessage());
            throw new ServiceException("上传协议失败");
        } catch (ApiRequestException apie) {
            log.error("[-uploadContract-] 错误信息：" + apie.getMessage());
            throw new ServiceException("上传协议失败,失败原因：" + apie.getMessage());
        } catch (Exception e) {
            log.error("[-uploadContract-] 错误：" + e.getMessage());
            throw new ServiceException("上传协议失败,失败原因：" + e.getMessage());
        }
        try {
            ContractPo contractPo = new ContractPo();
            BeanUtil.copyProperties(contractPo, contractDto);
            contractPo.setBase64Str(base64Str);
            contractPo.setCreateTime(new Date());
            contractPo.setContractNum(response.getContrantNum());
            contractMapper.insert(contractPo);
        } catch (Exception e) {
            log.error("上传协议失败，失败原因：{}", e.getMessage());
            throw new ServiceException("上传协议新增失败");
        }
    }

    @Override
    public IPage<ContractVo> getContracts(Page page, ContractDto contractDto) {
        IPage<ContractPo> contractPoIPage = contractMapper.getContracts(page, contractDto);
        return contractPoIPage.convert(this::convert);
    }

    private ContractVo convert(ContractPo po) {
        ContractVo vo = new ContractVo();
        BeanUtil.copyProperties(vo, po);
        return vo;
    }
}
