using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DirectoryDownload.Business;
using DirectoryDownload.FormSetter;
using DirectoryDownload.Helper;

namespace DirectoryDownload
{
    public partial class Form1 : Form
    {
        #region  函数封装
        /// <summary>
        /// 查询医保目录
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="directoryType"></param>

        private void queryInterfaceBasicInfo(int index)
        {
            string errorMsg = "";
            switch (index)
            {
                case 0:
                    {
                        IrisInterfaceService iris = new IrisInterfaceService();
                        JObject joRtn = iris.getHospital();
                        if (JsonHelper.parseBusinessJson(joRtn, out errorMsg) != 0)
                        {
                            MessageBox.Show(errorMsg);
                            return;
                        }

                        //JArray jaParams = JArray.FromObject(joRtn["result"]["data"]);
                        JArray jaParams = JArray.Parse(JsonHelper.getJsonValue(joRtn,"result.data"));
                        if (jaParams.Count == 0)
                        {
                            MessageBox.Show("未查询到数据");
                            return;
                        }
                        DataTable dt = new DataTable();
                        dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
                        GridViewSetter intefaceGrid = new GridViewSetter();
                        intefaceGrid.SetHeaderTextOfInterfaceMaintain(dt, dgvInterface);

                        joRtn = iris.getInterface();
                        jaParams = new JArray();
                        jaParams = JArray.FromObject(joRtn["result"]["data"]);
                        if (jaParams.Count == 0)
                        {
                            DataTableSetter dts = new DataTableSetter();
                            dt = dts.setDgvInterfaceDataTable();

                        }
                        else
                        {
                            dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
                        }
                        dt.AcceptChanges();
                        dgvInterface.DataSource = dt;
                        dgvInterface.ReadOnly = true;
                        break;
                    }
            }
        }
        private void queryInsuDirectory(int currentPage, int pageSize,  int directoryType,int directoryDr,string code)
        {
            string dirCode = tbDirectoryCode.Text;
            string dirName = tbDircetoryName.Text;
            Sunny.UI.UIDataGridView dgv;
            Sunny.UI.UIPagination pg;
            if (tabControl1.SelectedIndex == 1)
            {
                dirCode = tbDirectoryCode.Text;
                dirName = tbDircetoryName.Text;
                dgv = dgvDirectoy;
                pg = pgDownload;
            }
            else 
            {
                dirName = tbCenterDirectoryFilter.Text;
                dirCode = tbInsuCode.Text;
                dgv = dgvCenterDirectory;
                pg = pgCenterDirect;
            }
            
            IrisInterfaceService irisService = new IrisInterfaceService();
            JObject joRtn = irisService.getDirectoryByPagination(currentPage, pageSize,code,directoryType,dirCode,dirName, directoryDr);

            if (joRtn["errorCode"].ToString() != "0")
            {
                MessageBox.Show("IRIS数据返回错误:" + joRtn["errorMessage"].ToString());
                return;
            }
            if (joRtn["result"]["Data"] == null)
            {
                MessageBox.Show("该节点不存在");
                return;
            }

            if (joRtn["result"]["TotalCount"].ToString() == "0")
            {
                MessageBox.Show("未查询到数据");
                dgv.DataSource = null;
                return;
            }

            DataTable dt = (DataTable)joRtn["result"]["Data"].ToObject(typeof(DataTable));
            int totalCount = int.Parse(joRtn["result"]["TotalCount"].ToString());
            pg.TotalCount = totalCount;
            pg.PageSize = 50;
            dgv.DataSource = dt;
            dgv.Columns[0].ReadOnly = true;
        }
        private void setHeaderTxt(int directoryType,  Sunny.UI.UIDataGridView dgv)
        {
            GridViewSetter gvdSetter = new GridViewSetter();
            switch (directoryType)
            {
                case 0://药品
                    {
                        gvdSetter.SetHeaderTextOfDrug(dgv);
                        break;
                    }
                case 1://诊疗
                    {
                        gvdSetter.SetHeaderTextOfMedicalService(dgv);
                        break;
                    }
                case 2://材料
                    {
                        gvdSetter.SetHeaderTextOfMaterials(dgv);
                        break;
                    }
                case 3://疾病诊断
                    {
                        gvdSetter.SetHeaderTextOfDiagnose(dgv);
                        break;
                    }
                case 4://手术
                    {
                        gvdSetter.SetHeaderTextOfDiagnose(dgv);
                        break;
                    }
                case 5://慢性病
                    {
                        gvdSetter.SetHeaderTextOfDiagnose(dgv);
                        break;
                    }
                case 6://DRGs
                    {
                        gvdSetter.SetHeaderTextOfDiagnose(dgv);
                        break; ;
                    }
                case 7://日间手术
                    {
                        gvdSetter.SetHeaderTextOfDiagnose(dgv);
                        break; ;
                    }
                case 8://字典表
                    {
                        gvdSetter.SetHeaderTextOfDictionary(dgv);
                        break;
                    }
            }
        }
        private void queryHISInsuDirectory(int directoryType, int pageIndex, int count, Sunny.UI.UIDataGridView dgv, int directoryDr)
        {
            string code = "";
            if (tabControl1.SelectedIndex == 0)
            {
                code = "09010034";
            }
            else if (tabControl1.SelectedIndex == 1)
            {

                if (rbgDirecType.SelectedIndex == 8)
                { code = "09010043"; }
                else
                code = "09010042";
            }
            else
            { code = "09010042"; }

            queryInsuDirectory(pageIndex, count, directoryType + 1, directoryDr,code); 
            setHeaderTxt(directoryType, dgv);
        }
        private void queryHISDirectory(int currentPage, int pageSize)
        {
            string directoryType = string.Empty;
            switch (rbgDirecType_C.SelectedIndex)
            {
                case 0:
                    {
                        directoryType = "drugs";
                        break;
                    }
                case 1:
                    {
                        directoryType = "diagnosi";
                        break;
                    }
                case 2:
                    {
                        directoryType = "consumables";
                        break;
                    }
            }

            dynamic joInParams = new JObject();
            joInParams.pagination = new JArray() as dynamic;
            joInParams.session = new JArray() as dynamic;
            JArray jaParams = new JArray();

            JObject joRtn = new JObject();
            InvokeHelper invoker = new InvokeHelper();
            string flag = "";
            //全部是先调HIS，然后再匹配医保平台的对照关系
            if (rbAll.Checked) {

                flag = "All";
                dynamic joParam = new JObject();
                joParam.code = "";
                joParam.descripts = "";
                joParam.FindType = new JArray();
                joParam.TypeID = "";
                joParam.alias = tbHISDirectoryFilter.Text;
                joParam.include = "Hosp";
                joParam.groupID = "324";
                joParam.hospID = GlobalVariables.hospitalDr;
                joParam.interfaceDr = cbxInterface.SelectedValue;
                joParam.type = directoryType;
                joParam.flag = flag;
                joParam.specInput = "";
                jaParams.Add(joParam);
                joInParams.Add("params", JArray.FromObject(jaParams));
                dynamic joSession = new JObject();
                joSession.userID = "";
                joSession.locID = "";
                joSession.groupID = "";
                joSession.hospID = "";
                joSession.sessionID = "";
                joSession.hospCode = "";
                joSession.language = "";
                joSession.hostName = "";
                joSession.ipv4 = "";
                joSession.ipv6 = "";
                joSession.mac = "";
                joInParams.session.Add(joSession);
                dynamic joPagination = new JObject();
                joPagination.pageSize = pageSize;
                //joPagination.pageSize = 2;
                joPagination.currentPage = currentPage;
                joPagination.sortColumn = "Code";
                joPagination.sortOrder = "asc";
                joInParams.pagination.Add(joPagination);
                //该服务需要改写，需要跟（CloudMedicalInsurancePlatform.Tables.MapRelation）进行关联
                //joInParams.code = "09010038";
                joInParams.code = "05111002";


                

                joRtn = invoker.invokeHISService(joInParams.ToString(), "查询HIS目录");
                //JObject joRtn = JObject.Parse(irisRtn);
                if (joRtn["errorCode"].ToString() != "0")
                {
                    MessageBox.Show("IRIS数据返回错误！");
                    return;
                }
                if (joRtn["result"]["Data"] == null)
                {
                    MessageBox.Show("该节点不存在");
                    return;
                }

                //传给医保平台，进行对照匹配
                joInParams = new JObject();
                joParam = new JObject();
                jaParams = new JArray();
                joParam.TotalCount = joRtn["result"]["TotalCount"];
                joParam.HospitalDr = GlobalVariables.hospitalDr;
                joParam.InterfaceDr = cbxInterface.SelectedValue;
                joParam.Data = joRtn["result"]["Data"];
                jaParams.Add(joParam);
                joInParams.code = "09010057";
                joInParams.Add("params", jaParams);
                joRtn = invoker.invokeInsuService(joInParams.ToString(), "转换HIS目录");


            }


            //已对照是先调云医保，然后再匹配HIS
            if (rbMaped.Checked) {
                flag = "Maped";
                dynamic joParam = new JObject();
                joParam.alias = tbHISDirectoryFilter.Text;
                joParam.HospitalDr = GlobalVariables.hospitalDr;
                joParam.InterfaceDr = cbxInterface.SelectedValue;
                joParam.hisType = directoryType;
                jaParams.Add(joParam);
                joInParams.Add("params", jaParams);
                dynamic joPagination = new JObject();
                joPagination.pageSize = pageSize;
                joPagination.currentPage = currentPage;
                joPagination.sortColumn = "HisCode";
                joPagination.sortOrder = "asc";
                joInParams.pagination.Add(joPagination);
                joInParams.code = "09010058";
                joRtn = invoker.invokeInsuService(joInParams.ToString(), "获取已对照目录分页");


                //传给HIS，进行匹配
                joInParams = new JObject();
                joParam = new JObject();
                jaParams = new JArray();
                joParam.TotalCount = joRtn["result"]["TotalCount"];
                joParam.type = directoryType;
                joParam.flag = flag;
                joParam.HospitalDr = GlobalVariables.hospitalDr;
                joParam.InterfaceDr = cbxInterface.SelectedValue;
                joParam.alias = tbHISDirectoryFilter.Text;
                joParam.include = "Hosp";
                joParam.groupID = "324";
                joParam.hospID = GlobalVariables.hospitalDr;
                joParam.compareArr = joRtn["result"]["Data"];
                jaParams.Add(joParam);
                joInParams.code = "05111002";
                joInParams.Add("params", jaParams);
                joRtn = invoker.invokeHISService(joInParams.ToString(), "转换HIS目录");

            }
            if (rbNoMaped.Checked) { flag = "NoMaped"; }
            DataTable dt = (DataTable)joRtn["result"]["Data"].ToObject(typeof(DataTable));         
            int totalCount = int.Parse(joRtn["result"]["TotalCount"].ToString());
            pgHISDirect.TotalCount = totalCount;
            pgHISDirect.PageSize = 50;
            dgvHISDirectory.DataSource = null;
            dgvHISDirectory.DataSource = dt;
            dgvHISDirectory.Columns[0].ReadOnly = true;
        }
        private void queryCenterDirectory_09010012(int currentPage, int pageSize)
        {
            string directoryType = string.Empty;
            switch (rbgDirecType_C.SelectedIndex)
            {
                case 0:
                    {
                        directoryType = "drugs";
                        break;
                    }
                case 1:
                    {
                        directoryType = "diagnosi";
                        break;
                    }
                case 2:
                    {
                        directoryType = "consumables";
                        break;
                    }
            }
            dynamic joInParams = new JObject();
            joInParams.pagination = new JArray() as dynamic;
            joInParams.session = new JArray() as dynamic;
            JArray jaParams = new JArray();

            dynamic joParams = new JObject();
            joParams.code = "";
            joParams.descripts = "";
            joParams.FindType = new JArray();
            joParams.TypeID = "";
            joParams.alias = "";
            joParams.include = "Hosp";
            joParams.groupID = "324";
            joParams.hospID = "25";
            joParams.type = directoryType;
            joParams.specInput = "";
            jaParams.Add(joParams);
            joInParams.Add("params", JArray.FromObject(jaParams));
            dynamic joSession = new JObject();
            joSession.userID = "";
            joSession.locID = "";
            joSession.groupID = "";
            joSession.hospID = "";
            joSession.sessionID = "";
            joSession.hospCode = "";
            joSession.language = "";
            joSession.hostName = "";
            joSession.ipv4 = "";
            joSession.ipv6 = "";
            joSession.mac = "";
            joInParams.session.Add(joSession);
            dynamic joPagination = new JObject();
            joPagination.pageSize = pageSize;
            joPagination.currentPage = currentPage;
            joPagination.sortColumn = "Code";
            joPagination.sortOrder = "asc";
            joInParams.pagination.Add(joPagination);
            joInParams.code = "09010012";

            IrisServices HisREST = new IrisServices();
            string sInput = joInParams.ToString();
            string sRtn = HisREST.Invoke(sInput);

            JObject jsonRtn = JObject.Parse(sRtn);
            if (jsonRtn["result"]["Data"] == null)
            {
                MessageBox.Show("该节点不存在");
                return;
            }

            JObject joRtn = JObject.Parse(sRtn);
            DataTable dt = (DataTable)joRtn["result"]["Data"].ToObject(typeof(DataTable));
            int totalCount = int.Parse(joRtn["result"]["TotalCount"].ToString());
            pgCenterDirect.TotalCount = totalCount;
            pgCenterDirect.PageSize = 50;
            dgvCenterDirectory.DataSource = dt;
        }
        private void Mapping()
        {
            int iHis = dgvHISDirectory.CurrentRow.Index;
            if (dgvCenterDirectory.CurrentRow == null)
             {
                MessageBox.Show("请查询中心目录");
                return;
            }
            int iCenter = dgvCenterDirectory.CurrentRow.Index;
            DataTable dtHis = (DataTable)dgvHISDirectory.DataSource;
            DataTable dtCenter = (DataTable)dgvCenterDirectory.DataSource;

            dgvHISDirectory.Rows[iHis].Cells["insuCode"].Value = dgvCenterDirectory.Rows[iCenter].Cells["Code"].Value.ToString();
            dgvHISDirectory.Rows[iHis].Cells["insuName"].Value = dgvCenterDirectory.Rows[iCenter].Cells["Name"].Value.ToString();
            

            int hisType = rbgDirecType_C.SelectedIndex + 1;
            string hisTypeName = rbgDirecType_C.Items[hisType-1].ToString(); ;
            
            JArray jaParams = new JArray();
            dynamic jsonTemp = new JObject();
            jsonTemp.ID = dtHis.Rows[iHis]["MapID"];
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.InterfaceDr =  int.Parse(cbxInterface.SelectedValue.ToString()); 
            jsonTemp.HISCode = dgvHISDirectory.Rows[iHis].Cells["itemCode"].Value;
            jsonTemp.HISName = dgvHISDirectory.Rows[iHis].Cells["itemDesc"].Value;
            jsonTemp.ChargeItemDr = dtHis.Rows[iHis]["ID"];
            jsonTemp.DiretoryDr = dtCenter.Rows[iCenter]["ID"];
            //1.已对照  2.已对照但未上传  3 已对照且已上传
            jsonTemp.State = 1;
            jsonTemp.HisType = hisType;
            jsonTemp.HisTypeName = hisTypeName;
            jsonTemp.InsuCode = dgvCenterDirectory.Rows[dgvCenterDirectory.CurrentRow.Index].Cells["Code"].Value;
            jsonTemp.InsuName = dgvCenterDirectory.Rows[dgvCenterDirectory.CurrentRow.Index].Cells["Name"].Value;
            jsonTemp.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            jaParams.Add(jsonTemp);

            JObject joIn = new JObject();
            joIn.Add(new JProperty("params", jaParams));
            joIn.Add("code", "09010040");
            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeInsuService(joIn.ToString(),"插入对照信息");
            //JObject joRtn = JObject.Parse(irisRtn);

            if ((int)joRtn["errorCode"] == 0)
            {
                dgvHISDirectory.Rows[iHis].Cells["flag"].Value = "已对照";
            }
            else
            {
                dgvHISDirectory.Rows[iHis].Cells["flag"].Value = "对照失败";
            }

        }
        private void CancleMapping()
        {
            int iHis = dgvHISDirectory.CurrentRow.Index;
            DataTable dtHis = (DataTable)dgvHISDirectory.DataSource;

            JArray jaParams = new JArray();
            dynamic jsonTemp = new JObject();
            jsonTemp.ID = dtHis.Rows[iHis]["MapID"];
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.InterfaceDr = GlobalVariables.interfaceDr;
            jsonTemp.HISCode = dgvHISDirectory.Rows[iHis].Cells["itemCode"].Value;
            jsonTemp.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            jaParams.Add(jsonTemp);

            JObject joIn = new JObject();
            joIn.Add(new JProperty("params", jaParams));
            joIn.Add("code", "09010041");
            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeInsuService(joIn.ToString(),"取消对照");

  

            if ((int)joRtn["errorCode"] == 0)
            {
                dgvHISDirectory.Rows[iHis].Cells["insuCode"].Value = "";
                dgvHISDirectory.Rows[iHis].Cells["insuName"].Value = "";
                dgvHISDirectory.Rows[iHis].Cells["flag"].Value = "未对照";
            }
            else
            {
                dgvHISDirectory.Rows[iHis].Cells["flag"].Value = "取消失败";
            }
        }
        #endregion
        public Form1()
        {

            try
            {
                //模拟接口
                dynamic joInterface = new JObject();
                joInterface.HospitalNO = "55";
                joInterface.HospitalName = "成都普瑞眼科医院";
                joInterface.InterfaceID = "C";
                joInterface.HospitalDr = 50;
                joInterface.InterfaceDr = 8;
                joInterface.CenterURL = "";
                joInterface.operatoType = "";
                joInterface.operatorNO = "0";
                joInterface.operatorName = "管理员";
                joInterface.hospitalMedInsuAreaCode = "";
                joInterface.ID = 1;
                GlobalVariables.Init(joInterface.ToString());
                InitializeComponent();
                rbgDirecType.SelectedIndex = 0;
                rbgDirecType_C.SelectedIndex = 0;
                rbSingleDown.Checked = true;

                this.rbgDirecType.ValueChanged += new Sunny.UI.UIRadioButtonGroup.OnValueChanged(this.rbgDirecType_ValueChanged);
                this.pgDownload.PageChanged += new Sunny.UI.UIPagination.OnPageChangeEventHandler(this.pgDownload_PageChanged);
                this.pgCenterDirect.PageChanged += new Sunny.UI.UIPagination.OnPageChangeEventHandler(this.pgCenterDirect_PageChanged);

                Font rowFont = new Font("UTF-8", 8);
                Font columnFont = new Font("UTF-8", 9);
                //dgvDirectoy.Font = font;
                dgvInterface.RowsDefaultCellStyle.Font = dgvCenterDirectory.RowsDefaultCellStyle.Font = dgvHISDirectory.RowsDefaultCellStyle.Font = dgvDirectoy.RowsDefaultCellStyle.Font = rowFont;
                dgvInterface.ColumnHeadersDefaultCellStyle.Font = dgvCenterDirectory.ColumnHeadersDefaultCellStyle.Font = dgvHISDirectory.ColumnHeadersDefaultCellStyle.Font = dgvDirectoy.ColumnHeadersDefaultCellStyle.Font = columnFont;

                rbgInterface.SelectedIndex = 0;
                rbAll.Checked = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show("异常：" + ex.Message);
            }


        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //rbgDirecType.ValueChanged += new Sunny.UI.UIRadioButtonGroup.OnValueChanged(rbgDirecType_ValueChanged);
            try
            {

                this.WindowState = FormWindowState.Maximized;
                ComboxSetter cbxSetter = new ComboxSetter();
                cbxSetter.setCbxInterfaceDataSource(cbxInterface);
                cbxSetter.setCbxInterfaceDataSource(cbxInterface_down);
                this.cbxInterface_down.SelectedValueChanged += new System.EventHandler(this.cbxInterface_down_SelectedValueChanged);

            }
            catch (Exception ex)
            {
                MessageBox.Show("异常：" + ex.Message);
            }
            
            
        }
        private void btnDownload_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            HisBusiness hisBus = new HisBusiness();
            if (rbgDirecType.SelectedIndex == 8)
            {
                dynamic joData = new JObject();
                joData.type = tbDicType.Text;
                joData.parentValue = "";
                joData.admdvs = "";
                joData.date = tbDicDate.Text;
                joData.vali_flag = "";

                if  (hisBus.downloadDicionary(joData, uiProcessBar1,out errorMessage) != 0)
                {
                    MessageBox.Show(errorMessage);
                    return;
                }
            }
            else
            {
                if (rbSingleDown.Checked)
                {
                    string ver = tbVer.Text;
                    if (tbVer.Text != "")
                    {
                        ver = tbVer.Text;
                    }
                    if (hisBus.SingleDownload(ver, rbgDirecType.SelectedIndex, uiProcessBar1, out errorMessage) != 0)
                    {
                        MessageBox.Show(errorMessage);
                        return;
                    }
                }
                if (rbAutoDown.Checked)
                {
                    if (hisBus.AutoDownload(rbgDirecType.SelectedIndex, uiProcessBar1, out errorMessage) != 0)
                    {
                        MessageBox.Show(errorMessage);
                        return;
                    }
                }
            }
            

            
            btnQuery_Click(sender, e);
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            int a = int.Parse(cbxInterface.SelectedValue.ToString());
            queryHISInsuDirectory(rbgDirecType.SelectedIndex, 1, 50, dgvDirectoy,a);
        }

