using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Business;
using PTMedicalInsurance.FormSetter;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
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;

namespace PTMedicalInsurance.Forms
{
    public partial class MaintainBasicData : Form
    {

        CenterBusiness cBus = new CenterBusiness();
        HisMainBusiness hBus = new HisMainBusiness();
        HisIrisServices hIS = new HisIrisServices();
        MIIrisServices mIS = new MIIrisServices();
        InvokeHelper invoker = new InvokeHelper();

        public MaintainBasicData()
        {
            InitializeComponent();
            rbgInterface.SelectedIndex = 0;
            this.dgvInterface.DataError += delegate (object sender, DataGridViewDataErrorEventArgs e) { };
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {

        }

        private void btnIntefaceQuery_Click(object sender, EventArgs e)
        {
            queryInterfaceBasicInfo(0);
        }

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

        #region 接口维护
        private void queryInterfaceBasicInfo(int index)
        {
            string errorMsg = "";
            switch (index)
            {
                case 0:
                    {
                        JObject joRtn = mIS.DynamicQuery("SELECT ID, Code, Descripts, HisHospital_Dr FROM SQLUser.CB_Hospital ","查询医保平台医院表");
                        if (JsonHelper.parseIrisRtnValue(joRtn, out errorMsg) != 0)
                        {
                            MessageBox.Show(errorMsg);
                            return;
                        }

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

                        joRtn = mIS.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;
                    }
            }
        }
        #endregion

        private void btnInterfaceAdd_Click(object sender, EventArgs e)
        {
            dgvInterface.ReadOnly = false;
            DataTable dt = (DataTable)dgvInterface.DataSource;
            if (dt == null)
            {
                MessageBox.Show("请先点击查询");
                return;
            }
            DataRow dtr = dt.NewRow();
            dtr["UseFlag"] = "True";
            dtr["InsuRegionDr"] = 12;
            dtr["InsuRegionFlag"] = "0";
            //dtr["InsuCurrencyCataLogue"] = "0";
            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 = dt.Rows[index]["ID"].ToString();
            string interfaceID = dgvInterface.CurrentRow.Cells["InterfaceNO"].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)
        {
            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);
                        if (dt.Columns[j].ColumnName == "HospitalDr")
                        {
                            jsonTemp.Add(new JProperty("HospitalDr", Global.inf.hospitalDr));
                        }
                        else
                        {
                            jsonTemp.Add(new JProperty(dt.Columns[j].ColumnName, dt.Rows[i][j].ToString()));
                        }

                    }
                    jsonTemp.updateUserID = Global.user.ID;
                    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 = Global.user.ID;
                    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 = Global.user.ID;
                    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.parseIrisRtnValue(joRtn, out errorMessage) != 0)
            {
                MessageBox.Show("保存失败：" + errorMessage);
            }
            else
            {
                MessageBox.Show("保存成功！");
            }
            dgvInterface.ReadOnly = true;
        }
    }
}
