using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.FormSetter;
using PTMedicalInsurance.Business;
using PTMedicalInsurance.Variables;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SM2Crypto.Lib;



namespace PTMedicalInsurance.Forms
{
    public partial class PrescriptionCirculation : Form
    {
        //设置业务实例
        CenterBusiness cBus = new CenterBusiness();
        HisMainBusiness hBus = new HisMainBusiness();
        HisIrisServices hIS = new HisIrisServices();
        MIIrisServices mIS = new MIIrisServices();
        InvokeHelper invoker = new InvokeHelper();
        //InsuServices iris = new InsuServices();
        public string patInfo = "", ReadCardOutParam = "", CertNo = "";
        public string presAdmLoc = "", presAdmDoc = "", presAdmID = "", presNo = "", hiRxno = "";
        public string DrCode = "", DrName = "", DrInsuCode = "", DrCertNo = "";
        public string HospRxno = "";

        //1.声明自适应类实例
        AutoResizeForm asc = new AutoResizeForm();

        //public PrescriptionCirculation()
        //{
        //    InitializeComponent();

        //    asc.controllInitializeSize(this);
        //    asc.controlAutoSize(this);

        //    GridViewSetter grdSetter = new GridViewSetter();
            
        //    grdSetter.SetHeaderTextOfHISRegister(dgv_HISRegInfo);
        //    grdSetter.SetHeaderTextOfHISPrescFee(dgv_PrescriptionInfo);   
        //    grdSetter.DatagridviewColumnWidthAdaptation(dgv_HISRegInfo);
        //    grdSetter.DatagridviewColumnWidthAdaptation(dgv_PrescriptionInfo);

        //    dtST.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
        //    dtED.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

        //    if (CertNo != "")
        //    {
        //        //查询HIS就诊信息
        //        string outParam = "";
        //        DataTable dt = null;
        //        if (GetHISRegInfo("2023-06-14 00:00:00", "2023-06-14 23:59:59", "620202197310200245", ref outParam, ref dt) != 0)
        //        {
        //            MessageBox.Show(outParam);
        //            return;
        //        }
        //        dgv_HISRegInfo.DataSource = dt;


        //        //查询处方明细信息
        //        if (dt.Rows.Count == 0)
        //            return;
        //        if (dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["ID"].Value.ToString() == "")
        //            return;

        //        DataTable dt2 = null;
        //        presAdmDoc = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["doc"].Value.ToString();
        //        presAdmLoc = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["loc"].Value.ToString();
        //        presNo = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["prescNo"].Value.ToString();
        //        presAdmID = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["admID"].Value.ToString();
        //        Global.pat.adm_Dr = int.Parse(presAdmID);

        //        if (presNo == "") return;

        //        //获取HIS处方明细信息
        //        if (GetHISPrescFeeInfo(presNo, ref outParam, ref dt2) != 0)
        //        {
        //            MessageBox.Show(outParam);
        //            return;
        //        }

        //        dgv_PrescriptionInfo.DataSource = dt2;
        //    }   
        //}

        public PrescriptionCirculation(string PatInfo)
        {
            InitializeComponent();

            asc.controllInitializeSize(this);
            asc.controlAutoSize(this);

            GridViewSetter grdSetter = new GridViewSetter();

            grdSetter.SetHeaderTextOfHISRegister(dgv_HISRegInfo);
            grdSetter.SetHeaderTextOfHISPrescFee(dgv_PrescriptionInfo);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_HISRegInfo);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_PrescriptionInfo);

            dtST.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dtED.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            if (PatInfo != "")
            {
                //查询HIS就诊信息
                string outParam = "";
                DataTable dt = null;
                if (GetHISRegInfo(dtST.Text, dtED.Text, PatInfo, ref outParam, ref dt) != 0)
                {
                    MessageBox.Show(outParam);
                    return;
                }
                dgv_HISRegInfo.DataSource = dt;
                tb_CertNo.Text = PatInfo;

                //查询处方明细信息
                if (dt.Rows.Count == 0)
                    return;
                if (dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["ID"].Value.ToString() == "")
                    return;

                DataTable dt2 = null;
                presAdmDoc = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["doc"].Value.ToString();
                presAdmLoc = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["loc"].Value.ToString();
                presNo = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["prescNo"].Value.ToString();
                presAdmID = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["admID"].Value.ToString();
                Global.pat.adm_Dr = int.Parse(presAdmID);

                if (presNo == "") return;

                //获取HIS处方明细信息
                if (GetHISPrescFeeInfo(presNo, ref outParam, ref dt2) != 0)
                {
                    MessageBox.Show(outParam);
                    return;
                }

                dgv_PrescriptionInfo.DataSource = dt2;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void PrescriptionCirculation_Load(object sender, EventArgs e)
        {
            this.Height = 800;
            this.Width = 1500;

            this.WindowState = FormWindowState.Maximized;

            asc.controllInitializeSize(this);
            asc.controlAutoSize(this);            
        }

        private void SetDBLKCombox(ref PTControl.DBLookupCombox dblcbx, DataTable dtUserInfo)
        {
            dblcbx.sDisplayField = "Code,descripts,insuUserCode,credNo";
            dblcbx.sDisplayMember = "姓名";
            dblcbx.sKeyWords = "Code,descripts";
            dblcbx.DataSource = dtUserInfo;
            dblcbx.RowFilterVisible = true;
            dblcbx.TextBox.Width = 400;
            dblcbx.DataGridView.Width = 400;
            dblcbx.DataGridView.Columns[0].Name = "编码";
            dblcbx.DataGridView.Columns[1].Name = "姓名";
            dblcbx.DataGridView.Columns[2].Name = "医保医师代码";
            dblcbx.DataGridView.Columns[3].Name = "证件号码";
            dblcbx.DataGridView.Columns[0].Width = 55;
            dblcbx.DataGridView.Columns[1].Width = 55;
            dblcbx.DataGridView.Columns[2].Width = 115;
            dblcbx.DataGridView.Columns[3].Width = 200;
        }

        private void dgv_HISRegInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgv_HISRegInfo.DataSource == null)            
                return;

            if (dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["ID"].Value.ToString() == "")
                return;

            string outParam = "";
            DataTable dt = null;
            presAdmDoc = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["doc"].Value.ToString();
            presAdmLoc = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["loc"].Value.ToString();
            presNo = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["prescNo"].Value.ToString();
            presAdmID = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["admID"].Value.ToString();
            Global.pat.adm_Dr = int.Parse(presAdmID);

            if (presNo == "") return;

            //获取HIS处方明细信息
            if (GetHISPrescFeeInfo(presNo, ref outParam, ref dt) != 0)
            {
                MessageBox.Show(outParam);
                return;
            }

