package com.yifu.cloud.plus.v1.yifu.ekp.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.ekp.config.EkpOrderProperties;
import com.yifu.cloud.plus.v1.yifu.ekp.constant.EkpConstants;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpOrderParam;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpOrderReplyParam;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author licancan
 * @description 对接ekp订
 * @date 2022-08-31 15:35:20
 */
@Log4j2
@EnableConfigurationProperties(EkpOrderProperties.class)
@Component
public class EkpOrderUtil {
	@Autowired
	private EkpOrderProperties ekpProperties;

	/**
	 * 更新订单状态
	 *
	 * @author licancan
	 * @param param
	 * @return {@link String}
	 */
	public String sendOrderToEKP(EkpOrderParam param){
		log.info("推送EKP开始--订单状态");
		RestTemplate yourRestTemplate = new RestTemplate();
		try{
			String formValues = new ObjectMapper().writeValueAsString(param);
			//指向EKP的接口url
			//把ModelingAppModelParameterAddForm转换成MultiValueMap
			MultiValueMap<String,Object> wholeForm = new LinkedMultiValueMap<>();
			wholeForm.add("docSubject",ekpProperties.getOrderDocSubject());
			wholeForm.add("docCreator", "{\"LoginName\":\"admin\"}");
			wholeForm.add("docStatus", ekpProperties.getDocStatus());
			wholeForm.add("fdModelId", ekpProperties.getOrderFdModelId());
			wholeForm.add("fdFlowId", ekpProperties.getOrderFdFlowId());
			wholeForm.add("formValues", formValues);
			log.info("wholeForm:" + wholeForm);
			HttpHeaders headers = new HttpHeaders();
			//如果EKP对该接口启用了Basic认证，那么客户端需要加入
			//addAuth(headers,"yourAccount"+":"+"yourPassword");是VO，则使用APPLICATION_JSON
			headers.setContentType(MediaType.MULTIPART_FORM_DATA);
			//必须设置上传类型，如果入参是字符串，使用MediaType.TEXT_PLAIN；如果
			HttpEntity<MultiValueMap<String,Object>> entity = new HttpEntity<MultiValueMap<String,Object>>(wholeForm,headers);
			//有返回值的情况 VO可以替换成具体的JavaBean
			ResponseEntity<String> obj = yourRestTemplate.exchange(ekpProperties.getUrl(), HttpMethod.POST, entity, String.class);
			String body = obj.getBody();
			if (StringUtils.isBlank(body)){
				log.error(EkpConstants.SEND_FAILED);
				return null;
			}else{
				log.info(EkpConstants.SEND_SUCCESS + body);
				return body;
			}
		}catch (Exception e){
			log.error(e);
			return null;
		}
	}

	/**
	 * 推送订单回复
	 *
	 * @author licancan
	 * @param param
	 * @return {@link String}
	 */
	public String sendReplyToEKP(EkpOrderReplyParam param, MultipartFile[] multipartFiles){
		log.info("推送EKP开始--订单回复信息");
		RestTemplate yourRestTemplate = new RestTemplate();
		List<File> fileList = new ArrayList<>();
		try{
			String formValues = new ObjectMapper().writeValueAsString(param);
			//指向EKP的接口url
			//把ModelingAppModelParameterAddForm转换成MultiValueMap
			MultiValueMap<String,Object> wholeForm = new LinkedMultiValueMap<>();
			wholeForm.add("docSubject",ekpProperties.getReplyDocSubject());
			wholeForm.add("docCreator", "{\"LoginName\":\"admin\"}");
			wholeForm.add("docStatus", ekpProperties.getDocStatus());
			wholeForm.add("fdModelId", ekpProperties.getReplyFdModelId());
			wholeForm.add("fdFlowId", ekpProperties.getReplyFdFlowId());
			wholeForm.add("formValues", formValues);
			if (ArrayUtils.isNotEmpty(multipartFiles)){
				for (int i = 0; i < multipartFiles.length; i++) {
					String fileName = multipartFiles[i].getOriginalFilename();
					File file = new File(fileName);
					FileUtils.copyInputStreamToFile(multipartFiles[i].getInputStream(), file);
					wholeForm.add("attachmentForms["+i+"].fdKey", ekpProperties.getReplyAttachKey());
					wholeForm.add("attachmentForms["+i+"].fdFileName", multipartFiles[i].getOriginalFilename());
					wholeForm.add("attachmentForms["+i+"].fdAttachment", new FileSystemResource(file));
					fileList.add(file);
				}
			}

			log.info("wholeForm:" + wholeForm);
			HttpHeaders headers = new HttpHeaders();
			//如果EKP对该接口启用了Basic认证，那么客户端需要加入
			//addAuth(headers,"yourAccount"+":"+"yourPassword");是VO，则使用APPLICATION_JSON
			headers.setContentType(MediaType.MULTIPART_FORM_DATA);
			//必须设置上传类型，如果入参是字符串，使用MediaType.TEXT_PLAIN；如果
			HttpEntity<MultiValueMap<String,Object>> entity = new HttpEntity<MultiValueMap<String,Object>>(wholeForm,headers);
			//有返回值的情况 VO可以替换成具体的JavaBean
			ResponseEntity<String> obj = yourRestTemplate.exchange(ekpProperties.getUrl(), HttpMethod.POST, entity, String.class);
			String body = obj.getBody();
			if (StringUtils.isBlank(body)){
				log.error(EkpConstants.SEND_FAILED);
				return null;
			}else{
				log.info(EkpConstants.SEND_SUCCESS + body);
				return body;
			}
		}catch (Exception e){
			log.error(e);
			return null;
		}finally {
			//将产生的临时附件删除，这里的fileList没值得话是[]，不会是null，如果是null需要做判空处理
			fileList.stream().forEach(e -> {
				boolean delete = e.delete();
				log.info("临时附件删除结果：{}",delete);
			});
		}
	}
	/**
	 * @Author fxj
	 * @Description 同步项目订单的附件信息（含删除的附件）
	 * @Date 15:10 2024/11/15
	 * @Param
	 * @return
	 **/
	public String syncFileFromEkp(String orderNo, String attIds){
		log.info("同步项目订单附件信息");
		RestTemplate yourRestTemplate = new RestTemplate();
		try{
			HttpHeaders headers = new HttpHeaders();
			//如果EKP对该接口启用了Basic认证，那么客户端需要加入
			//addAuth(headers,"yourAccount"+":"+"yourPassword");是VO，则使用APPLICATION_JSON
			headers.setContentType(MediaType.MULTIPART_FORM_DATA);
			//必须设置上传类型，如果入参是字符串，使用MediaType.TEXT_PLAIN；如果
			HttpEntity<Map<String,Object>> entity = new HttpEntity<Map<String,Object>>(null,headers);
			//有返回值的情况 VO可以替换成具体的JavaBean
			log.error("附件同步结果"+ekpProperties.getUrl());
			ResponseEntity<String> obj = yourRestTemplate.exchange(ekpProperties.getUrl2()+"?addIds="+attIds+"&orderNo="+orderNo, HttpMethod.POST, null, String.class);
			log.error("附件同步结果："+ JSONObject.toJSONString(obj));
			String body = obj.getBody();
			if (!"推送成功".equals(body)){
				log.error(EkpConstants.SEND_FAILED);
				return EkpConstants.SEND_FAILED;
			}else{
				log.info(EkpConstants.SEND_SUCCESS + body);
				return null;
			}
		}catch (Exception e){
			log.error(e);
			return "项目订单附件同步异常："+e.getMessage();
		}
	}
}