        private void btnQueryHISDirectory_Click(object sender, EventArgs e)
        {
            queryHISDirectory(1, 50);
            GridViewSetter gridSetter = new GridViewSetter();
            gridSetter.SetHeaderTextOfMapping_HisDirectory(dgvHISDirectory);
        }

        private void btnQueryCenterDirectory_Click(object sender, EventArgs e)
        {
            int a = int.Parse(cbxInterface.SelectedValue.ToString());
            queryHISInsuDirectory(rbgDirecType_C.SelectedIndex, 1, 50, dgvCenterDirectory,a);
        }

        private void pgDownload_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            int a = int.Parse(cbxInterface.SelectedValue.ToString());
            queryHISInsuDirectory(rbgDirecType.SelectedIndex, pageIndex, count,dgvDirectoy,a);
        }

        private void pgHISDirect_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            queryHISDirectory(pageIndex, 50);
        }

        private void pgCenterDirect_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            pgDownload_PageChanged(null, pagingSource, pageIndex, count);
        }

        private void rbgDirecType_ValueChanged(object sender, int index, string text)
        {
            btnQuery_Click(null, new EventArgs());
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            CancleMapping();
        }

        private void tsmiMapping_Click(object sender, EventArgs e)
        {
            Mapping();
        }

        private void dgvHISDirectory_DoubleClick(object sender, EventArgs e)
        {
            int currentPage = pgHISDirect.ActivePage;
            string flag = dgvHISDirectory.Rows[dgvHISDirectory.CurrentRow.Index].Cells["flag"].Value.ToString();
            if (flag == "未对照")
            {
                Mapping();
            }
            else
            if (flag == "已对照")
            {
                CancleMapping();
            }
            if (rbAll.Checked)
            { queryHISDirectory(currentPage, 50); }
        }

        private void dgvDirectoy_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvDirectoy_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void uiRadioButton1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void dgvDirectoy_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dgvDirectoy.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dgvDirectoy.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dgvDirectoy.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        private void rbAutoDown_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void uiRadioButton2_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void btnIntefaceQuery_Click(object sender, EventArgs e)
        {
            queryInterfaceBasicInfo(rbgInterface.SelectedIndex);
        }

        private void rbgInterface_ValueChanged(object sender, int index, string text)
        {
            queryInterfaceBasicInfo(index);
        }

        private void btnInterfaceAdd_Click(object sender, EventArgs e)
        {
            dgvInterface.ReadOnly = false;
            DataTable dt = (DataTable)dgvInterface.DataSource;
            DataRow dtr = dt.NewRow();
            dt.Rows.Add(dtr);
            
        }

        private void btnInterfaceDelete_Click(object sender, EventArgs e)
        {
            dgvInterface.ReadOnly = true;
            DataTable dt = (DataTable)dgvInterface.DataSource;
            int index = dgvInterface.CurrentRow.Index;
            string ID = dgvInterface.CurrentRow.Cells["ID"].Value.ToString();
            string interfaceID = dgvInterface.CurrentRow.Cells["InterfaceID"].Value.ToString();
            DataRow[] drs = dt.Select("ID = " + ID + " AND InterfaceNO='" + interfaceID + "'");
            drs[0].Delete();
            dgvInterface.ReadOnly = false;
        }

        private void btnInterfceSave_Click(object sender, EventArgs e)
        {
            //int i = dgvInterface.CurrentRow.Index;
            //MessageBox.Show(dgvInterface.Rows[i].Cells[0].Value.ToString());
            //MessageBox.Show(dgvInterface.Rows[i].Cells[1].Value.ToString());
            //MessageBox.Show(dgvInterface.Rows[i].Cells["InterfaceID"].Value.ToString());
            //MessageBox.Show(dgvInterface.Rows[i].Cells["InterfaceName"].Value.ToString());

            DataTable dt = (DataTable)dgvInterface.DataSource;

            

            dynamic jsonInsert = new JObject();
            dynamic jsonUpdate = new JObject();
            dynamic jsonDelete = new JObject();
            JArray jsonArry_I = new JArray();
            JArray jsonArry_U = new JArray();
            JArray jsonArry_D = new JArray();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //MessageBox.Show(dt.Rows[i].RowState.ToString() + ':' + dt.Rows[i][0].ToString());            
                dynamic jsonTemp = new JObject();
                if (dt.Rows[i].RowState.ToString() == "Added")
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        //MessageBox.Show(dt.Columns[j].ColumnName);
                        jsonTemp.Add(new JProperty(dt.Columns[j].ColumnName, dt.Rows[i][j].ToString()));
                    }
                    jsonTemp.updateUserID = GlobalVariables.operatorNO;
                    jsonArry_I.Add(jsonTemp);

                }

                if (dt.Rows[i].RowState.ToString() == "Deleted")
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        string CloumnName = dt.Columns[j].ColumnName;
                        jsonTemp.Add(new JProperty(CloumnName, dt.Rows[i][CloumnName, DataRowVersion.Original].ToString()));
                    }
                    jsonTemp.updateUserID = GlobalVariables.operatorNO;
                    jsonArry_D.Add(jsonTemp);
                }

                if (dt.Rows[i].RowState.ToString() == "Modified")
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        //MessageBox.Show(dt.Columns[j].ColumnName);
                        jsonTemp.Add(new JProperty(dt.Columns[j].ColumnName, dt.Rows[i][j].ToString()));
                    }
                    jsonTemp.updateUserID = GlobalVariables.operatorNO;
                    jsonArry_U.Add(jsonTemp);
                }
            }
            jsonInsert.Add(new JProperty("params", jsonArry_I));
            jsonInsert.code = "09010005";
            jsonUpdate.Add(new JProperty("params", jsonArry_U));
            jsonUpdate.code = "09010005";
            jsonDelete.Add(new JProperty("params", jsonArry_D));
            jsonDelete.code = "09010006";

            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = new JObject();
            if (jsonArry_I.Count != 0)
            {
                 joRtn = invoker.invokeInsuService(jsonInsert.ToString(),"插入");

            }

            if (jsonArry_U.Count != 0)
            {
                 joRtn = invoker.invokeInsuService(jsonUpdate.ToString(), "更新");
            }

            if (jsonArry_D.Count != 0)
            {
                 joRtn = invoker.invokeInsuService(jsonDelete.ToString(), "删除");
            }

            string errorMessage = "";
            if (JsonHelper.parseBusinessJson(joRtn, out errorMessage) != 0)
            {
                MessageBox.Show("保存失败：" + errorMessage);
            }
            dgvInterface.ReadOnly = true;
        }

        private void dgvInterface_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            dgvInterface.ReadOnly = false;
        }

        private void uiRadioButtonGroup1_ValueChanged(object sender, int index, string text)
        {

        }

        private void dgvHISDirectory_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            

}

        private void dgvHISDirectory_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void uiGroupBox2_Click(object sender, EventArgs e)
        {

        }


        private void cbxInterface_down_SelectedValueChanged(object sender, EventArgs e)
        {
            //int i = 0;
            //if (int.TryParse(cbxInterface_down.SelectedValue.ToString(), out i))
            //{ GlobalVariables.interfaceDr_Download = i; }
            //else
            //{
            //    GlobalVariables.interfaceDr_Download = 0;
            //}
            GlobalVariables.interfaceDr_Download = int.Parse(cbxInterface_down.SelectedValue.ToString()) ;
            IrisInterfaceService iris = new IrisInterfaceService();
            JObject joInterface = iris.getInterface(cbxInterface_down.SelectedValue.ToString());
            //赋值
            GlobalVariables.hospitalNO = (string)joInterface["HospitalNO"];
            GlobalVariables.hospitalDr = (int)joInterface["HospitalDr"];
            GlobalVariables.interfaceNO = (string)joInterface["InterfaceNO"];
            GlobalVariables.interfaceDr = (int)joInterface["ID"];
            GlobalVariables.centerURL = (string)joInterface["CenterURL"];
            GlobalVariables.businessDllName = (string)joInterface["DLLName"];
            GlobalVariables.patientMedInsuAreaCode = (string)joInterface["AreaCode"];
        }

        private void panel5_Paint(object sender, PaintEventArgs e)
        {

        }

        private void rbAll_ValueChanged(object sender, bool value)
        {
            btnQueryHISDirectory_Click(null,new EventArgs());
        }

        private void rbMaped_CheckedChanged(object sender, EventArgs e)
        {
            queryHISDirectory(1, 50);
        }

        private void rbNoMaped_CheckedChanged(object sender, EventArgs e)
        {
            queryHISDirectory(1, 50);
        }

        private void pgHISDirect_Click(object sender, EventArgs e)
        {

        }

        private void cmsMapping_Opening(object sender, CancelEventArgs e)
        {

        }

        private void 测试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void panel6_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tbCenterDirectoryFilter_TextChanged(object sender, EventArgs e)
        {

        }

        private void uiTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void dgvCenterDirectory_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void cmsUpdateAuxInfo_Opening(object sender, CancelEventArgs e)
        {

        }

        private void 更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void cbxInterface_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void uiButton2_Click(object sender, EventArgs e)
        {

        }
    }


}
