package com.sunxung.factoring.service.financing.contractTemplate.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.util.CloseableHttpClientUtils;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.component.util.FileUtil;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.financing.contractTemplate.ContractTemplate;
import com.sunxung.factoring.entity.financing.contractTemplate.vo.SynchronizeFileVo;
import com.sunxung.factoring.entity.financing.contractTemplate.vo.SynchronizeVo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.mapper.financing.contractTemplate.ContractTemplateMapper;
import com.sunxung.factoring.service.financing.contractTemplate.IContractTemplateService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 合同模板 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2024-03-04
 */
@Service
public class ContractTemplateServiceImpl extends ServiceImpl<ContractTemplateMapper, ContractTemplate> implements IContractTemplateService {

    @Autowired
    private FileStorageService fileStorageService;

    @Value("${sop.synchronizeDownloadFile}")
    private String getFileUrl;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void SynchronizeContractTemplate(SynchronizeVo synchronizeVo) {
        String versionNo = synchronizeVo.getVersionNo();
        Integer count = lambdaQuery().eq(ContractTemplate::getVersion, versionNo).count();
        if (count != null && count > 0) {
            throw new BusinessException(CodeUtil.FAIL, "该版本合同已经通不过，无需再同步！");
        }
        List<SynchronizeFileVo> synchronizeFileVos = synchronizeVo.getSynchronizeFileVos();

        if (CollectionUtil.isNotEmpty(synchronizeFileVos)) {
            lambdaUpdate().set(ContractTemplate::getVisible, 0).update();
        } else {
            throw new BusinessException(CodeUtil.FAIL, "该版本未获取到合同信息！");
        }
        for (SynchronizeFileVo synchronizeFileVo : synchronizeFileVos) {
            //保存合同模板信息
            String name = synchronizeFileVo.getName().replace("编号","");
            String contractType = synchronizeFileVo.getContractType();
            String templateCode = synchronizeFileVo.getTemplateCode();
            String templateType = synchronizeFileVo.getTemplateType();
            ContractTemplate contractTemplate = new ContractTemplate();
            contractTemplate.setVersion(versionNo);
            contractTemplate.setName(name);
            contractTemplate.setTemplateCode(templateCode);
            contractTemplate.setTemplateType(templateType);
            contractTemplate.setContractType(contractType);
            contractTemplate.setVisible(1);
            save(contractTemplate);
            //从sop获取文件
            String fileType = synchronizeFileVo.getFileType();
            Long file = synchronizeFileVo.getFile();
            FileModuleDict.ChildEnum childEnum = FileModuleDict.ChildEnum.CONTRACT_TEMPLATE_FILE;
            String fileName = UUID.randomUUID().toString();
            String localFilePath = FileUtil.getAbsolutePath(fileName, fileType, childEnum);
            File destFile = new File(localFilePath);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            getFileFromSop(file, destFile);
            //新建FileStorage
            FileStorage newFileStorage = new FileStorage(fileName, name + fileType, localFilePath, childEnum);
            fileStorageService.add(newFileStorage);
            List list = new ArrayList();
            list.add(newFileStorage.getId());

            AttachmentDto attachmentDto = AttachmentDto.builder()
                    .setEntityId(contractTemplate.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.CONTRACT_TEMPLATE_FILE)
                    .build();
            sysAttachmentRefService.saveRef(list, attachmentDto);
        }
    }

    private void getFileFromSop(Long file, File destFile) {
        CloseableHttpClient httpclient = CloseableHttpClientUtils.getHttpClient();

        HttpPost request = new HttpPost(getFileUrl + "?fileId=" + file);
        HttpResponse response;
        try {
            response = httpclient.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                InputStream input = response.getEntity().getContent();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOUtils.copy(input, baos);
                FileUtils.writeByteArrayToFile(destFile, baos.toByteArray());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
