package com.cusc.nirvana.user.rnr.fp.client;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import com.cusc.nirvana.user.rnr.fp.common.constant.UserRnrFpConstant;
import com.cusc.nirvana.user.rnr.fp.dto.FileDownloadDTO;
import com.cusc.nirvana.user.rnr.fp.dto.FileRecordDTO;
import com.cusc.nirvana.user.rnr.fp.dto.FileUploadDTO;
import com.cusc.nirvana.user.rnr.fp.dto.ImageBase64DTO;
import com.cusc.nirvana.user.rnr.fp.util.RnrFpRestTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Type;


/**
 * 文件系统 client
 * @author stayand
 */
@Component
@Slf4j
public class FileSystemClient {

    @Autowired
    @Qualifier("restTemplateRnrFp")
    RestTemplate restTemplateRnrFp;


    /**
     * 获取文件大小
     *
     * @param
     */
    public Response<FileRecordDTO> getFileSize(FileRecordDTO dto) {
        return RnrFpRestTemplateUtils.postForResponse(restTemplateRnrFp,
                UserRnrFpConstant.USER_RNR_FP_URL + "/file/getFileSize", dto, FileRecordDTO.class);
    }

    public Response<ImageBase64DTO> getBase64(FileDownloadDTO fileDownloadDTO) {
        return RnrFpRestTemplateUtils.postForResponse(restTemplateRnrFp,
                UserRnrFpConstant.USER_RNR_FP_URL + "/file/getBase64", fileDownloadDTO, ImageBase64DTO.class);
    }


	public Response<FileRecordDTO> getUrl(@RequestBody FileDownloadDTO fileDownloadDTO){
		return RnrFpRestTemplateUtils.postForResponse(restTemplateRnrFp,
				UserRnrFpConstant.USER_RNR_FP_URL + "/file/getUrl", fileDownloadDTO, FileRecordDTO.class);
	}




    public Response uploadImage(FileUploadDTO fileUploadDTO) {
        String url = UserRnrFpConstant.USER_RNR_FP_URL + "/file/uploadImage";
		ResponseEntity<String> entity = execute(fileUploadDTO, url);

		Response<FileRecordDTO> response = JSONObject.parseObject(entity.getBody(),
                new TypeReference<Response<FileRecordDTO>>(new Type[]{FileRecordDTO.class}) {
                }.getType());
        return response;
    }

	public Response uploadFile(FileUploadDTO fileUploadDTO) {
		String url = UserRnrFpConstant.USER_RNR_FP_URL + "/file/uploadFile";
		ResponseEntity<String> entity = execute(fileUploadDTO, url);

		Response<FileRecordDTO> response = JSONObject.parseObject(entity.getBody(),
				new TypeReference<Response<FileRecordDTO>>(new Type[]{FileRecordDTO.class}) {
				}.getType());
		return response;
	}


    private ResponseEntity<String> execute(FileUploadDTO fileUploadDTO,String url){
		MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
		final HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.MULTIPART_FORM_DATA);
		ByteArrayResource resource = null;
		try {
			//存储
			resource = new ByteArrayResource(fileUploadDTO.getFile().getBytes()) {
				@Override
				public String getFilename() {
					return fileUploadDTO.getFile().getOriginalFilename();
				}
			};
		} catch (Exception e) {
			log.error("uploadImage error:", e.getMessage(), e);
			throw new CuscUserException(ResponseCode.SYSTEM_ERROR.getCode(),"上传文件失败");
		}
		parameters.add("file", resource);

		final HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parameters, headers);
		final ResponseEntity<String> entity = restTemplateRnrFp.exchange(url, HttpMethod.POST, httpEntity, String.class);
		log.info("FileUpload, url:{},parameter:{},response:{}", url, fileUploadDTO,
				entity.toString());
		return entity;
	}
}
