using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace PTMedicalInsurance.Helper
{
    class InvokeDllCenter : IInvokeCenter
    {
        public int Business(string inputData, ref string outputData, ref string pErrMsg)
        {
            pErrMsg = "";
            outputData = "";
            string method = Global.curEvt.funNo;

            try
            {
                inputData = inputData.Replace("\n", "").Replace("\t", "").Replace("\r", "");
                Global.curEvt.msgid = Global.inf.hospitalNO + DateTime.Now.ToString("yyyyMMddHHmmssffff");

                //调用业务函数
                //StringBuilder sbOut = new StringBuilder(4096000);
                //insuplc_admdvs 社保清算机构(参保地)
                string orgCode = Utils.GetInsuCode();
                if (!Utils.isOtherCity())
                {
                    //如果是本地人员,除read_card和query_basic_info这两个接口传”000000”之外,其他与参保人相关的交易接口中sbjgbh必须传read_card和query_basic_info接口中返回的sbjgbh值
                    if (("read_card".Equals(method)) || ("query_basic_info".Equals(method)))
                    {
                        orgCode = "000000"; //市内(本地)
                    }
                }
                else
                {
                    orgCode = "37000000"; //跨省、省内异地
                    if (Utils.isOtherProvice() && "read_card".Equals(method)) {
                        method = "read_card_qgyd"; //全国异地读卡
                    }
                    // 省医保
                    if (Global.inf.interfaceDr == 28)
                    {
                        orgCode = Global.pat.insuplc_admdvs;  //参保地
                    }
                }
                
                string userCode = Global.user.ID;
                string tradeNo = Global.curEvt.msgid;
                string hospCode = Utils.GetInsuOrgCode();

                int pRtn = 0;
                // com调用
                //cressWSDLLLib.DWCressCom comCls = new cressWSDLLLib.DWCressCom();
                //outputData = comCls.f_invoke_cress_com(orgCode, hospCode, tradeNo, method, inputData, hospCode);

                // dll调用
                //pRtn = BusinessHandle(orgCode, userCode, tradeNo, method, inputData, hospCode, ref outputData);
                //outputData = sbOut.ToString();
                return pRtn;
            }
            catch (Exception ex)
            {
                pErrMsg = "业务函数["+method+"]异常:" + ex.Message;
                return -1;
            }
            finally
            {
                Global.writeLog("业务函数["+method+"]", inputData, outputData);
            }
        }

        public int BusinessExt(string inputData, ref string outputData, ref string pErrMsg)
        {
            pErrMsg = "";
            outputData = "";
            try
            {
                //inputData = inputData.Replace("\n", "").Replace("\t", "").Replace("\r", "");

                StringBuilder errmsgSb = new StringBuilder(4096);
                StringBuilder outSb = new StringBuilder(40960);
                StringBuilder sbHospitalNO = new StringBuilder(Global.inf.hospitalNO);
                StringBuilder sbCreditID = new StringBuilder(Global.inf.CreditID);
                StringBuilder sbBusinessID = new StringBuilder(Global.inf.BusinessID);
                StringBuilder sbInput = new StringBuilder(inputData);
                //调用业务函数
                int pRtn = 0; // BusinessHandleW(sbHospitalNO, sbCreditID, sbBusinessID, sbInput, outSb, errmsgSb);

                if (pRtn != 0)
                {
                    outputData = outSb.ToString();
                    pErrMsg = errmsgSb.ToString();
                    return -1;
                }
                else
                {
                    outputData = outSb.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                pErrMsg = "invokeInitByDLL.BusinessHandle 异常:" + ex.Message;
                return -1;
            }
            finally
            {
                Global.writeLog("CreditID12", Global.inf.CreditID, Global.inf.BusinessID);
                Global.writeLog("invokeInitByDLL.BusinessHandleW医保动态库通用业务函数", inputData, outputData);
            }
        }

        public int DownloadFile(string inputData, ref string outputData)
        {
            outputData = "";
            string error = string.Empty; int errorCode = 0;
            try
            {
                JObject jsonInParam = JObject.Parse(inputData);
                string fileName = (string)jsonInParam["input"]["fsDownloadIn"]["filename"];
                string filePath = Global.curEvt.path + "\\YBDLOAD\\" + fileName;
                //如果不存在目录,则创建目录
                if (!Directory.Exists(Global.curEvt.path + "\\YBDLOAD"))
                {
                    //创建文件夹
                    DirectoryInfo dirInfo = Directory.CreateDirectory(Global.curEvt.path + "\\YBDLOAD");
                }
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                int iRes = Business(inputData, ref outputData,ref error);
                Global.writeLog("DLL下载文件返回:["+iRes+"]",inputData,outputData);
                if (iRes == 0)
                {
                    dynamic joReturn = new JObject();
                    joReturn.errorCode = errorCode;
                    joReturn.errorMessage = error;
                    joReturn.filePath = filePath;
                    outputData = joReturn.ToString();
                }
                else
                {
                    errorCode = -100;
                    dynamic joReturn = new JObject();
                    joReturn.errorCode = errorCode;
                    joReturn.errorMessage = error;
                    outputData = joReturn.ToString();
                    return -1;
                }
            }
            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 Init(ref string pErrMsg)
        {
            int pRtn = -1;
            pErrMsg = "";
            JObject joRtn = new JObject();
            try
            {
                StringBuilder sbOut = new StringBuilder(40960);
                pRtn = 0; // Init(sbOut);
                pErrMsg = sbOut.ToString();
                Global.writeLog("DLL返回:"+pErrMsg);
                return pRtn;
            }
            catch (Exception ex)
            {
                pErrMsg = "invokeInitByDLL.Init 异常:" + ex.Message;
                return -1;
            }
            finally
            {
                Global.writeLog("InvokeInitByDLL(" + Global.inf.centerURL + ")", Global.inf.CreditID + ":" + Global.inf.BusinessID, pRtn.ToString() + pErrMsg);
            }
        }

        public int UploadFile(string inputData, ref string outputData, ref string pErrMsg)
        {
            pErrMsg = "";
            outputData = "";
            JObject joRtn = new JObject();
            try
            {
                inputData = inputData.Replace("\n", "").Replace("\t", "").Replace("\r", "");

                StringBuilder errmsgSb = new StringBuilder(4096);
                StringBuilder outSb = new StringBuilder(40960);

                //调用业务函数
                int pRtn = 0; // UploadFile(Global.inf.hospitalNO, Global.inf.CreditID, Global.inf.BusinessID, Global.inf.fileName, inputData, outSb, errmsgSb);

                if (pRtn != 0)
                {
                    outputData = outSb.ToString();
                    pErrMsg = errmsgSb.ToString();
                    return -1;
                }
                else
                {
                    outputData = outSb.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                pErrMsg = "invokeUploadFileByDLL.UploadFile 异常:" + ex.Message;
                return -1;
            }
            finally
            {
                Global.writeLog("invokeUploadFileByDLL.UploadFile医保动态库上传业务函数", inputData, outputData);
            }
        }

        /// <summary>
        /// 初始化函数
        /// </summary>
        /// <param name="pErrMsg"></param>
        /// <returns></returns>
        //[DllImport("cressWSDLL.dll", EntryPoint = "INIT", CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)] 
        //static extern int Init(StringBuilder pErrMsg);

        /// <summary>
        /// 通用业务函数
        /// </summary>
        /// <param name="inputData"></param>
        /// <param name="outputData"></param>
        /// <returns></returns>     
        [DllImport("cressWSDLL.dll", EntryPoint = "f_invoke_cress", CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)] 
        static extern int BusinessHandle(string sbjgbh, string czybh,string hisjyh,string method,string jsonPara,string yybm, ref string outputData);


    }
}