using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PTMedicalInsurance.Business;
using System.Diagnostics;
using PTMedicalInsurance.Forms;


namespace PTMedicalInsurance.Helper
{
    class InvokeComCenter : IInvokeCenter
    {
        string progID1 = "ybjk.interface";
        System.Type YinHaiComType;
        object YinHaiComInstance;

        //[STAThread]
        //static void Main()
        //{
        //    //Application.EnableVisualStyles();
        //    //Application.SetCompatibleTextRenderingDefault(false);
        //    // 开始监控窗口
        //    WindowMonitor.Start();
        //    // 运行应用程序
        //    //Application.Run();
        //}
       
        public int Business(string infno, ref  string input, ref string output)
        {
            YinHaiComType = System.Type.GetTypeFromProgID(progID1);

            JObject jo = new JObject();
            jo.Add("transNo", infno);
            jo.Add("transType", "passwordCheck");
            jo.Add("timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
            jo.Add("businessType", Global.pat.card.ecBizType);
            jo.Add("data", JObject.Parse(input));
            string inpar = jo.ToString();
            
            try
            {           
                //WindowMonitor.Start();

                // 创建Com的实例
                if (YinHaiComType != null)
                {
                    //创建实例
                    YinHaiComInstance = Activator.CreateInstance(YinHaiComType);
                    //设置需要设置的参数值
                    //设置需要设置的参数值
                    object[] ParamArray = new object[3];
                    ParamArray[0] = infno;
                    ParamArray[1] = inpar;
                    ParamArray[2] = "";
                    ParameterModifier[] ParamMods = new ParameterModifier[1];
                    ParamMods[0] = new ParameterModifier(3); // 初始化为接口参数的个数
                                                             //ParamMods[0][0] = false;
                                                             //ParamMods[0][1] = false; 
                    ParamMods[0][2] = true;

                    YinHaiComType.InvokeMember("xjyb_call", // 接口函数名
                        BindingFlags.Default | BindingFlags.InvokeMethod,
                    null,
                    YinHaiComInstance, // 调用的COM组件
                    ParamArray, // 参数数组
                    ParamMods, // 指定返回参数的ParameterModifier数组
                    null,
                    null);
                    output = ParamArray[2].ToString();

                    return 0;
                }
                else
                {
                    output = "YinHaiComType加载失败！";
                    return 1;
                }
            }
            catch (Exception ex)
            {
                string outMes = ex.Message;
                if (ex.InnerException != null)
                {
                    outMes += ex.InnerException.Message;
                }
                output = outMes;
                return -1;
            }
            finally
            {
                Global.writeLog("InvokeComCenter.Business", inpar, output);
            }
        }

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

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

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

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

    /// <summary>
    /// 2026版本控件调用
    /// </summary>
    class InvokeComCenter2026 : IInvokeCenter
    {
        string progID1 = "ybjk.interface";
        System.Type YinHaiComType;
        object YinHaiComInstance;

        public int Business(string infno, ref string input, ref string output)
        {
            try
            {
                Type comType = Type.GetTypeFromProgID(progID1);
                if (comType == null)
                {
                    output = "COM 组件未注册或 progID 错误";
                    return -1;
                }

                object comInstance = Activator.CreateInstance(comType);

                // 构造输入 JSON（略，你已有）
                JObject jo = new JObject();
                jo.Add("timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
                jo.Add("business_type", Global.pat.card.ecBizType );
                jo.Add("mdtrt_cert_type", Global.pat.mdtrtcertType);
                jo.Add("operator_id", Global.user.ID);
                jo.Add("operator_name", Global.user.name);
                jo.Add("device_type", ""); // 注意：你之前写成 user.ID，可能错误！
                jo.Add("office_id", Global.user.officeID);
                jo.Add("office_name", Global.user.officeName);
                jo.Add("work_injury_flag", Global.pat.isWorkInjury ? "1" :"0");
                jo.Add("data", string.IsNullOrWhiteSpace(input) ? new JObject() : JObject.Parse(input));

                string inpar = jo.ToString();

                // === 关键：调用 COM 方法 ===
                string jysc = ""; // 初始化输出参数（必须是 string 类型！）

                // 使用 object[] 传递参数
                object[] args = new object[3] { infno, inpar, jysc };

                // 告诉 .NET 第3个参数是 ref（可被修改）
                ParameterModifier paramMod = new ParameterModifier(3);
                paramMod[2] = true; // 索引从0开始，第3个参数是索引2

                comType.InvokeMember(
                    "xjyb_call",
                    BindingFlags.InvokeMethod,
                    null,
                    comInstance,
                    args,
                    new ParameterModifier[] { paramMod },
                    null,
                    null
                );

                // 取出被 COM 修改后的输出值
                output = args[2]?.ToString() ?? "";

                // 可选：记录日志
                Global.writeLog($"InvokeComCenter.Business.{infno}", inpar, output);

                return 0;
            }
            catch (Exception ex)
            {
                output = $"调用 COM 失败: {ex.Message}";
                Global.writeLog("InvokeComCenter.Error", "", output);
                return -1;
            }
        }


        //public int Business(string infno, ref string input, ref string output)
        //{
        //    YinHaiComType = System.Type.GetTypeFromProgID(progID1);

        //    JObject jo = new JObject();
        //    jo.Add("timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
        //    jo.Add("business_type", Global.pat.card.ecBizType);
        //    jo.Add("mdtrt_cert_type", Global.pat.mdtrtcertType);
        //    jo.Add("operator_id", Global.user.ID);
        //    jo.Add("operator_name", Global.user.name);
        //    jo.Add("device_typ", Global.user.ID);//自助机该字段设为SelfService，其它情况 不用设置
        //    jo.Add("office_id", Global.user.officeID);
        //    jo.Add("office_name", Global.user.officeName);
        //    jo.Add("work_injury_flag", Global.pat.isWorkInjury?1:0);//根据此标志转发人社工伤医疗费用结算子系统，见本文档附件 2《字典表》
        //    jo.Add("data", JObject.Parse(input));
        //    string inpar = jo.ToString();

        //    try
        //    {
        //        //WindowMonitor.Start();

        //        // 创建Com的实例
        //        if (YinHaiComType != null)
        //        {
        //            //创建实例
        //            YinHaiComInstance = Activator.CreateInstance(YinHaiComType);
        //            //设置需要设置的参数值
        //            //设置需要设置的参数值
        //            object[] ParamArray = new object[3];
        //            ParamArray[0] = infno;
        //            ParamArray[1] = inpar;
        //            ParamArray[2] = "";
        //            ParameterModifier[] ParamMods = new ParameterModifier[1];
        //            ParamMods[0] = new ParameterModifier(3); // 初始化为接口参数的个数
        //                                                     //ParamMods[0][0] = false;
        //                                                     //ParamMods[0][1] = false; 
        //            ParamMods[0][2] = true;

        //            YinHaiComType.InvokeMember("xjyb_call", // 接口函数名
        //                BindingFlags.Default | BindingFlags.InvokeMethod,
        //            null,
        //            YinHaiComInstance, // 调用的COM组件
        //            ParamArray, // 参数数组
        //            ParamMods, // 指定返回参数的ParameterModifier数组
        //            null,
        //            null);
        //            output = ParamArray[2].ToString();

        //            return 0;
        //        }
        //        else
        //        {
        //            output = "YinHaiComType加载失败！";
        //            return 1;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        string outMes = ex.Message;
        //        if (ex.InnerException != null)
        //        {
        //            outMes += ex.InnerException.Message;
        //        }
        //        output = outMes;
        //        return -1;
        //    }
        //    finally
        //    {
        //        Global.writeLog($"InvokeComCenter.Business{infno}", inpar, output);
        //    }
        //}

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

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

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

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