package com.docus.server.common.service.impl;

import com.docus.core.util.Func;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.server.common.entity.RemoteCallResult;
import com.docus.server.common.mapper.RemoteCallResultMapper;
import com.docus.server.common.service.RemoteCallResultService;
import com.docus.server.common.util.FileUtil;
import org.springframework.stereotype.Service;

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

/**
 * 远程调用存储服务业务实现
 *
 * @author wyb
 */
@Service
public class RemoteCallResultServiceImpl implements RemoteCallResultService {
    @Resource
    private IdService idService;
    @Resource
    private RemoteCallResultMapper remoteCallResultMapper;

    private final static int SAVE_DISK_DATA_LENGTH = 1024;

    private final static String REMOTE_CALL_SAVE_PATH = FileUtil.currentPath() + File.separator + "remote-call";

    @Override
    public void save(RemoteCallResult remoteCallResult) {
        remoteCallResult.setRequestStorageType(0);
        remoteCallResult.setResponseStorageType(0);

        Long id = remoteCallResult.getId() == null ? idService.getDateSeq() : remoteCallResult.getId();
        remoteCallResult.setId(id);
        String request = remoteCallResult.getRequest();
        String response = remoteCallResult.getResponse();
        if (Func.isNotBlank(request) && request.length() > SAVE_DISK_DATA_LENGTH) {
            String saveReqPath = REMOTE_CALL_SAVE_PATH + File.separator + id + "_request";
            FileUtil.saveStrData(response, new File(saveReqPath));
            remoteCallResult.setRequestStorageType(1);
            remoteCallResult.setRequest(saveReqPath);
        }
        if (Func.isNotBlank(response) && response.length() > SAVE_DISK_DATA_LENGTH) {
            String saveRespPath = REMOTE_CALL_SAVE_PATH + File.separator + id + "_response";
            FileUtil.saveStrData(response, new File(saveRespPath));
            remoteCallResult.setResponseStorageType(1);
            remoteCallResult.setResponse(saveRespPath);
        }
        remoteCallResultMapper.save(remoteCallResult);
    }
}
