package com.sw.mes.jip.service.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.annotation.Jinko;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.utils.JwtUtil;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.jip.dao.JipHeaderConfigDao;
import com.sw.mes.jip.dto.JipParamsDto;
import com.sw.mes.jip.dto.TokenDto;
import com.sw.mes.jip.entity.JipHeaderConfig;
import com.sw.mes.jip.service.JipHeaderConfigService;

import lombok.extern.slf4j.Slf4j;

/**
 * 晶科JIP接口配置信息Service业务层处理
 * 
 * @author liru
 * @date 2024-01-01
 */
@Slf4j
@Service
@Transactional
@Jinko(value="晶科JIP接口配置信息Service业务层处理",author = "liru")
public class JipHeaderConfigServiceImpl extends BaseServiceImpl<JipHeaderConfig> implements JipHeaderConfigService
{
    private JipHeaderConfigDao dao;
    
    @Autowired
    private DiscoveryClient discoveryClient;
    
    @Autowired
    RestTemplate restTemplate;
    

    @Autowired
    public void setDao(JipHeaderConfigDao dao) {
        super.setBaseDao(dao);
        this.dao=dao;
    }

    @Override
    public JipHeaderConfig getByIfId(String ifId) {
        List<JipHeaderConfig> configs = dao.findByIfId(ifId);
        if(configs.size()>0)
            return configs.get(0);
        return null;
    }

    @Override
    public JipHeaderConfig getByKeyword(String keyword) {
        List<JipHeaderConfig> configs = dao.findByKeyword(keyword);
        if(configs.size()>0)
            return configs.get(0);
        return null;
    }
    
    @Override
    public JSONObject httpRequestJip(String url, JSONObject json, TokenDto token){
    	// 获取所有服务的名称
//        List<String> services = discoveryClient.getServices();
        // 只关注某一个mes-pc-serve服务
        String serviceId = "mes-pc-server"; // 替换为你的服务ID
        // 获取圆棒服务的所有实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        // 将实例转换为字符串列表，根据需要进行字段选择
        List<String> instanceStrings = instances.stream()
                .map(instance -> instance.getHost() + ":" + instance.getPort())
                .collect(Collectors.toList());
        
        //按字符串字典顺序排序,请求顺序
        Collections.sort(instanceStrings, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
        });
        
        //获取第一个请求实例
        if(instanceStrings.size()>0) {
        	String instnceString = instanceStrings.get(0);
        	String instanceUrl = "http://"+instnceString + "/mes/config/sendRequest";
        	//instanceUrl = "http://127.0.0.1:9009/mes/config/sendRequest";
        	JipParamsDto params = new JipParamsDto();
        	params.setJson(json);
        	params.setToken(token);
        	params.setUrl(url);
        	
        	
        	HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            //判断是否设置秘钥
            headers.add("token", "token_admin");

            HttpEntity<JipParamsDto> request = new HttpEntity(params, headers);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(instanceUrl, request, JSONObject.class);
            serverIsRight(responseEntity);  //判断服务器返回状态码
            return responseEntity.getBody();
        }else {
        	throw new BusinessException("Nacos无请求实例");
        }
        
    }
    
    
    private static void serverIsRight(ResponseEntity responseEntity) {
        if (responseEntity.getStatusCodeValue() == 200) {
        } else {
            log.error("serverIsRight_error", JSON.toJSONString(responseEntity));
            //System.out.println("服务器请求异常：{}" + responseEntity.getStatusCodeValue());
            throw new RuntimeException("Nacos服务器请求异常：{}" + responseEntity.getStatusCodeValue());
        }
    }
    
}