            dgv_PrescriptionInfo.DataSource = dt;
        }

        private void btnUpload_Pre_Click(object sender, EventArgs e)
        {
            string OutMsg = "", InsuOutMsg = "", outParam = "";
            if (((DataTable)dgv_HISRegInfo.DataSource == null) || ((DataTable)dgv_PrescriptionInfo.DataSource == null))
            {
                MessageBox.Show("请先查询该患者就诊处方信息！");
                return;
            }

            if (presNo == "")
            {
                MessageBox.Show("请选择处方就诊记录！");
                return;
            }

            //Global.pat.adm_Dr = int.Parse(presAdmID);
            //获取最近医保挂号信息（电子处方流转只能取通过电子凭证挂号登记的记录）
            //if (GetInsuRegIDFromHIS(presAdmID,AdmDoc,AdmLoc,out Global.pat.mdtrtID, out OutMsg) != 0)
            //{
            //    MessageBox.Show("【医保电子处方流程业务】获取医保就诊ID失败！");
            //    return;
            //}

            #region【获取电子处方上传预核验业务入参】
            if (GetPreVerificationInput(presAdmID, presNo, ref outParam) != 0)
            {
                MessageBox.Show("【医保电子处方流转业务】获取电子处方上传预核验业务入参失败：" + outParam);
                return;
            }

            string pharCode = JObject.Parse(outParam)["mdtrtinfo"]["pharCode"].ToString();
            if (pharCode == "")
            {
                MessageBox.Show("【医保电子处方流转业务】获取电子处方上传预核验成功,但返回审方医保药师代码信息为空！");
                return;
            }
            #endregion

            #region【2201医保挂号-2203医保就诊信息上传-获取医保就诊ID】               
            if (GetPresCirInsuRegID(out Global.pat.mdtrtID, out OutMsg) != 0)
            {
                MessageBox.Show("【医保电子处方流转业务】医保挂号失败：" + OutMsg);
                return;
            }
            #endregion

            #region【7101】电子处方上传预核验             
            JObject joInput = JObject.Parse(outParam);
            joInput["mdtrtinfo"]["mdtrtId"] = Global.pat.mdtrtID;  //取最新的2201医保挂号返回就诊ID
            joInput["mdtrtinfo"]["psnNo"] = Global.pat.psn_no;
            joInput["mdtrtinfo"]["medType"] = Global.pat.medType;
            joInput["insuPlcNo"] = Global.pat.insuplc_admdvs;          

            JObject joRtn = invoker.invokeCenterServicePresCir("7101", JsonHelper.setCenterInparPresCirNew(joInput));
            if (JsonHelper.parseCenterRtnValuePresCir(joRtn, out InsuOutMsg) != 0)
            {
                //电子处方上传预核验失败,调用2202撤销医保挂号
                if (CancelInsuReg(Global.pat.psn_no, Global.pat.mdtrtID, presAdmID, out string OutMsg2) != 0)
                {
                    MessageBox.Show("【7101】电子处方上传预核验失败:" + InsuOutMsg + "\r\n" + ",撤销医保挂号失败：" + OutMsg2);
                    return;
                }
                else
                {
                    //中心撤销成功后调用撤销医保平台登记表信息                    
                    if (mIS.cancleRegister(6, out OutMsg) != 0) //取消医保平台登记
                    {
                        MessageBox.Show("【7101】电子处方上传预核验失败,撤销医保挂号成功，但云医保平台取消失败:" + OutMsg);
                        return;
                    }
                    else
                    {                        
                        if (hIS.cancleRegister(out outParam) != 0) //取消HIS 门诊登记
                        {
                            MessageBox.Show("【7101】电子处方上传预核验失败,云医保平台取消登记成功，但HIS取消失败，" + outParam + InsuOutMsg);
                            return;
                        }
                        else
                        {
                            MessageBox.Show("【7101】电子处方上传预核验失败,撤销医保挂号成功 :" + InsuOutMsg);
                            return;
                        }
                    }
                }
            }
            else
            {
                /*使用平台公钥（publicKey赋值为平台实际分配的平台公钥）对远端服务HTTP接口返回Respone对象数据进行验签示例*/
                //JObject testRespone = joRtn;
                //JValue encDataObj = (JValue)testRespone.GetValue("encData");
                //testRespone.Remove("encData");
                //JValue signDataObj = (JValue)testRespone.GetValue("signData");
                //testRespone.Remove("signData");
                //String encData = encDataObj.ToString();
                //String signData = signDataObj.ToString();
                //JObject signDto = testRespone;
                ////解密
                //String decDatas = SMUtil.decrypt(encData, Global.inf.appId, Global.inf.Secret);
                //Console.WriteLine("解密：" + decDatas);
                //signDto.Remove("data");
                //JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                //{
                //    FloatParseHandling = FloatParseHandling.Decimal
                //};
                //signDto.Add("data", JToken.FromObject(JsonConvert.DeserializeObject(decDatas)));
                ////验签
                //Boolean isVerifys = SMUtil.verify(signDto, Global.inf.Secret, Global.inf.publicKey, signData);
                //Console.WriteLine("验签：" + isVerifys);

                /*使用应用公钥（publicKey示例默认值）对本地自签名的数据进行验签示例*/
                JValue encDataObj = (JValue)joRtn.GetValue("encData");
                string encData = encDataObj.ToString();
                //解密
                string decDatas = SMUtil.decrypt(encData, Global.inf.appId, Global.inf.Secret);
                JObject joRtnEncDataObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(decDatas);

                //验签
                //Boolean isVerifys = SMUtil.verify(signDto, Global.inf.Secret, Global.inf.publicKey, signData);
                //MessageBox.Show("验签：" + isVerifys);

                //医保电子处方上传预核验成功后写入后台记录
                if (insertPresCirPreResult(joInput, joRtnEncDataObj, out OutMsg) != 0)
                {
                    MessageBox.Show("【7101】电子处方上传预核验成功，调用IRIS服务插入记录失败：" + OutMsg);
                    return;
                }

                MessageBox.Show("电子处方上传预核验成功！");
            }
            #endregion
        }

        private void btnElcSign_Click(object sender, EventArgs e)
        {
            if ((DataTable)dgv_HISRegInfo.DataSource == null)
            {
                MessageBox.Show("请先查询该患者就诊处方信息！");
                return;
            }

            if (presNo == "")
            {
                MessageBox.Show("请选择处方记录！");
                return;
            }

            #region【组织originalValue原始待签名处方信息】

            //1.获取处方预核验表信息
            if (mIS.GetPresCirPreCheckInfo(presNo, out string OutMsg) != 0)
            {
                MessageBox.Show("查询电子处方上传预核验信息失败：" + OutMsg);
                return;
            }

            //2.组织电子处方电子签名调用入参
            JObject joPreCheckParam = MontageElcSignParam(OutMsg);
            string originalValue = Base64Encrypt(joPreCheckParam.ToString());
            string originalRxFile;

            //MessageBox.Show("originalValue加密值base64：" + originalValue);
            //MessageBox.Show("originalValue解密值：" + Base64Decrypt(originalValue));

            //3.获取参数originalRxFile原始待签名处方文件base64的字符值
            if (hIS.GetPrescPDFBase64Str("处方笺", presNo, Global.inf.hisHospitalDr.ToString(), out OutMsg) != 0)
            {
                MessageBox.Show("【7102】电子处方医保电子签名GetPrescPDFBase64Str失败, :" + OutMsg);
                return;
            }
            else
            {
                JObject joRxFile = JObject.Parse(JsonHelper.getDestValue(JObject.Parse(OutMsg), "result"));
                originalRxFile = JsonHelper.getDestValue(joRxFile, "base64Str");
                if (originalRxFile == "")
                {
                    MessageBox.Show("【7102】电子处方医保电子签名失败,电子处方PDF生成Base64Str失败 :" + OutMsg);
                    return;
                }
            }

            //4.调用电子处方医保电子签名
            JObject joInParam = new JObject();
            joInParam.Add("fixmedinsCode", Global.inf.hospitalNO);
            joInParam.Add("originalValue", originalValue);
            joInParam.Add("originalRxFile", originalRxFile);
            joInParam.Add("extras", "1");            
            JObject joRtn = invoker.invokeCenterServicePresCir("7102", JsonHelper.setCenterInparPresCirNew(joInParam));
            if (JsonHelper.parseCenterRtnValuePresCir(joRtn, out OutMsg) != 0)
            {
                MessageBox.Show("【7102】电子处方医保电子签名失败 :" + OutMsg);
                return;
            }

            //5.解密返回值
            JValue encDataObj = (JValue)joRtn.GetValue("encData");
            string encData = encDataObj.ToString();
            string decDatas = SMUtil.decrypt(encData, Global.inf.appId, Global.inf.Secret);
            JObject joRtnEncDataObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(decDatas);

            //6.医保电子处方电子签名成功后调用IRIS服务写入后台记录
            if (insertPresCirSignResult(joPreCheckParam, originalValue, originalRxFile, joRtnEncDataObj, out OutMsg) != 0)
            {
                MessageBox.Show("【7102】电子处方医保电子签名成功，调用IRIS服务插入记录失败：" + OutMsg);
                return;
            }

            MessageBox.Show("电子处方医保电子签名成功！");

            #endregion
        }

        private void btnPresUpload_Click(object sender, EventArgs e)
        {
            if ((DataTable)dgv_HISRegInfo.DataSource == null)
            {
                MessageBox.Show("请先查询该患者就诊处方信息！");
                return;
            }

            if (presNo == "")
            {
                MessageBox.Show("请选择处方记录！");
                return;
            }            

            string OutMsg1, OutMsg2, OutMsg;

            //1.查询电子处方预核验信息
            if (mIS.GetPresCirPreCheckInfo(presNo, out OutMsg1) != 0)
            {
                MessageBox.Show("查询电子处方上传预核验信息失败：" + OutMsg1);
                return;
            }
           
            //2.查询电子处方电子签名信息
            if (mIS.GetPresCirElectronicSignatureInfo(presNo, out OutMsg2) != 0)
            {
                MessageBox.Show("查询电子处方电子签名信息失败,请重新执行一次电子签名操作：" + OutMsg2);
                return;
            }

            //3.组织电子处方上传接口入参
            JObject joPreCheckInfo = JObject.Parse(OutMsg1);  //预核验信息
            JObject joElectronicSignatureInfo = JObject.Parse(OutMsg2);  //电子签名信息
            JObject joInput = MontagePresCiruUploadParam(joPreCheckInfo, joElectronicSignatureInfo);

            //4.调用7103电子处方上传接口
            JObject joRtn = invoker.invokeCenterServicePresCir("7103", JsonHelper.setCenterInparPresCirNew(joInput));
            if (JsonHelper.parseCenterRtnValuePresCir(joRtn, out OutMsg) != 0)
            {
                MessageBox.Show("【7103】电子处方上传失败 :" + OutMsg);
                return;
            }

            //5.解密返回值
            JValue encDataObj = (JValue)joRtn.GetValue("encData");
            string encData = encDataObj.ToString();
            string decDatas = SMUtil.decrypt(encData, Global.inf.appId, Global.inf.Secret);
            JObject joRtnEncDataObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(decDatas);

            //6.电子处方上传7103接口调用成功后插入后台
            if (insertPresCirUploadRecord(joInput, joRtnEncDataObj, out OutMsg) != 0)
            {
                MessageBox.Show("【7101】电子处方上传预核验成功，调用IRIS服务插入记录失败：" + OutMsg);
                return;
            }

            //7.电子处方上传成功后更新HIS处方状态
            if (hIS.updateHISPrecNoStatus(presNo, hiRxno, "B", out OutMsg) != 0)
            {
                MessageBox.Show("【7101】电子处方上传预核验成功，调用IRIS服务插入记录成功，更新HIS处方状态失败：" + OutMsg);
                return;
            }

            MessageBox.Show("【7103】电子处方上传成功！");
        }              

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string sqlStr = " SELECT * FROM BS_MedInsuPresCiruUploadRecord ";
            sqlStr = sqlStr + "WHERE Hospital_Dr=" + Global.inf.hospitalDr; //Upload=Y And 
            sqlStr = sqlStr + " and Interface_Dr= " + Global.inf.interfaceDr;
            sqlStr = sqlStr + " and OccurTime>'" + dt_St.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dt_Et.Text + "'";
            if (tb_CertnoQuery.Text != "")
            {
                sqlStr = sqlStr + " and Certno='" + tb_CertnoQuery.Text + "'";
            }

            switch (rg_type.SelectedIndex)
            {
                case 1:
                    {
                        sqlStr = sqlStr + " and Upload='Y'";
                        break;
                    }
                case 2:
                    {
                        sqlStr = sqlStr + " and Upload='N'";
                        break;
                    }
            }

            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010100");
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询电子处方上传信息");

            DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
            dgv_Master.DataSource = dt;

            if (dt.Rows.Count <= 0)
                dgv_Master.DataSource = null;

        }

        private void cbx_DocInfo_AfterSelector(object sender, PTControl.AfterSelectorEventArgs e)
        {
            DataGridViewRow row = e.Value as DataGridViewRow;
            DataRowView dataRow = row.DataBoundItem as DataRowView;

            DrCode = dataRow["Code"].ToString().Trim();      //HIS工号
            DrName = dataRow["descripts"].ToString().Trim();      //姓名
            DrInsuCode = dataRow["insuUserCode"].ToString().Trim();  //医保医师代码
            DrCertNo = dataRow["credNo"].ToString().Trim();    //身份证号

            cbx_DocInfo.Text = DrName;                                                               
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (dgv_Master.DataSource == null)
            {
                MessageBox.Show("请先查询电子处方信息！");
                return;
            }

            if ((rtb_CancelReason.Text == "") || (rtb_CancelReason.Text == "请输入撤销原因"))
            {
                MessageBox.Show("请输入撤销原因！");
                return;
            }

            if (cbx_DocInfo.Text == "")
            {
                MessageBox.Show("请选择撤销医师！");
                return;
            }

            string OutPut, errMsg;
            int i = dgv_Master.CurrentRow.Index;
            DataTable dt = (DataTable)dgv_Master.DataSource;
            string HiRxno = dt.Rows[i]["HiRxno"].ToString();
            string FixmedinsCode = dt.Rows[i]["FixmedinsCode"].ToString();
            string ID = dt.Rows[i]["ID"].ToString();
            presNo = dt.Rows[i]["HospRxno"].ToString();

            JObject joData = new JObject();
            joData.Add("hiRxno", HiRxno);                  //医保处方编号
            joData.Add("fixmedinsCode", FixmedinsCode);    //定点医疗机构编号
            joData.Add("drCode", DrInsuCode);                //撤销医师的医保医师代码
            joData.Add("undoDrName", DrName);            //撤销医师姓名
            joData.Add("undoDrCertType", "01");          //撤销医师证件类型
            joData.Add("undoDrCertno", DrCertNo);          //撤销医师证件号码
            joData.Add("undoRea", rtb_CancelReason.Text);               //撤销原因描述
            joData.Add("undoTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));              //撤销时间

            JObject joRtn7104 = invoker.invokeCenterServicePresCir("7104", JsonHelper.setCenterInparPresCirNew(joData));
            if (JsonHelper.parseCenterRtnValuePresCir(joRtn7104, out OutPut) != 0)
            {
                MessageBox.Show("【7104】电子处方撤销！" + OutPut);
                return;
            }
            else
            {
                //解密
                JValue encDataObj = (JValue)joRtn7104.GetValue("encData");
                string encData = encDataObj.ToString();
                string decDatas = SMUtil.decrypt(encData, Global.inf.appId, Global.inf.Secret);
                JObject joRtnEncDataObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(decDatas);

                //撤销电子处方上传更新IRIS表
                if (mIS.cancelPresCirUpload(joRtnEncDataObj, ID, HiRxno, FixmedinsCode, rtb_CancelReason.Text, DrInsuCode, DrName, DrCertNo, out string OutMsg) != 0)                
                {
                    MessageBox.Show("【7104】电子处方撤销成功,IRIS服务更新处方上传记录表失败!" + OutMsg);
                    return;
                }

                //电子处方上传成功后更新HIS处方状态
                if (hIS.updateHISPrecNoStatus(presNo, HiRxno, "C", out OutMsg) != 0)
                {
                    MessageBox.Show("【7104】电子处方撤销成功,IRIS服务更新处方上传记录表成功，更新HIS处方状态失败：" + OutMsg);
                    return;
                }

                MessageBox.Show("【7104】医保电子处方撤销成功！");
            }
        }

        private void btnReadCard_Click(object sender, EventArgs e)
        {
            if (tb_CertNo.Text == "")
            {
                MessageBox.Show("请先输入患者身份证号进行查找患者未结算处方信息！");
                return;
            }
            else
            {
                dgv_HISRegInfo.DataSource = null;
                dgv_PrescriptionInfo.DataSource = null;

                CertNo = tb_CertNo.Text;
                Global.pat.certNO = tb_CertNo.Text;
            }

            #region【查询HIS就诊信息-用身份证号查询患者当日的就诊记录】
            string outParam = "";
            DataTable dt1 = null;
            if (GetHISRegInfo(dtST.Text, dtED.Text, Global.pat.certNO, ref outParam,ref dt1) != 0)
            {
                MessageBox.Show(outParam);
                return;
            }

            dgv_HISRegInfo.DataSource = dt1;
            #endregion

            #region【调用医保平台获取医保登记信息-根据HIS就诊信息查找医保登记信息 (接诊医生、接诊科室)】
            /*
            if (GetInsuRegIDFromHIS(presAdmID, presAdmDoc, presAdmLoc, out Global.pat.mdtrtID, out outParam) != 0)
            {
                MessageBox.Show(outParam);
                return;
            }
            */
            #endregion

            presAdmDoc = dgv_HISRegInfo.Rows[0].Cells["doc"].Value.ToString();
            presAdmLoc = dgv_HISRegInfo.Rows[0].Cells["loc"].Value.ToString();
            presNo = dgv_HISRegInfo.Rows[0].Cells["prescNo"].Value.ToString();
            presAdmID = dgv_HISRegInfo.Rows[0].Cells["admID"].Value.ToString();
            Global.pat.adm_Dr = int.Parse(presAdmID);

            if (presNo == "") return;
            DataTable dt2 = null;
            //获取HIS处方明细信息
            if (GetHISPrescFeeInfo(presNo, ref outParam, ref dt2) != 0)
            {
                MessageBox.Show(outParam);
                return;
            }

            dgv_PrescriptionInfo.DataSource = dt2;
        }

        /// <summary>
        /// 获取HIS就诊信息
        /// </summary>
        /// <param name="dtST"></param>
        /// <param name="dtED"></param>
        /// <param name="PatInfo"></param>
        /// <param name="errMsg"></param>
        /// <param name="DT"></param>
        /// <returns></returns>
        private int GetHISRegInfo(string dtST, string dtED, string PatInfo, ref string errMsg, ref DataTable DT)
        {
            dynamic joTmp = new JObject();
            joTmp.Add("stDate", dtST);
            joTmp.Add("endDate", dtED);
            joTmp.Add("patInfo", PatInfo);

            JObject joRtnHISRegInfo = hIS.GetHISRegInfo(joTmp);

            if (JsonHelper.parseIrisRtnValue(joRtnHISRegInfo, out errMsg) != 0)
            {
                errMsg = "获取HIS患者就诊信息失败，请联系管理员！" + errMsg;
                return -1;
            }
            else
            {
                if ((joRtnHISRegInfo["result"]["rows"].ToString() == "[]"))
                {
                    errMsg = "查询HIS就诊信息结果为空！";
                    return -1;
                }
                else
                {
                    DT = (DataTable)joRtnHISRegInfo["result"]["rows"].ToObject(typeof(DataTable));
                    return 0;
                }
            }
        }

        /// <summary>
        /// 获取HIS费用明细信息
        /// </summary>
        /// <param name="PrescNo"></param>
        /// <param name="errMsg"></param>
        /// <param name="DT"></param>
        /// <returns></returns>
        private int GetHISPrescFeeInfo(string PrescNo, ref string errMsg, ref DataTable DT)
        {
            dynamic joTmp = new JObject();
            joTmp.Add("prescNo", PrescNo);

            JObject joRtnHISPrescFeeInfo = hIS.GetHISPrescFeeInfo(joTmp);

            if (JsonHelper.parseIrisRtnValue(joRtnHISPrescFeeInfo, out errMsg) != 0)
            {
                errMsg = "获取HIS患者处方信息失败，请联系管理员！" + errMsg;
                return -1;
            }
            else
            {
                if ((joRtnHISPrescFeeInfo["result"]["rows"].ToString() == "[]"))
                {
                    errMsg = "查询HIS处方信息结果为空！";
                    return -1;
                }
                else
                {
                    DT = (DataTable)joRtnHISPrescFeeInfo["result"]["rows"].ToObject(typeof(DataTable));
                    return 0;
                }
            }
        }

        /// <summary>
        /// 获取电子处方预核验入参
        /// </summary>
        /// <param name="AdmID"></param>
        /// <param name="prescNo"></param>
        /// <param name="outParam"></param>
        /// <returns></returns>
        private int GetPreVerificationInput(string AdmID, string prescNo, ref string outParam)
        {
            dynamic joTmp = new JObject();
            joTmp.Add("prescNo", prescNo);
            joTmp.Add("admID", AdmID);

            JObject joRtnPreVerificationData = hIS.GetPreVerificationData(joTmp);
            if (JsonHelper.parseIrisRtnValue(joRtnPreVerificationData, out outParam) != 0)
            {
                outParam = "获取处方流传预核验数据失败，请联系管理员！" + outParam;
                return -1;
            }
            else
            {
                if (joRtnPreVerificationData["dllinput"]["params"].ToString() == "[]")
                {
                    outParam = "获取处方流传预核验数据结果为空！";
                    return -1;
                }
                else
                {
                    //outParam = joRtnPreVerificationData["dllinput"]["params"].ToString();

                    JObject jo = JObject.Parse(joRtnPreVerificationData["dllinput"].ToString());
                    JArray ja = (JArray)jo["params"];

                    foreach (var item in ja)
                    {
                        outParam = item.ToString();
                    }
                }

                return 0;
            }
        }

        /// <summary>
        /// 医保患者参保信息获取
        /// </summary>
        /// <param name="OutParam"></param>
        /// <returns></returns>
        private int GetPersonInfo(ref string OutParam)
        {
            string errMsg;
            //打开读卡窗口，操作员选择读卡类型后进行读卡器读卡，再进行1101获取参保信息
            if (hBus.readCard(out ReadCardOutParam) != 0)
            {
                OutParam = JsonHelper.setExceptionJson(-100, "【医保电子处方流转业务】读卡失败！", ReadCardOutParam).ToString();
                return -1;
            }
            else
            {
                //展示患者信息界面
                if (hBus.showPatInfo(ReadCardOutParam, out patInfo) != 0)
                {
                    OutParam = "【医保电子处方流转业务】读卡成功，展示患者信息界面失败：" + patInfo;
                    return -1;
                }

                if (hBus.setGlobalPatAfaterShowPatInfo(patInfo, out errMsg) != 0)
                {
                    OutParam = JsonHelper.setExceptionJson(-1, "setGlobalPatAfaterShowPatInfo", errMsg).ToString();
                    return -1;
                }

                OutParam = patInfo;
                return 0;
            }
        }

        /// <summary>
        /// 医保电子处方流转前调用医保挂号和就诊信息上传获取最新的医保登记流水号
        /// </summary>
        /// <param name="Inparam"></param>
        /// <param name="MdtrtID"></param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        private int MedInsuRegisterAndVisitUpload(string patInfo, out string MdtrtID, out string Msg)
        {
            string errMsg;
            MdtrtID = "";
            Msg = "";

            try
            {
                if (hBus.setGlobalPatAfaterShowPatInfo(patInfo, out errMsg) != 0)
                {
                    Msg = JsonHelper.setExceptionJson(-1, "setGlobalPatAfaterShowPatInfo", errMsg).ToString();
                    return -1;
                }

                //显示登记面板
                string outParam;
                if (hBus.showOutPatRegisterForm(out outParam) != 0)
                {
                    Msg = JsonHelper.setExceptionJson(-1, "显示登记面板", outParam).ToString();
                    return -1;
                }
                JObject joReg = JObject.Parse(outParam);

                //医保挂号
                JObject jo2201Inpar = JObject.Parse(JsonHelper.getDestProperty(joReg, "data"));
                JObject jo2201Inpar_plain = JObject.Parse(JsonHelper.getDestProperty(joReg, "data"));
                jo2201Inpar = JObject.Parse(JsonHelper.setCenterInpar("2201", jo2201Inpar));
                jo2201Inpar_plain = JObject.Parse(JsonHelper.setCenterInpar_plain("2201", jo2201Inpar_plain));
                //此处先取到就诊信息上传的入参，只要挂号成功就保存到云HIS后台（保存后台需要用到2203入参）
                JObject jo2203Inpar = new JObject();
                JObject jo2203Inpar_plain = new JObject();
                jo2203Inpar.Add("mdtrtinfo", JObject.Parse(JsonHelper.getDestValue(joReg, "mdtrtinfo")));
                jo2203Inpar.Add("diseinfo", JArray.Parse(JsonHelper.getDestValue(joReg, "diseinfo")));
                JObject jo2201Rtn = invoker.invokeCenterService("2201", jo2201Inpar);
                if (JsonHelper.parseCenterRtnValue(jo2201Rtn, out errMsg) != 0)
                {
                    Msg = JsonHelper.setExceptionJson(-1, "医保挂号失败", errMsg).ToString();
                    return -1;
                }
                else
                {
                    MdtrtID = JsonHelper.getDestValue(jo2201Rtn, "output.data.mdtrt_id");
                    Global.pat.mdtrtID = MdtrtID;

                    //插入患者本次就诊用的参保信息
                    hBus.insertPatCurInsuInfo(patInfo, out outParam);

                    jo2203Inpar["mdtrtinfo"]["mdtrt_id"] = MdtrtID;
                    jo2203Inpar_plain = JObject.Parse(JsonHelper.setCenterInpar_plain("2203", jo2203Inpar));
                    jo2203Inpar = JObject.Parse(JsonHelper.setCenterInpar("2203", jo2203Inpar));
                    //门诊登记信息，插入云医保平台
                    jo2201Rtn.Add("validflag", 1);
                    jo2201Rtn.Add("regstate", 1);
                    jo2201Rtn.Add("type", 6);
                    Global.writeLog(jo2201Inpar_plain.ToString());
                    if (mIS.saveOutpatRegisterInfoPresCiru(jo2201Inpar_plain, jo2201Rtn, jo2203Inpar_plain, out errMsg) != 0)
                    {
                        Msg = JsonHelper.setExceptionJson(-1, "中心登记成功但医保平台保存失败，请联系管理员！", errMsg).ToString();
                        return -1;
                    }

                    //门诊登记信息，插入HIS就诊信息表
                    if (hIS.returnRegisterInfo(jo2203Inpar_plain, MdtrtID, out outParam) != 0)
                    {
                        Msg = JsonHelper.setExceptionJson(-1, "HIS平台保存登记信息", outParam).ToString();
                        return -1;
                    }

                    //门诊就诊信息上传                            
                    JObject jo2203Rtn = invoker.invokeCenterService("2203", jo2203Inpar);
                    if (JsonHelper.parseCenterRtnValue(jo2203Rtn, out errMsg) != 0)
                    {
                        Msg = JsonHelper.setExceptionJson(-1, "门诊就诊信息上传", errMsg).ToString();
                        return -1;
                    }

                    return 0;
                }
            }
            catch (Exception e)
            {
                Msg = JsonHelper.setExceptionJson(-1, "医保门诊挂号和就诊信息上传异常", e.Message).ToString();
                return -1;
            }

        }

        /// <summary>
        /// 组织电子处方电子签名入参
        /// </summary>
        /// <param name="sInput"></param>
        /// <returns></returns>
        private JObject MontageElcSignParam(string sInput)
        {
            JObject joPreCheckInfo = JObject.Parse(sInput);
            JObject joInput = new JObject();
            joInput.Add("rxTraceCode", JsonHelper.getDestValue(joPreCheckInfo, "RxTraceCode"));
            joInput.Add("hiRxno", JsonHelper.getDestValue(joPreCheckInfo, "HiRxno"));
            //joInput.Add("hospRxno", JsonHelper.getDestValue(joPreCheckInfo, "HospRxno"));
            joInput.Add("mdtrtId", JsonHelper.getDestValue(joPreCheckInfo, "MdtrtID"));
            joInput.Add("patnName", JsonHelper.getDestValue(joPreCheckInfo, "PatnName"));
            joInput.Add("psnCertType", JsonHelper.getDestValue(joPreCheckInfo, "PsnCertType"));
            joInput.Add("certno", JsonHelper.getDestValue(joPreCheckInfo, "Certno"));
            joInput.Add("fixmedinsName", Global.inf.hospitalName);
            joInput.Add("fixmedinsCode", Global.inf.hospitalNO);
            joInput.Add("drCode", JsonHelper.getDestValue(joPreCheckInfo, "DrCode"));
            joInput.Add("prscDrName", JsonHelper.getDestValue(joPreCheckInfo, "PrscDrName"));
            joInput.Add("pharDeptName", JsonHelper.getDestValue(joPreCheckInfo, "PharDeptName"));
            joInput.Add("pharDeptCode", JsonHelper.getDestValue(joPreCheckInfo, "PharDeptCode"));
            joInput.Add("pharProfttlCodg", ""); //审方药师职称编码phar_pro_tech_duty JsonHelper.getDestValue(joPreCheckInfo, "DrProfttlCodg")
            joInput.Add("pharProfttlName", ""); //审方药师职称名称 JsonHelper.getDestValue(joPreCheckInfo, "DrProfttlName")
            joInput.Add("pharCode", JsonHelper.getDestValue(joPreCheckInfo, "PharCode"));  //审方医保药师代码
            joInput.Add("pharCertType", "");
            joInput.Add("pharCertno", "");
            joInput.Add("pharName", JsonHelper.getDestValue(joPreCheckInfo, "PharName"));
            joInput.Add("pharPracCertNo", ""); //审方药师执业资格证号
            joInput.Add("pharChkTime", JsonHelper.getDestValue(joPreCheckInfo, "PharChkTime"));

            Global.writeLog("原始待签名处方信息：" + joInput.ToString());
            HospRxno = JsonHelper.getDestValue(joPreCheckInfo, "HospRxno");

            Global.pat.mdtrtID = JsonHelper.getDestValue(joPreCheckInfo, "MdtrtID");

            return joInput;
        }

        /// <summary>
        /// 组织电子处方上传入参
        /// </summary>
        /// <param name="sInput"></param>
        /// <returns></returns>
        private JObject MontagePresCiruUploadParam(JObject joPreCheckInfo, JObject joElectronicSignatureInfo)
        {
            JObject joInput = new JObject();
            Global.pat.mdtrtID = JsonHelper.getDestValue(joPreCheckInfo, "MdtrtID");
            HospRxno = JsonHelper.getDestValue(joPreCheckInfo, "HospRxno");
            Global.pat.name = JsonHelper.getDestValue(joPreCheckInfo, "PatnName");
            //joInput.Add("hospRxno", JsonHelper.getDestValue(joPreCheckInfo, "HospRxno"));
            joInput.Add("rxTraceCode", JsonHelper.getDestValue(joPreCheckInfo, "RxTraceCode"));
            joInput.Add("hiRxno", JsonHelper.getDestValue(joPreCheckInfo, "HiRxno"));
            joInput.Add("mdtrtId", JsonHelper.getDestValue(joPreCheckInfo, "MdtrtID"));
            joInput.Add("patnName", JsonHelper.getDestValue(joPreCheckInfo, "PatnName"));
            joInput.Add("psnCertType", JsonHelper.getDestValue(joPreCheckInfo, "PsnCertType"));
            joInput.Add("certno", JsonHelper.getDestValue(joPreCheckInfo, "Certno"));
            joInput.Add("fixmedinsName", Global.inf.hospitalName);
            joInput.Add("fixmedinsCode", Global.inf.hospitalNO);
            joInput.Add("drCode", JsonHelper.getDestValue(joPreCheckInfo, "DrCode"));
            joInput.Add("prscDrName", JsonHelper.getDestValue(joPreCheckInfo, "PrscDrName"));
            joInput.Add("pharDeptName", JsonHelper.getDestValue(joPreCheckInfo, "PharDeptName"));
            joInput.Add("pharDeptCode", JsonHelper.getDestValue(joPreCheckInfo, "PharDeptCode"));
            joInput.Add("pharProfttlCodg", ""); //审方药师职称编码phar_pro_tech_duty  JsonHelper.getDestValue(joPreCheckInfo, "DrProfttlCodg")
            joInput.Add("pharProfttlName", ""); //审方药师职称名称 JsonHelper.getDestValue(joPreCheckInfo, "DrProfttlName")
            joInput.Add("pharCode", JsonHelper.getDestValue(joPreCheckInfo, "PharCode"));  //审方医保药师代码
            joInput.Add("pharCertType", "");
            joInput.Add("pharCertno", "");
            joInput.Add("pharName", JsonHelper.getDestValue(joPreCheckInfo, "PharName"));
            joInput.Add("pharPracCertNo", ""); //审方药师执业资格证号

            joInput.Add("pharChkTime", JsonHelper.getDestValue(joPreCheckInfo, "PharChkTime"));

            Global.writeLog("电子处方上传前20位：" + joInput.ToString());

            joInput.Add("rxFile", JsonHelper.getDestValue(joElectronicSignatureInfo, "RxFile"));
            joInput.Add("signDigest", JsonHelper.getDestValue(joElectronicSignatureInfo, "SignDigest"));
            joInput.Add("extras", JsonHelper.getDestValue(joElectronicSignatureInfo, "Extras"));

            return joInput;
        }

        /// <summary>
        /// 医保电子处方上传预核验成功调用IRIS服务插入记录
        /// </summary>
        /// <param name="JoRtn"></param>
        /// <param name="OutMsg"></param>
        /// <returns></returns>
        public int insertPresCirPreResult(JObject JoInput, JObject JoRtn, out string OutMsg)
        {
            string errMsg = "";

            try
            {
                //string hiRxno = JsonHelper.getDestValue(JoRtn, "hiRxno");
                //string rxTraceCode = JsonHelper.getDestValue(JoRtn, "rxTraceCode");

                JObject joInParam = new JObject();

                joInParam.Add("Hospital_Dr", Global.inf.hospitalDr);
                joInParam.Add("Interface_Dr", Global.inf.interfaceDr);
                joInParam.Add("MdtrtID", Global.pat.mdtrtID);
                joInParam.Add("Adm_Dr", Global.pat.adm_Dr);

                joInParam.Add("HospRxno", JsonHelper.getDestValue(JoInput, "hospRxno"));
                joInParam.Add("MdtrtCertType", JsonHelper.getDestValue(JoInput, "mdtrtCertType"));
                joInParam.Add("MdtrtCertNo", JsonHelper.getDestValue(JoInput, "mdtrtCertNo"));

                if (JsonHelper.getDestValue(JoInput, "insuPlcNo")=="")
                    joInParam.Add("InsuPlcNo", Global.pat.insuplc_admdvs);
                else
                    joInParam.Add("InsuPlcNo", JsonHelper.getDestValue(JoInput, "insuPlcNo"));

                joInParam.Add("InitRxno", JsonHelper.getDestValue(JoInput, "initRxno"));
                joInParam.Add("RxTypeCode", JsonHelper.getDestValue(JoInput, "rxTypeCode"));
                joInParam.Add("PrscTime", JsonHelper.getDestValue(JoInput, "prscTime"));
                joInParam.Add("RxDrugCnt", JsonHelper.getDestValue(JoInput, "rxDrugCnt"));
                joInParam.Add("ValiDays", JsonHelper.getDestValue(JoInput, "mdtrtCertType"));
                joInParam.Add("ValiEndTime", JsonHelper.getDestValue(JoInput, "valiEndTime"));
                joInParam.Add("MedType", JsonHelper.getDestValue(JoInput, "mdtrtinfo.medType"));
                joInParam.Add("IptOtpNo", JsonHelper.getDestValue(JoInput, "mdtrtinfo.iptOtpNo"));
                joInParam.Add("OtpIptFlag", JsonHelper.getDestValue(JoInput, "mdtrtinfo.otpIptFlag"));
                joInParam.Add("PsnNo", JsonHelper.getDestValue(JoInput, "mdtrtinfo.psnNo"));
                joInParam.Add("PatnName", JsonHelper.getDestValue(JoInput, "mdtrtinfo.patnName"));

                if (JsonHelper.getDestValue(JoInput, "mdtrtinfo.PsnCertType")=="")
                    joInParam.Add("PsnCertType", "01");
                else
                    joInParam.Add("PsnCertType", JsonHelper.getDestValue(JoInput, "mdtrtinfo.PsnCertType"));

                joInParam.Add("Certno", JsonHelper.getDestValue(JoInput, "mdtrtinfo.certno"));
                joInParam.Add("PatnAge", JsonHelper.getDestValue(JoInput, "mdtrtinfo.patnAge"));
                joInParam.Add("Gend", JsonHelper.getDestValue(JoInput, "mdtrtinfo.gend"));
                joInParam.Add("PrscDeptName", JsonHelper.getDestValue(JoInput, "mdtrtinfo.prscDeptName"));
                joInParam.Add("PrscDeptCode", JsonHelper.getDestValue(JoInput, "mdtrtinfo.prscDeptCode"));
                joInParam.Add("DrCode", JsonHelper.getDestValue(JoInput, "mdtrtinfo.drCode"));
                joInParam.Add("PrscDrName", JsonHelper.getDestValue(JoInput, "mdtrtinfo.prscDrName"));
                joInParam.Add("DrProfttlCodg", JsonHelper.getDestValue(JoInput, "mdtrtinfo.drProfttlCodg"));
                joInParam.Add("DrProfttlName", JsonHelper.getDestValue(JoInput, "mdtrtinfo.drProfttlName"));

                joInParam.Add("MdtrtTime", JsonHelper.getDestValue(JoInput, "mdtrtinfo.mdtrtTime"));
                joInParam.Add("DiseCodg", JsonHelper.getDestValue(JoInput, "mdtrtinfo.diseCodg"));
                joInParam.Add("DiseName", JsonHelper.getDestValue(JoInput, "mdtrtinfo.diseName"));
                joInParam.Add("SpDiseFlag", JsonHelper.getDestValue(JoInput, "mdtrtinfo.spDiseFlag"));
                joInParam.Add("MaindiagCode", JsonHelper.getDestValue(JoInput, "mdtrtinfo.maindiagCode"));
                joInParam.Add("MaindiagName", JsonHelper.getDestValue(JoInput, "mdtrtinfo.maindiagName"));
                joInParam.Add("OccurTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                joInParam.Add("RxTraceCode", JsonHelper.getDestValue(JoRtn, "rxTraceCode"));
                joInParam.Add("HiRxno", JsonHelper.getDestValue(JoRtn, "hiRxno"));
                joInParam.Add("UpdateUserID", Global.user.ID);

                joInParam.Add("PharCode", JsonHelper.getDestValue(JoInput, "mdtrtinfo.pharCode"));
                joInParam.Add("PharName", JsonHelper.getDestValue(JoInput, "mdtrtinfo.pharName"));

                joInParam.Add("PharChkTime", JsonHelper.getDestValue(JoInput, "mdtrtinfo.pharChkTime"));
                joInParam.Add("PharDeptCode", JsonHelper.getDestValue(JoInput, "mdtrtinfo.pharDeptCode")); 
                joInParam.Add("PharDeptName", JsonHelper.getDestValue(JoInput, "mdtrtinfo.pharDeptName"));

                JObject joRtn = invoker.invokeInsuService(JsonHelper.setIrisInpar("09010096", joInParam).ToString(), "插入电子处方上传预核验信息");

                if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
                {
                    OutMsg = errMsg;
                    return -1;
                }
                else
                {
                    OutMsg = joRtn.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                OutMsg = "插入电子处方上传预核验信息：" + ex.Message;
                return -1;
            }           
        }

        /// <summary>
        /// 医保电子处方医保电子签名成功调用IRIS服务插入记录
        /// </summary>
        /// <param name="JoInput"></param>
        /// <param name="originalValue"></param>
        /// <param name="originalRxFile"></param>
        /// <param name="JoRtn"></param>
        /// <param name="OutMsg"></param>
        /// <returns></returns>
        public int insertPresCirSignResult(JObject JoInput,string originalValue,string originalRxFile, JObject JoRtn, out string OutMsg)
        {
            string errMsg = "";
            try
            {
                //string rxFile = JsonHelper.getDestValue(JoRtn, "rxFile");
                //string signDigest = JsonHelper.getDestValue(JoRtn, "signDigest");
                //string signCertSn = JsonHelper.getDestValue(JoRtn, "signCertSn");
                //string signCertDn = JsonHelper.getDestValue(JoRtn, "signCertDn");

                JObject joInParam = new JObject();

                joInParam.Add("Hospital_Dr", Global.inf.hospitalDr);
                joInParam.Add("Interface_Dr", Global.inf.interfaceDr);
                joInParam.Add("MdtrtID", Global.pat.mdtrtID);
                joInParam.Add("Adm_Dr", Global.pat.adm_Dr); 

                joInParam.Add("FixmedinsCode", JsonHelper.getDestValue(JoInput, "fixmedinsCode"));
                joInParam.Add("HospRxno", HospRxno);
                joInParam.Add("IptOtpNo", JsonHelper.getDestValue(JoInput, "iptOtpNo"));
                joInParam.Add("OriginalValue", originalValue);
                joInParam.Add("OriginalRxFile", originalRxFile);
                joInParam.Add("Extras", JsonHelper.getDestValue(JoInput, "extras"));
                joInParam.Add("OccurTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                joInParam.Add("RxFile", JsonHelper.getDestValue(JoRtn, "rxFile"));
                joInParam.Add("SignDigest", JsonHelper.getDestValue(JoRtn, "signDigest"));
                joInParam.Add("SignCertSn", JsonHelper.getDestValue(JoRtn, "signCertSn"));
                joInParam.Add("SignCertDn", JsonHelper.getDestValue(JoRtn, "signCertDn"));
                joInParam.Add("UpdateUserID", Global.user.ID);

                JObject joRtn = invoker.invokeInsuService(JsonHelper.setIrisInpar("09010097", joInParam).ToString(), "插入电子处方医保电子签名信息");

                if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
                {
                    OutMsg = errMsg;
                    return -1;
                }
                else
                {
                    OutMsg = joRtn.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                OutMsg = "插入电子处方医保电子签名信息：" + ex.Message;
                return -1;
            }
        }

        private void btn_QueryUploadInfo_Click(object sender, EventArgs e)
        {
            dgv_PresUploadInfo.DataSource = null;
            dgv_PresAuditResults.DataSource = null;

            string sqlStr = " SELECT * FROM BS_MedInsuPresCiruUploadRecord ";
            sqlStr = sqlStr + "WHERE Hospital_Dr=" + Global.inf.hospitalDr; //Upload=Y And 
            sqlStr = sqlStr + " and Interface_Dr= " + Global.inf.interfaceDr;
            sqlStr = sqlStr + " and OccurTime>'" + dt_ST_Process.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dt_ET_Process.Text + "'";
            sqlStr = sqlStr + " and Upload= 'Y'";
            if (tb_CertnoQuery.Text != "")
            {
                sqlStr = sqlStr + " and Certno='" + tb_CertnoQuery.Text + "'";
            }

            switch (rg_type.SelectedIndex)
            {
                case 1:
                    {
                        sqlStr = sqlStr + " and Upload='Y'";
                        break;
                    }
                case 2:
                    {
                        sqlStr = sqlStr + " and Upload='N'";
                        break;
                    }
            }

            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010100");
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询电子处方上传信息");

            DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
            
            if (dt.Rows.Count>0)
                dgv_PresUploadInfo.DataSource = dt;
        }

        private void uiButton5_Click(object sender, EventArgs e)
        {
            if (dgv_PresUploadInfo.DataSource == null)
            {
                MessageBox.Show("请先查询电子处方信息！");
                return;
            }

            string OutPut, errMsg;
            int i = dgv_PresUploadInfo.CurrentRow.Index;
            DataTable dt = (DataTable)dgv_PresUploadInfo.DataSource;
            string HiRxno = dt.Rows[i]["HiRxno"].ToString();
            string FixmedinsCode = dt.Rows[i]["FixmedinsCode"].ToString();
            string ID = dt.Rows[i]["ID"].ToString();
            string MdtrtId = dt.Rows[i]["MdtrtId"].ToString();
            string PsnName = dt.Rows[i]["PatnName"].ToString();
            string PsnCertType = dt.Rows[i]["PsnCertType"].ToString();
            string Certno = dt.Rows[i]["Certno"].ToString();

            if (PsnCertType == "")
                PsnCertType = "01";

            JObject joData = new JObject();
            joData.Add("hiRxno", HiRxno);                  //医保处方编号
            joData.Add("fixmedinsCode", FixmedinsCode);    //定点医疗机构编号
            joData.Add("mdtrtId", MdtrtId);                //医保就诊ID
            joData.Add("psnName", PsnName);            //姓名
            joData.Add("psnCertType", PsnCertType);          //撤销医师证件类型
            joData.Add("certno", Certno);          //撤销医师证件号码          
            JObject joRtn7106 = invoker.invokeCenterServicePresCir("7106", JsonHelper.setCenterInparPresCirNew(joData));
            if (JsonHelper.parseCenterRtnValuePresCir(joRtn7106, out OutPut) != 0)
            {
                MessageBox.Show("【7106】电子处方审核结果查询失败！" + OutPut);
                return;
            }
            else
            {
                //解密
                JValue encDataObj = (JValue)joRtn7106.GetValue("encData");
                string encData = encDataObj.ToString();
                string decDatas = SMUtil.decrypt(encData, Global.inf.appId, Global.inf.Secret);
                JObject joRtnEncDataObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(decDatas);

                JArray jaRtnEncDataObj = new JArray();
                jaRtnEncDataObj.Add(joRtnEncDataObj);                

                //DataTable dtRtn = (DataTable)joRtnEncDataObj["result"]["data"].ToObject(typeof(DataTable));
                DataTable dtRtn = (DataTable)jaRtnEncDataObj.ToObject(typeof(DataTable));
                dgv_PresAuditResults.DataSource = dtRtn;

                if (dgv_PresAuditResults.Rows.Count <= 0)
                    dgv_PresAuditResults.DataSource = null;

                //撤销电子处方上传更新IRIS表
                if (mIS.UpdatePresCirUpload(joRtnEncDataObj, ID, out string OutMsg) != 0)
                {
                    MessageBox.Show("【7106】电子处方审核结果查询成功,IRIS服务更新处方上传记录表失败!" + OutMsg);
                    return;
                }

                MessageBox.Show("【7106】电子处方审核结果查询成功！");
            }
        }

        private void tb_QueryPresPreCheck_Click(object sender, EventArgs e)
        {
            dgv_PresPreChekInfo.DataSource = null;
            //1.获取处方预核验表信息
            string sqlStr = " SELECT * FROM BS_MedInsuPresCiruUploadPreCheck ";
            sqlStr = sqlStr + " WHERE Hospital_Dr=" + Global.inf.hospitalDr;
            sqlStr = sqlStr + " and Interface_Dr= " + Global.inf.interfaceDr;            
            sqlStr = sqlStr + " and OccurTime>'" + dt_ST_PPC.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dt_ET_PPC.Text + "'";

            if (tb_PresCertNo.Text != "")
                sqlStr = sqlStr + " and CertNo='" + tb_PresCertNo.Text + "'";

            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010101");
            JObject joPresPreCheckInfo = invoker.invokeInsuService(joSettlQuery.ToString(), "查询电子处方上传预核验信息");

            DataTable dt = (DataTable)joPresPreCheckInfo["result"]["data"].ToObject(typeof(DataTable));

            if (dt.Rows.Count > 0)
                dgv_PresPreChekInfo.DataSource = dt;
        }

        private void btn_InsuQuery_Click(object sender, EventArgs e)
        {
            dgv_Main_tb.DataSource = null;
            dgv_DetlList_tb.DataSource = null;
            dgv_Otpinfo_tb.DataSource = null;
            dgv_DiseList_tb.DataSource = null;

            if (dgv_PresPreChekInfo.DataSource == null)
            {
                MessageBox.Show("请先查询电子处方预核验信息！");
                return;
            }        

            string OutPut, errMsg;
            int i = dgv_PresPreChekInfo.CurrentRow.Index;
            DataTable dt = (DataTable)dgv_PresPreChekInfo.DataSource;
            JObject joInput = new JObject();
            joInput.Add("fixmedinsCode", Global.inf.hospitalNO);       //定点医疗机构编号
            joInput.Add("hiRxno", dt.Rows[i]["HiRxno"].ToString());    //医保处方号
            joInput.Add("mdtrtId", dt.Rows[i]["MdtrtId"].ToString());  //医保就诊ID
            joInput.Add("ecToken", "");                                //电子凭证令牌
            joInput.Add("psnName", dt.Rows[i]["PatnName"].ToString()); //人员名称
            joInput.Add("psnCertType", "01");                          //人员证件类型
            joInput.Add("certno", dt.Rows[i]["Certno"].ToString());    //证件号码
            JObject joRtn7105 = invoker.invokeCenterServicePresCir("7105", JsonHelper.setCenterInparPresCirNew(joInput));
            if (JsonHelper.parseCenterRtnValuePresCir(joRtn7105, out OutPut) != 0)            
            {
                MessageBox.Show("【7105】电子处方信息查询失败" + OutPut);
                return;
            }
            else
            {
                //解密
                JValue encDataObj = (JValue)joRtn7105.GetValue("encData");
                string encData = encDataObj.ToString();
                string decDatas = SMUtil.decrypt(encData, Global.inf.appId, Global.inf.Secret);
                JObject joRtnEncDataObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(decDatas);

                JArray jaOtpinfo = new JArray();
                jaOtpinfo.Add(JObject.Parse(JsonHelper.getDestValue(joRtnEncDataObj, "rxOtpinfo")));
                JObject joOtpinfo = new JObject();
                joOtpinfo.Add("rxOtpinfoList", jaOtpinfo);

                JObject joData = new JObject();
                joData.Add("fixmedinsCode", JsonHelper.getDestValue(joRtnEncDataObj, "fixmedinsCode"));
                joData.Add("fixmedinsName", JsonHelper.getDestValue(joRtnEncDataObj, "fixmedinsName"));
                joData.Add("hiRxno", JsonHelper.getDestValue(joRtnEncDataObj, "hiRxno"));
                joData.Add("longRxFlag", JsonHelper.getDestValue(joRtnEncDataObj, "longRxFlag"));
                joData.Add("prscTime", JsonHelper.getDestValue(joRtnEncDataObj, "prscTime"));
                joData.Add("rxStasCodg", JsonHelper.getDestValue(joRtnEncDataObj, "rxStasCodg"));
                joData.Add("rxStasName", JsonHelper.getDestValue(joRtnEncDataObj, "rxStasName"));
                joData.Add("rxTypeCode", JsonHelper.getDestValue(joRtnEncDataObj, "rxTypeCode"));
                joData.Add("rxTypeName", JsonHelper.getDestValue(joRtnEncDataObj, "rxTypeName"));
                joData.Add("rxUsedStasCodg", JsonHelper.getDestValue(joRtnEncDataObj, "rxUsedStasCodg"));
                joData.Add("rxUsedStasName", JsonHelper.getDestValue(joRtnEncDataObj, "rxUsedStasName"));
                joData.Add("valiDays", JsonHelper.getDestValue(joRtnEncDataObj, "valiDays"));
                joData.Add("valiEndTime", JsonHelper.getDestValue(joRtnEncDataObj, "valiEndTime"));

                JArray jaDataList = new JArray();
                jaDataList.Add(joData);

                joRtnEncDataObj.Add("rxDataList", jaDataList);

                DataTable dt1 = (DataTable)joRtnEncDataObj["rxDataList"].ToObject(typeof(DataTable));
                DataTable dt2 = (DataTable)joRtnEncDataObj["rxDetlList"].ToObject(typeof(DataTable));
                DataTable dt3 = (DataTable)joOtpinfo["rxOtpinfoList"].ToObject(typeof(DataTable));
                DataTable dt4 = (DataTable)joRtnEncDataObj["rxDiseList"].ToObject(typeof(DataTable));

                dgv_Main_tb.DataSource = dt1;
                dgv_DetlList_tb.DataSource = dt2;
                dgv_Otpinfo_tb.DataSource = dt3;
                dgv_DiseList_tb.DataSource = dt4;

            }
        }

        /// <summary>
        /// 医保电子处方上传成功调用IRIS服务插入记录
        /// </summary>
        /// <param name="JoInput"></param>
        /// <param name="JoRtn"></param>
        /// <param name="OutMsg"></param>
        /// <returns></returns>
        public int insertPresCirUploadRecord(JObject JoInput, JObject JoRtn, out string OutMsg)
        {
            string errMsg = "";
            try
            {
                //string rxFile = JsonHelper.getDestValue(JoRtn, "rxFile");
                //string signDigest = JsonHelper.getDestValue(JoRtn, "signDigest");
                //string signCertSn = JsonHelper.getDestValue(JoRtn, "signCertSn");
                //string signCertDn = JsonHelper.getDestValue(JoRtn, "signCertDn");

                JObject joInParam = new JObject();

                joInParam.Add("Hospital_Dr", Global.inf.hospitalDr);
                joInParam.Add("Interface_Dr", Global.inf.interfaceDr);
                joInParam.Add("MdtrtID", Global.pat.mdtrtID);
                joInParam.Add("Adm_Dr", Global.pat.adm_Dr);

                joInParam.Add("HiRxno", JsonHelper.getDestValue(JoRtn, "hiRxno"));
                hiRxno = JsonHelper.getDestValue(JoRtn, "hiRxno");

                joInParam.Add("PatnName", JsonHelper.getDestValue(JoInput, "patnName"));

                joInParam.Add("RxTraceCode", JsonHelper.getDestValue(JoInput, "rxTraceCode"));
                joInParam.Add("PsnCertType", JsonHelper.getDestValue(JoInput, "psnCertType"));
                joInParam.Add("Certno", JsonHelper.getDestValue(JoInput, "certno"));
                joInParam.Add("FixmedinsName", JsonHelper.getDestValue(JoInput, "fixmedinsName"));
                joInParam.Add("FixmedinsCode", JsonHelper.getDestValue(JoInput, "fixmedinsCode"));
                joInParam.Add("DrCode", JsonHelper.getDestValue(JoInput, "drCode"));
                joInParam.Add("PrscDrName", JsonHelper.getDestValue(JoInput, "prscDrName"));
                joInParam.Add("PharDeptName", JsonHelper.getDestValue(JoInput, "pharDeptName"));
                joInParam.Add("PharDeptCode", JsonHelper.getDestValue(JoInput, "pharDeptCode"));
                joInParam.Add("PharCode", JsonHelper.getDestValue(JoInput, "pharCode"));
                joInParam.Add("PharName", JsonHelper.getDestValue(JoInput, "pharName"));
                joInParam.Add("PharChkTime", JsonHelper.getDestValue(JoInput, "pharChkTime"));
                joInParam.Add("RxFile", JsonHelper.getDestValue(JoInput, "rxFile"));
                joInParam.Add("SignDigest", JsonHelper.getDestValue(JoInput, "signDigest"));
                joInParam.Add("Extras", JsonHelper.getDestValue(JoInput, "extras"));

                joInParam.Add("RxStasCodg", JsonHelper.getDestValue(JoRtn, "rxStasCodg"));      
                joInParam.Add("RxStasName", JsonHelper.getDestValue(JoRtn, "rxStasName"));
                joInParam.Add("Upload", "Y");
                joInParam.Add("OccurTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                joInParam.Add("UpdateUserID", Global.user.ID);

                joInParam.Add("HospRxno", presNo); //HIS处方编号

                JObject joRtn = invoker.invokeInsuService(JsonHelper.setIrisInpar("09010098", joInParam).ToString(), "插入电子处方上传信息");

                if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
                {
                    OutMsg = errMsg;
                    return -1;
                }
                else
                {
                    OutMsg = joRtn.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                OutMsg = "插入电子处方上传信息：" + ex.Message;
                return -1;
            }
        }

        private void PrescriptionCirculation_Shown(object sender, EventArgs e)
        {
            GridViewSetter grdSetter = new GridViewSetter();         
            grdSetter.SetHeaderTextOfHISRegister(dgv_HISRegInfo);
            grdSetter.SetHeaderTextOfHISPrescFee(dgv_PrescriptionInfo);
            grdSetter.SetHeaderTextOfPresUploadInfo(dgv_Master);
            grdSetter.SetHeaderTextOfPresUploadProcessInfo(dgv_PresUploadInfo);
            grdSetter.SetHeaderTextOfPresPresAuditResults(dgv_PresAuditResults);
            grdSetter.SetHeaderTextOfPresPresCheckInfo(dgv_PresPreChekInfo);

            grdSetter.SetHeaderTextOfPresDataInfo(dgv_Main_tb);
            grdSetter.SetHeaderTextOfPresDetlListInfo(dgv_DetlList_tb);
            grdSetter.SetHeaderTextOfPresOtpinfoInfo(dgv_Otpinfo_tb);
            grdSetter.SetHeaderTextOfPresDiseListInfo(dgv_DiseList_tb);

            grdSetter.DatagridviewColumnWidthAdaptation(dgv_HISRegInfo);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_PrescriptionInfo);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_Master);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_PresUploadInfo);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_PresAuditResults);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_PresPreChekInfo);

            grdSetter.DatagridviewColumnWidthAdaptation(dgv_Main_tb);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_DetlList_tb);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_Otpinfo_tb);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_DiseList_tb);

            dtST.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dtED.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            dt_St.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dt_Et.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            dt_ST_Process.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dt_ET_Process.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            dt_ST_PPC.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dt_ET_PPC.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            tb_CertNo.Text = "620202197310200245";
            rg_type.SelectedIndex = 0;

            //获取医院用户信息
            JObject joUserInfo = hIS.GetHosUserInfo("");
            DataTable dt = (DataTable)joUserInfo["result"]["rows"].ToObject(typeof(DataTable));
            SetDBLKCombox(ref cbx_DocInfo, dt);
        }

        private void dgv_PrescriptionInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        /// <summary>
        /// 通过医保电子凭证获取参保信息进行医保挂号和就诊信息上传获取最新医保就诊ID
        /// </summary>
        /// <param name="PatInfo"></param>
        /// <param name="MdtrtIDNew"></param>
        /// <param name="OutMsg"></param>
        /// <returns></returns>
        public int GetPresCirInsuRegID(out string MdtrtIDNew, out string OutMsg)
        {
            MdtrtIDNew = "";
            string PatInfo = "";
            Global.pat.bPresCirul = true;
            if (GetPersonInfo(ref PatInfo) != 0)
            {
                OutMsg = "读卡失败：" + PatInfo;
                return -1;
            }

            if (MedInsuRegisterAndVisitUpload(PatInfo, out MdtrtIDNew, out OutMsg) != 0)
            {
                OutMsg = "医保挂号和医保就诊信息上传失败：" + OutMsg;
                return -1;
            }

            return 0;
        }

        /// <summary>
        /// 调用2202撤销医保挂号
        /// </summary>
        /// <param name="PsnNo"></param>
        /// <param name="MdtrtID"></param>
        /// <param name="IptotpNo"></param>
        /// <param name="OutMsg"></param>
        /// <returns></returns>
        public int CancelInsuReg(string PsnNo, string MdtrtID, string IptotpNo, out string OutMsg)
        {
            if ((PsnNo == "") || (MdtrtID == "") || (IptotpNo == ""))
            {
                OutMsg = "撤销医保挂号PsnNo或MdtrtID或IptotpNo入参不能为空";
                return -1;
            }
            //组织挂号入参
            JObject joCancleRegInpar = new JObject();            
            joCancleRegInpar.Add("psn_no", PsnNo);
            joCancleRegInpar.Add("mdtrt_id", MdtrtID);
            joCancleRegInpar.Add("ipt_otp_no", IptotpNo);

            JObject joRegInput = new JObject();
            joRegInput.Add("data", joCancleRegInpar);
            //取消挂号信息
            JObject jo2202Rtn = invoker.invokeCenterService("2202", JsonHelper.setCenterInpar("2202", joRegInput.ToString()));
            if (JsonHelper.parseCenterRtnValue(jo2202Rtn, out OutMsg) != 0)
            {
                OutMsg = "取消医保挂号失败：" + OutMsg;
                return -1;
            }
            else
            {
                OutMsg = "取消挂号成功";
            }

            return 0;
        }

        /// <summary>
        /// 获取最近一次电子凭证扫码挂号返回的医保就诊ID
        /// </summary>
        /// <param name="AdmID"></param>
        /// <param name="AdmDoc"></param>
        /// <param name="AdmLoc"></param>
        /// <param name="MdtrtID"></param>
        /// <param name="OutMsg"></param>
        /// <returns></returns>
        public int GetInsuRegIDFromHIS(string AdmID,string AdmDoc,string AdmLoc,out string MdtrtID,out string OutMsg)
        {
            MdtrtID = "";
            OutMsg = "";
            if ((AdmID == "") || (AdmDoc == "") || (AdmLoc == ""))
            {
                OutMsg = "获取HIS历史医保挂号信息AdmID或AdmDoc或AdmLoc入参不能为空";
                return -1;
            }
            
            string sqlStr = " SELECT Top 1 * FROM  BS_MedInsuRegisterInfo " //DateDiff(dd,OccurTime,getdate())=0
                          + " WHERE Type=3 And RegState=1 and OccurTime> '" + dtST.Text + "' And OccurTime<'" + dtED.Text + "'"
                          + " AND CertificateType='01' " //只取使用电子凭证就诊的挂号记录
                          + " and PersonalNO='" + Global.pat.psn_no + "' and Hospital_Dr='" + Global.inf.hospitalDr + "'"
                          + " and Adm_Dr='" + AdmID + "'"
                          + " And AdmInDepName='" + AdmLoc + "'"
                          + " And ChiefPhyDocName='" + AdmDoc + "'"
                          + " Order By OccurTime DESC ";

            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010062");
            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询门诊挂号");

            try
            {
                if (joRtn["result"]["data"].ToString() == "[]")
                {
                    OutMsg = "查询结果为空";
                    return -1;
                }
                else
                {
                    DataTable dtInsu = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
                    MdtrtID = dtInsu.Rows[0]["InsuRegID"].ToString();
                    return 0;
                }
            }
            catch (Exception eX)
            {
                MdtrtID = "";
                OutMsg = "查询获取HIS历史医保挂号信息异常：" + eX.Message;
                return -1;
            }
        }

        #region Base64加密解密
        /// <summary>
        /// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。
        /// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 ，
        /// 這樣共有62個字元，用來作為開始的64個數字，最後兩個用來作為數字的符號在不同的
        /// 系統中而不同。
        /// Base64加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Base64Encrypt(string str)
        {
            byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
            return Convert.ToBase64String(encbuff);
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Base64Decrypt(string str)
        {
            byte[] decbuff = Convert.FromBase64String(str);
            return System.Text.Encoding.UTF8.GetString(decbuff);
        }
        #endregion

        #region【文件转BASE64 （互转）】
        /// <summary>
        /// 文件转base64 
        /// </summary>
        /// <param name="fileName">文件全路径</param>
        /// <returns></returns>
        public string DocumentToBase64Str(string fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);

            byte[] bt = new byte[filestream.Length];
            //调用read读取方法
            filestream.Read(bt, 0, bt.Length);
            string base64Str = Convert.ToBase64String(bt);
            filestream.Close();
            return base64Str;
        }

        /// <summary>
        /// Base64字符串转文件并保存
        /// </summary>
        /// <param name="base64String">base64字符串</param>
        /// /// <param name="fileFullPath">保存的文件路径</param>
        /// <param name="fileName">保存的文件名</param>
        /// <returns>是否转换并保存成功</returns>
        public bool Base64StringToFile(string base64String, string fileFullPath, string fileName)
        {
            bool opResult = false;
            try
            {
                if (!Directory.Exists(fileFullPath))
                {
                    Directory.CreateDirectory(fileFullPath);
                }
                MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64String));
                FileStream fs = new FileStream(fileFullPath + "\\" + fileName, FileMode.OpenOrCreate, FileAccess.Write);
                byte[] b = stream.ToArray();
                fs.Write(b, 0, b.Length);
                fs.Close();

                opResult = true;
            }
            catch (Exception e)
            {
                MessageBox.Show("Base64字符串转文件并保存异常" + e.Message);
            }
            return opResult;
        }
        #endregion

    }
}
