package nc.impl.hr.train;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

import com.alibaba.fastjson.JSONObject;

import nc.hrhi.httpUtil.MySecureProtocolSocketFactory;
import nc.vo.pub.BusinessException;

public class TrainCloudSchoolImpl {
	
	private static Properties props = new Properties(); 
	
	static {
		try {
			if (props.size() <= 0) {
				ClassLoader classLoader = new Object() {}.getClass().getClassLoader();
				URL url = classLoader.getResource("cloudapi.properties");
				FileInputStream in = new FileInputStream(url.getFile());
				props.load(in);
			}
		} catch (IOException e) {
			
		}
	}
	
	public String getUrl() {
		return props.getProperty("cloudapi.url");
	}
	
	/**
	 * 获取表头处理数据
	 * @return
	 */
	public Map<String,Object> getBodyMap() {
        Map<String, Object> body = new HashMap();
        String apikey = props.getProperty("cloudapi.apikey");//"21d0b041-13d4-4670-a107-626443693182";// 从云学堂客服获取
        String salt = String.valueOf(new Date().getTime()).substring(0, 6);;// 随机数，为api的每个请求随机生成的字符串，最短3位，最长32位
        String secretKey =  props.getProperty("cloudapi.secretKey");//"552333e8-36b7-4eb1-a131-4aa63004e92b";//从云学堂客服获取
        String signature = DigestUtils.sha256Hex(secretKey + salt);//将secretKey salt 2个字符串按先后顺序拼接成一个字符串并进行SHA-256哈希计算
        body.put("apikey", apikey);
        body.put("salt", salt);
        body.put("signature", signature);
        return body;
    }
	/**
     * 从输入流中读取数据
     * 
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }
	/**
	 * 根据传参数调用不一样的云学堂接口
	 * @param bodyMap
	 * @param url
	 * @return
	 */
	public String getCouldSchool(Map<String,Object> bodyMap,String url) throws BusinessException{
		String result = "";
		String bodyString = JSONObject.toJSONString(bodyMap);
		try {
			byte[] requestBytes = bodyString.getBytes("utf-8"); // 将参数转为二进制流
	        HttpClient httpClient = new HttpClient();// 客户端实例化
	        PostMethod postMethod = new PostMethod(url);
	        //设置请求头Authorization
	//        postMethod.setRequestHeader("Authorization", "Basic " + authorization);
	        // 设置请求头  Content-Type
	        postMethod.setRequestHeader("Content-Type", "application/json");
	        InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
	                requestBytes.length);
	        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
	                requestBytes.length, "application/json; charset=utf-8"); // 请求体
	        postMethod.setRequestEntity(requestEntity);
	        httpClient.executeMethod(postMethod);// 执行请求
	        InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
	        byte[] datas = null;
            datas = readInputStream(soapResponseStream);// 从输入流中读取数据
            // 将二进制流转为String
            result = new String(datas, "UTF-8");
        } catch (Exception e) {
            System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
		}
        return result;
		
