using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PTMedicalInsurance.Helper
{
    class InvokeRestCenter : IInvokeCenter
    {
        public int Business(string inputData, ref string outputData, ref string pErrMsg)
        {
            outputData = "";
            pErrMsg = "";
            JObject joRtn = new JObject();
            try
            {
                //创建一个HTTP请求  
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.inf.centerURL);
                //Post请求方式  
                request.Method = "POST";
                //string nonce = Guid.NewGuid().ToString();         //非重复的随机字符串（十分钟内不能重复）
                //string timestamp = TimeStamp.get13().ToString();  //当前时间戳（秒）
                //string BusinessID = Global.inf.BusinessID;        //服务商ID
                //string InsuHosID = Global.inf.hospitalNO;         //医疗机构ID
                //string CreditID = Global.inf.CreditID;            //服务商统一社会信用代码                

                //内容类型
                request.ContentType = "application/json";

                //昆明增加头部信息
                //string sTemp = timestamp + BusinessID + nonce;
                //Sha256 加密生成的签名 signature = sha256(hsf_timestamp + infosyssign + hsf_nonce)
                //string signature = Encrypt.SHA256EncryptStr(sTemp);

                //request.Headers.Add("hsf_signature", signature);
                //request.Headers.Add("hsf_timestamp", timestamp);
                //request.Headers.Add("hsf_nonce", nonce);
                //request.Headers.Add("fixmedins_code", InsuHosID);
                //request.Headers.Add("infosyscode", CreditID);

                //设置参数，并进行URL编码 
                string paraUrlCoded = inputData;//System.Web.HttpUtility.UrlEncode(jsonParas);   
                byte[] payload;
                //将Json字符串转化为字节  
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                //设置请求的ContentLength   
                request.ContentLength = payload.Length;
                //发送请求，获得请求流 
                Stream writer;
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
                                                    //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                writer.Close();//关闭请求流
                               // String strValue = "";//strValue为http响应所返回的字符流
                HttpWebResponse response = null;
                try
                {
                    //获得响应流
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (Exception ex)
                {
                    JsonHelper.setExceptionJson(-99, "centerServeiceInvok中获得响应流异常", ex.Message);
                    return -1;
                }
                outputData = getResponseData(response);
                joRtn = JObject.Parse(outputData);//返回Json数据
                if (joRtn.ContainsKey("body"))
                {
                    joRtn = (JObject)joRtn.GetValue("body");
                    outputData = JsonHelper.toJsonString(joRtn);
                }
                return 0;
            }
            catch (Exception ex)
            {
                joRtn.Add("infcode", -1);
                joRtn.Add("err_msg", "调用中心服务异常invokeCenterService(1):" + ex.Message);
                outputData = JsonHelper.toJsonString(joRtn); 
                return -1;
            }
            finally
            {
                Global.writeLog(Global.inf.centerURL, inputData, outputData);
            }
        }

        public int BusinessExt(string inputData, ref string outputData, ref string pErrMsg)
        {
            return this.Business(inputData, ref outputData, ref pErrMsg);
        }

        public int DownloadFile(string inputData, ref string outputData)
        {
            outputData = "";
            string error = string.Empty; int errorCode = 0;
            try
            {
                JObject jsonInParam = JObject.Parse(inputData);
                // 去除外wrapper层便于通用
                Utils.removeWrapper(jsonInParam);

                string fileName = (string)jsonInParam["input"]["fsDownloadIn"]["filename"];
                string filePath = Global.curEvt.path + "\\Download\\" + fileName;

                //如果不存在目录，则创建目录
                if (!Directory.Exists(Global.curEvt.path + "\\Download"))
                {
                    //创建文件夹
                    DirectoryInfo dirInfo = Directory.CreateDirectory(Global.curEvt.path + "\\Download");
                }
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                //创建一个HTTP请求  
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL);

                //Post请求方式  
                request.Method = "POST";
                //string timestamp = TimeStamp.get13().ToString();  //当前时间戳（秒）
                //string nonce = Guid.NewGuid().ToString();         //非重复的随机字符串（十分钟内不能重复）
                //string InsuHosID = Global.inf.hospitalNO;         //医疗机构ID
                //string CreditID = Global.inf.CreditID;            //服务商统一社会信用代码
                //string BusinessID = Global.inf.BusinessID;        //服务商ID
                //内容类型
                request.ContentType = "application/json";

                //昆明增加头部信息
                //string sTemp = timestamp + BusinessID + nonce;
                //Sha256 加密生成的签名 signature = sha256(hsf_timestamp + infosyssign + hsf_nonce)
                //string signature = Encrypt.SHA256EncryptStr(sTemp);

                //request.Headers.Add("hsf_signature", signature);
                //request.Headers.Add("hsf_timestamp", timestamp);
                //request.Headers.Add("hsf_nonce", nonce);
                //request.Headers.Add("fixmedins_code", InsuHosID);
                //request.Headers.Add("infosyscode", CreditID);

                //设置参数，并进行URL编码 
                string paraUrlCoded = JsonHelper.toJsonString(jsonInParam);
                byte[] payload;
                //将Json字符串转化为字节  
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                //设置请求的ContentLength   
                request.ContentLength = payload.Length;
                Stream writer;
                try
                {
                    writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
                }
                catch (Exception)
                {
                    writer = null;
                    errorCode = -100;
                    error = "连接服务器失败!";
                }
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                writer.Close();//关闭请求流
                               // String strValue = "";//strValue为http响应所返回的字符流
                               //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                //创建本地文件写入流
                byte[] bArr = new byte[1024];
                int iTotalSize = 0;
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    iTotalSize += size;
                    fs.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                fs.Close();
                responseStream.Close();
                dynamic joReturn = new JObject();
                joReturn.errorCode = errorCode;
                joReturn.errorMessage = error;
                joReturn.filePath = filePath;
                outputData = joReturn.ToString();
            }
            catch (Exception ex)
            {
                errorCode = -100;
                error = ex.Message;
                dynamic joReturn = new JObject();
                joReturn.errorCode = errorCode;
                joReturn.errorMessage = error;
                outputData = joReturn.ToString();
                return -1;
            }
            finally
            {
                Global.writeLog("DownloadCenterFile" + "(" + Global.curEvt.URL + ")", inputData, outputData);
            }
            return 0;
        }
        public int DownloadPDF(string inputData, string filePath, out string errMsg)
        {
            errMsg = "";
            try
            {
                JObject jsonInParam = JObject.Parse(inputData);
                // 去除外wrapper层便于通用
                Utils.removeWrapper(jsonInParam);

                //如果不存在目录，则创建目录
                if (!Directory.Exists(Global.curEvt.path + "\\Download"))
                {
                    //创建文件夹
                    DirectoryInfo dirInfo = Directory.CreateDirectory(Global.curEvt.path + "\\Download");
                }
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                //创建一个HTTP请求  
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.inf.centerURL);

                //Post请求方式  
                request.Method = "POST";
                //内容类型
                request.ContentType = "application/json";

                //设置参数，并进行URL编码 
                string paraUrlCoded = JsonHelper.toJsonString(jsonInParam);
                byte[] payload;
                //将Json字符串转化为字节  
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                //设置请求的ContentLength   
                request.ContentLength = payload.Length;
                Stream writer;
                try
                {
                    writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
                }
                catch (Exception)
                {
                    writer = null;
                    errMsg = "连接服务器失败!";
                    return -1;
                }
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                writer.Close();//关闭请求流
                               // String strValue = "";//strValue为http响应所返回的字符流
                               //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                //创建本地文件写入流
                byte[] bArr = new byte[1024];
                int iTotalSize = 0;
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    iTotalSize += size;
                    fs.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                fs.Close();
                responseStream.Close();
                errMsg = filePath;
                return 0;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return -1;
            }
            finally
            {
                Global.writeLog("DownloadPDF" + "(" + Global.inf.centerURL + ")", inputData,  errMsg);
            }

        }
        public int Init(ref string pErrMsg)
        {
            return 0;
        }

        public int UploadFile(string inputData, ref string outputData, ref string pErrMsg)
        {
            throw new NotImplementedException();
        }


        private string getResponseData(HttpWebResponse response)
        {
            string data = "";
            if (response != null)
            {
                Stream s = response.GetResponseStream();
                StreamReader sRead = new StreamReader(s);
                data = sRead.ReadToEnd();
                sRead.Close();
                response.Close();
            }
            return data;
        }

    }
}
