/******************************************************************************
 * 文件名称: CenterBusiness.cs
 * 文件说明: 中心交易封装
 * 当前版本: V1.0
 * 创建日期: 2022-06-20
 *
 * * 2020-06-20: 增加 CenterBusiness 类
 * *****  2020-06-20: 增加 CardReader 方法，获取URL地址,USER信息，地方版SSCard.dll使用
 * *****  2020-06-20: 增加 CardReader 方法重载，国家版电子凭证使用
 * *****  2020-06-20: 增加 Init 方法，SSCard环境初始化



******************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using System.Windows.Forms;

namespace PTMedicalInsurance.Business
{

   
    class CenterBusiness
    {
        private InvokeHelper invoker = new InvokeHelper();

        #region 目录下载
        /// <summary>
        /// 下载业务（1301-1309），返回会的JSON串中包含解压后的TXT地址
        /// </summary>
        /// <param name="funNO"></param>
        /// <param name="ver"></param>
        /// <param name="outPath"></param>
        /// <returns></returns>
        public JObject DownDictionay(JObject joData)
        {
            string outparam = "";
            try
            {
                dynamic joParam = new JObject();
                joParam.data = joData;

                JObject joRtn = invoker.invokeCenterService("1901", JsonHelper.setCenterInpar("1901",joParam));
                outparam = joRtn.ToString();
                return joRtn;
            }
            catch (Exception ex)
            {
                JObject joRtn = JsonHelper.setExceptionJson(-1, "DownDictionay:", ex.Message);
                outparam = joRtn.ToString();
                return joRtn;
            }
        }

        /// <summary>
        /// 下载业务（1301-1309），返回会的JSON串中包含解压后的TXT地址
        /// </summary>
        /// <param name="funNO"></param>
        /// <param name="ver"></param>
        /// <param name="outPath"></param>
        /// <returns></returns>
        public JObject DownDirecotry(string funNO, string ver)
        {
            try
            {
                dynamic joTmp = new JObject();
                joTmp.ver = ver;
                JObject joData = new JObject {
                    { "data",joTmp}
                };

                return invoker.invokeCenterService(funNO, JsonHelper.setCenterInpar(funNO,joData));
            }
            catch (Exception ex)
            {
                return JsonHelper.setExceptionJson(-1, "DownDirecotry:", ex.Message);
            }
        }

        /// <summary>
        /// 91021保存文件
        /// </summary>
        /// <param name="jo"></param>
        /// <returns>正常返回结果同中心文档，异常返回结果同HIS</returns>
        public JObject SaveFile(JObject jo,string ver)
        {
            try
            {
                string filename = JsonHelper.getDestValue(jo, "output.filename");
                string file_qury_no = JsonHelper.getDestValue(jo, "output.file_qury_no");
                string data_cnt = JsonHelper.getDestValue(jo, "output.data_cnt");

               
                dynamic jo9102InParam = new JObject();
                dynamic jofsDownloadIn = new JObject();
                jofsDownloadIn.filename = filename;
                jofsDownloadIn.file_qury_no = file_qury_no;
                jofsDownloadIn.fixmedins_code = Global.inf.hospitalNO;

                //合肥文件名固定
                jofsDownloadIn.filename = "plc";
                jofsDownloadIn.fixmedins_code = ver;


                jo9102InParam.fsDownloadIn = jofsDownloadIn;
                return  invoker.DownloadCenterFile(JsonHelper.setCenterInpar("9102", jo9102InParam.ToString()));

            }
            catch (Exception ex)
            {
                return JsonHelper.setExceptionJson(-1, "9102保存文件", ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 医保相关查询交易-不需要下载文件解析
        /// </summary>
        /// <param name="funNO"></param>
        /// <returns></returns>
        public JObject InvokeMedicalInsuranceInquiry(string funNO, JObject joInData)
        {
            try
            {
                JObject joInput = new JObject();

                if (funNO != "1201")
                    joInput.Add("data", joInData);
                else
                    joInput.Add("medinsinfo", joInData);

                return invoker.invokeCenterService(funNO, JsonHelper.setCenterInpar(funNO, joInput.ToString()));
            }
            catch (Exception ex)
            {
                //封装返回值的格式 {"errorCode":"-1","errorMessage":"InvokeMedicalInsuranceInquiry+异常信息"}
                return JsonHelper.setExceptionJson(-1, "InvokeMedicalInsuranceInquiry:", ex.Message);
            }
        }

        /// <summary>
        /// 签到
        /// </summary>
        /// <returns></returns>
        public int signIn(out JObject joRtn)
        {
            string outParam = "";
            string inParam = "";
            try
            {
                dynamic jsonSignIn = new JObject();
                dynamic jsonInput = new JObject();

                if (Global.inf.interfaceDr == 12)//安徽省基线版
                {
                    jsonSignIn.opter_no = "A05CA9455BE8BF66";
                }
                if (Global.inf.interfaceDr == 16)//合肥市基线版
                {
                    jsonSignIn.opter_no = "7571C4995A2F4290";
                }
                if (Global.inf.interfaceDr == 15)//安徽省基线版-蜀山老院
                {
                    jsonSignIn.opter_no = "48664E4455CC0F8F";
                }
                if (Global.inf.interfaceDr == 17)//合肥市基线版-蜀山老院
                {
                    jsonSignIn.opter_no = "4D91C975CF902EB2";
                }
                //jsonSignIn.opter_no = "888888";  //测试账号

                jsonSignIn.mac = Global.curEvt.mac;
                
                //MessageBox.Show(Global.inf.hospitalNO + "||" + Global.inf.CreditID + "||" + Global.inf.BusinessID);

                jsonSignIn.ip = Global.curEvt.ip;
                jsonInput.signIn = jsonSignIn;
                Global.writeLog(jsonInput.ToString());
                inParam = JsonHelper.setCenterInpar("9001", jsonInput.ToString());               

                outParam = invoker.invokeCenterService("9001", inParam).ToString();
                joRtn = JObject.Parse(outParam);
                if (joRtn["infcode"].ToString() == "0")
                {
                    Global.curEvt.signno = joRtn["output"]["signinoutb"]["sign_no"].ToString();
                    return 0;
                }
                else
                {
                    //joRtn = JsonHelper.getIrisExceptionJson(-100, "签到异常", (string)joRtn["err_msg"]);
                    Global.curEvt.signno = "";
                    return -1;
                }

            }
            catch (Exception ex)
            {
                joRtn = new JObject();
                joRtn.Add("infcode", -1);
                joRtn.Add("err_msg", outParam + ex.Message);
                //joRtn = JsonHelper.getIrisExceptionJson(-100,"签到异常", outParam + ex.Message);
                return -2;
            }

        }

        //【1191】身份认证
        public int Authenticate(out string outPar)
        {
            outPar = "";
            string cardtype = "";            
            string operatorid = Global.user.ID;     
            string operatorname = Global.user.name;
            string officeid = "A10";
            string officename = "眼科";
            try
            {
                if (Global.pat.mdtrtcertType == "01")
                {
                    cardtype = "1";  
                }
                else
                {
                    cardtype = "0";  
                }

                JObject joData = new JObject();
                joData.Add("mdtrt_cert_type", Global.pat.mdtrtcertType);
                joData.Add("cardtype ", cardtype);                //卡片类型 0：实体卡 1：电子社保卡
                joData.Add("businesstype", Global.businessType);       //用码业务类型 01挂号
                joData.Add("operatorid", operatorid);           //收款员编号
                joData.Add("operatorname", operatorname);       //收款员姓名
                joData.Add("officeid", officeid);               //医保科室编号
                joData.Add("officename", officename);           //科室名称

                //joData.Add("card_sn", Global.pat.card.SN);
                //joData.Add("card_pwd", Global.pat.card.password);
                //joData.Add("psn_cert_type", Global.pat.certType);
                //joData.Add("certno", Global.pat.card.NO);
                //joData.Add("real_certno", Global.pat.certNO);
                //joData.Add("card_lv", Global.pat.card.level);
                //joData.Add("psn_name", Global.pat.name);
                //joData.Add("extra", "");

                JObject joInput = new JObject();
                joInput.Add("data",joData);
                string funNO = "1191";
                JObject joRtn = invoker.invokeCenterService(funNO, JsonHelper.setCenterInpar(funNO, joInput));
                string errMsg;

                if (JsonHelper.parseCenterRtnValue(joRtn,out errMsg) != 0)
                {
                    outPar = errMsg;
                    return -1;
                }
                else
                {
                    outPar = joRtn.ToString();
                    if (Global.pat.mdtrtcertType == "03")
                      Global.pat.card.Cardtoken = JsonHelper.getDestValue(JObject.Parse(outPar), "output.cardinfo.cardtoken");

                    return 0;
                }
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        /// <summary>
        /// 住院患者登记
        /// </summary>
        /// <returns></returns>
        public int inPatReg(string inParam,out string outparam)
        {
            outparam = "";
            try
            {

                return 0;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        public int cancleRegister(string funNO, out string outparam)
        {
            outparam = "";
            string errMsg;
            try
            {
                dynamic joTmp = new JObject();
                joTmp.mdtrt_id = Global.pat.mdtrtID;
                joTmp.psn_no = Global.pat.psn_no;
                if (funNO == "2202")
                {
                    joTmp.ipt_otp_no = Global.pat.adm_Dr.ToString();
                }
                JObject joData = new JObject();
                joData.Add("data", joTmp);
                //好后上传给中心
                //string inpar = Global.inf.SetJsonParam("2405", joTmp).ToString();

                JObject joRtn = invoker.invokeCenterService(funNO, JsonHelper.setCenterInpar(funNO, joData).ToString());
                if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
                {
                    outparam = errMsg;
                    return -1;
                }
                else
                {
                    outparam = joRtn.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                outparam = "取消登记异常" + funNO + ":" + ex.Message;
                return -1;
            }
        }

        /// <summary>
        /// 取消费用传送
        /// </summary>
        /// <param name="pat"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public int cancleFeeUpload(string funNO,out string errMsg)
        {
            errMsg = "";
            try
            {
                //组织入参
                dynamic joTmp = new JObject();
                if (funNO == "2205")
                {
                    joTmp.chrg_bchno = "0000";
                }
                else
                {
                    joTmp.feedetl_sn = "0000";
                }
                
                joTmp.mdtrt_id = Global.pat.mdtrtID;
                joTmp.psn_no = Global.pat.psn_no;

                JObject joData = new JObject();
                if (funNO == "2205")
                {
                    joData.Add("data", joTmp);
                }
                else
                {
                    JArray jaData = new JArray();
                    jaData.Add(joTmp);
                    joData.Add("data", jaData);
                }
                    

                //组织好后上传给中心
                JObject joRtn = invoker.invokeCenterService(funNO, JsonHelper.setCenterInpar(funNO, joData.ToString()));
                if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
                {
                    return -1;
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                errMsg = "cancleFeeUpload异常：" + ex.Message;
                return -1;
            }
            
            
            

        }

        public int cancleSettlement(string funNO, out string outparam)
        {
            outparam = "";
            string errMsg;
            try
            {
                dynamic joTmp = new JObject();
                joTmp.mdtrt_id = Global.pat.mdtrtID;
                joTmp.psn_no = Global.pat.psn_no;
                joTmp.setl_id = Global.pat.settlID;
                joTmp.exp_content = "";
                JObject joData = new JObject();
                joData.Add("data", joTmp);
                JObject joRtn = invoker.invokeCenterService(funNO, JsonHelper.setCenterInpar(funNO, joData).ToString());
                if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
                {
                    outparam = errMsg;
                    return -1;
                }
                else
                {
                    outparam = joRtn.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                outparam = "取消结算异常" + funNO + ":" + ex.Message;
                return -1;
            }
        }

        public int DealFor2001(string funNO, out string errMsg)
        {
            //人员待遇享受检查
            JObject joData2001 = new JObject();
            joData2001.Add("psn_no", Global.pat.psn_no);
            joData2001.Add("insutype", Global.pat.insuType);
            joData2001.Add("fixmedins_code", Global.inf.hospitalNO);
            joData2001.Add("med_type", Global.pat.medType);
            joData2001.Add("begntime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            joData2001.Add("endtime", "");
            joData2001.Add("dise_codg", Global.pat.disCode);
            joData2001.Add("dise_name", Global.pat.disName);
            joData2001.Add("oprn_oprt_code", "");
            joData2001.Add("oprn_oprt_name", "");
            joData2001.Add("matn_type", "");
            joData2001.Add("birctrl_type", "");

            JObject joInput = new JObject();
            joInput.Add("data", joData2001);
            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn2001 = invoker.invokeCenterService("2001", JsonHelper.setCenterInpar("2001", joInput));

            if (JsonHelper.parseCenterRtnValue(joRtn2001, out errMsg) != 0)
            {
                //MessageBox.Show("人员待遇享受检查调用失败，中心返回错误信息：" + errMsg);

                errMsg = "人员待遇享受检查调用失败，中心返回错误信息：" + errMsg;
                return -1;
            }
            else
            {
                return 0;
            }
        }

    }
}