//        try {
////            OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(500000, TimeUnit.MILLISECONDS).build();
////            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
////            RequestBody requestBody = RequestBody.create(mediaType, bodyString);
////            Request request = new Request.Builder().headers(Headers.of(new HashMap<>(1))).url(url).post(requestBody).build();
////            Response response = client.newBuilder().readTimeout(500000L, TimeUnit.MILLISECONDS).build().newCall(request).execute();
////            result = response.body().string();
//        	OkHttpClient client = SSLSocketClient.OkHttpClientgetUnsafeOkHttpClient().newBuilder()
//        			.sslSocketFactory(SSLSocketClient.getSSLSocketFactory())//配置
//        			.hostnameVerifier(SSLSocketClient.getHostnameVerifier())//配置
//        			.readTimeout(500000, TimeUnit.MILLISECONDS)
//        			  .build().connectionSpecs(Collections.singletonList(spec));
//        	
//        			MediaType mediaType = MediaType.parse("application/json");
//        			RequestBody body = RequestBody.create(mediaType, bodyString);
//        			Request request = new Request.Builder()
//        			  .url(url)
//        			  .method("POST", body)
//        			  .addHeader("Content-Type", "application/json")
//        			  .build();
//        			Response response = client.newBuilder().readTimeout(500000L, TimeUnit.MILLISECONDS).build().newCall(request).execute();
//        			result = response.body().string();
//        } catch (Exception e) {
//            System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
//            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
//        }
//        return result;
	}
	
	/**
	 * 根据传参数调用不一样的云学堂接口
	 * @param bodyMap
	 * @param url
	 * @return
	 */
	public String getCouldSchool2(Map<String,Object> bodyMap,String url) throws BusinessException{
		String result = "";
		String bodyString = JSONObject.toJSONString(bodyMap);
		//声明
		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
		//加入相关的https请求方式
		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		//发送请求即可
		org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient();
		PostMethod postMethod = new PostMethod(url);
		try {
			byte[] requestBytes = bodyString.getBytes("utf-8"); // 将参数转为二进制流
	        postMethod.setRequestHeader("Content-Type", "application/json");
	        InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
	                requestBytes.length);
	        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
	                requestBytes.length, "application/json; charset=utf-8"); // 请求体
	        postMethod.setRequestEntity(requestEntity);
	        httpclient.executeMethod(postMethod);// 执行请求
	        InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
	        byte[] datas = null;
            datas = readInputStream(soapResponseStream);// 从输入流中读取数据
            // 将二进制流转为String
            result = new String(datas, "UTF-8");
		} catch (Exception e) {
            System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
		} finally {
			postMethod.releaseConnection();
		}
        return result;
	}
	
	/**
	 * 获取用户列表数据
	 * @param bodyMap
	 * @return
	 */
	public String getUserList(Map<String,Object> bodyMap) throws BusinessException{
		String result = "";
//		bodyMap.put("pageNo", 1);
//		bodyMap.put("updateDate", new UFDate().toDate());//此处是添加接口所需传入参数
		String bodyString = JSONObject.toJSONString(bodyMap);
		String qurl = getUrl();
        // 阿里环境域名http://sdcs-api-dpbc1.yunxuetang.cn/v1 ;
        // ucloud环境域名 http://sdcs-api-dpb.yunxuetang.cn/v1 ;
		//测试http://sdcs-api-dpb.yunxuetang.com.cn
        String url = qurl + "/v1/customdata/users";
        try {
        	result = getCouldSchool(bodyMap,url);
        } catch (Exception e) {
        	System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
        }
        return result;
	}
	
	/**
	 * 学习计划执行明细（分页）（学习计划）
	 * @param bodyMap
	 * @param curPage 当前页
	 * @param pageSize 每页大小
	 * @return
	 * @throws BusinessException 
	 */
	public String getStudyplandetailpagelist(Map<String,Object> bodyMap,int curPage,int pageSize) throws BusinessException {
		String result = "";
		bodyMap.put("curPage", curPage);//当前页
		bodyMap.put("pageSize", pageSize);//每页大小
//		bodyMap.put("updateDate", new UFDate().toDate());//员工学习知识的最新日期(用于获取增量数据，员工最新学习时间大于等于该日期的数据)，示例：2017-10-01
//		bodyMap.put("updateEndDate", new UFDate().toDate());//更新结束时间，查询从更新开始日期到更新结束日期之间有过更新或新增操作的数据
//		bodyMap.put("planID", "");//学习计划id 不是必输项
//		bodyMap.put("userId", "");//用户id（不必填）
//		bodyMap.put("status", "");//状态，枚举（未学习NoStart；学习中Studying；已完成 Completed） 不是必输项
		String bodyString = JSONObject.toJSONString(bodyMap);
		String qurl = getUrl();
		String url = qurl + "/v1/studyplans/studyplandetailpagelist";
        try {
        	result = getCouldSchool(bodyMap,url);
        } catch (Exception e) {
        	System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
        }
        return result;
	}
	
	/**
	 * 所有培训课程（分页）
	 * @param bodyMap
	 * @param curPage
	 * @param pageSize
	 * @return
	 * @throws BusinessException 
	 */
	public String gettrainingcontentlistpage(Map<String,Object> bodyMap,int curPage,int pageSize) throws BusinessException {
		String result = "";
		bodyMap.put("curPage", curPage);//当前页
		bodyMap.put("pageSize", pageSize);//每页大小
//		bodyMap.put("updateDate", new UFDate().toDate());//培训课程更新日期 例如2020-01-01
//		bodyMap.put("trainingID", "");//更培训ID 不是必输项
		String bodyString = JSONObject.toJSONString(bodyMap);
		String qurl = getUrl();
		String url = qurl + "/v1/training/gettrainingcontentlistpage";
        try {
        	result = getCouldSchool(bodyMap,url);
        } catch (Exception e) {
        	System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
        }
        return result;
	}
	
	/**
	 * 培训课程完成情况(线下培训)
	 * @param bodyMap
	 * @param curPage
	 * @param pageSize
	 * @param trainContentID
	 * @return
	 * @throws BusinessException 
	 */
	public String getcontentfinshdetaillist(Map<String,Object> bodyMap,int curPage,int pageSize,String trainContentID) throws BusinessException {
		String result = "";
		bodyMap.put("curPage", curPage);//当前页
		bodyMap.put("pageSize", pageSize);//每页大小
//		bodyMap.put("updateDate", new UFDate().toDate());//培训课程更新日期 例如2020-01-01
		bodyMap.put("trainContentID", trainContentID);//培训内容id 必填
		String qurl = getUrl();
		String url = qurl + "/v1/training/getcontentfinshdetaillist";
		String bodyString = JSONObject.toJSONString(bodyMap);
        try {
        	result = getCouldSchool(bodyMap,url);
        } catch (Exception e) {
        	System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
        }
        return result;
	}
	
	/**
	 * 获取知识目录列表
	 * @param bodyMap
	 * @param curPage
	 * @param pageSize
	 * @return
	 * @throws BusinessException 
	 */
	public String getKngcatalogs(Map<String,Object> bodyMap,int curPage,int pageSize) throws BusinessException {
		String result = "";
//		bodyMap.put("curPage", curPage);//当前页
//		bodyMap.put("pageSize", pageSize);//每页大小
//		bodyMap.put("updateDate", new UFDate().toDate());//培训课程更新日期 例如2020-01-01
//		bodyMap.put("trainContentID", trainContentID);//培训内容id 必填
		String qurl = getUrl();
		String url = qurl + "/v1/customdata/knowledges/kngcatalogs";
		String bodyString = JSONObject.toJSONString(bodyMap);
        try {
        	result = getCouldSchool(bodyMap,url);
        } catch (Exception e) {
        	System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
        }
        return result;
	}
	
	/**
	 * 获取知识列表
	 * @param bodyMap
	 * @param curPage
	 * @param pageSize
	 * @return
	 * @throws BusinessException 
	 */
	public String getKnowledges(Map<String,Object> bodyMap,int curPage,int pageSize) throws BusinessException {
		String result = "";
		String qurl = getUrl();
		String url = qurl + "/v1/customdata/knowledges";
		String bodyString = JSONObject.toJSONString(bodyMap);
        try {
        	result = getCouldSchool(bodyMap,url);
        } catch (Exception e) {
        	System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
        }
        return result;
	}

	/**
	 * 员工所有线上学习记录  所有用户线上学习记录，包含自主学习、学习计划、岗位学习、混合式学习等，并包含课程包明细
	 * @param bodyMap
	 * @param curPage
	 * @param pageSize
	 * @return
	 * @throws BusinessException 
	 */
	public String getOnlineuserknowledge(Map<String,Object> bodyMap,int curPage,int pageSize) throws BusinessException {
		String result = "";
		bodyMap.put("curPage", curPage);//当前页
		bodyMap.put("pageSize", pageSize);//每页大小
//		updateDate 更新开始时间
//		updateEndDate 更新结束时间 时间间隔不超过一个月，数据量大，建议最好按天查询
		String bodyString = JSONObject.toJSONString(bodyMap);
		
		String qurl = getUrl();
		String url = qurl + "/v1/knowledge/getonlineuserknowledge";
        try {
        	result = getCouldSchool(bodyMap,url);
        } catch (Exception e) {
        	System.out.println("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
            throw new BusinessException("执行包含头部的post请求,body:" + bodyString + ",url:" + url + ",执行错误信息:" + e);
        }
        return result;
	}
	
}
