/******************************************************************************
 * 文件名称: DataImoport.cs
 * 文件说明: 医保目录数据导入
 * 当前版本: V1.0
 * 创建日期: 2022-04-12
 *
 * 2020-04-12: 增加GetDrugsJsonByTxt方法
 * 2020-04-12: 增加GetMedicalServiceJsonByTxt方法
 * 2020-04-12: 增加 GetMaterialJsonByTxt 方法
 * 2020-04-14: 增加 GetDiagnoseJsonByTxt 方法
 * 2020-04-14: 增加 GetOperationJsonByTxt 方法
 * 2020-04-14: 增加 applyDataToIris 方法
 * 2020-04-14: 增加 importDataToIrisByTxt 方法
 * 2020-04-14: 增加 GetOperationJsonByTxt 方法
 * 2020-04-14: 增加 GetOperationJsonByTxt 方法
 * 2020-04-14: 增加 GetOperationJsonByTxt 方法
 * 2020-04-14: 增加 GetOperationJsonByTxt 方法


******************************************************************************/
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DirectoryDownload.Business;
using DirectoryDownload.Helper;

namespace DirectoryDownload
{
    class DataImoport
    {
        /// <summary>
        /// 读取TXT后，Array中的空值会返回NULL，将其转换为"".应有其他方式处理，后面再优化
        /// 明天试试Convert.ToString(a)
        /// </summary>
        /// <param name="arrayValue"></param>
        /// <returns></returns>
        private string  convertArrayNull(string arrayValue)
        {
            string returnValue = string.Empty;
            if (arrayValue == "null")
            {
                returnValue = "";
            }
            else
            {
                returnValue = arrayValue;
            }
            return returnValue;
        }
        /// <summary>
        /// 从TXT文件中获取药品数据，并组装成JSON
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private JObject GetDrugsJsonByTxt(string[] arr)
        {
            dynamic jsonTemp = new JObject();
            jsonTemp.ID = "";
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.InterfaceDr = GlobalVariables.interfaceDr_Download;
            jsonTemp.Code = arr[0];
            jsonTemp.Name = arr[7];
            jsonTemp.HisType = "1";
            jsonTemp.HisTypeName = "药品";
            jsonTemp.LocateCode = "";
            jsonTemp.LocateName = "";
            jsonTemp.DosageFormCode = arr[9];
            jsonTemp.DosageFormName = arr[10];
            jsonTemp.CategoryCode = arr[11];
            jsonTemp.CategoryName = arr[12];
            jsonTemp.Specification = arr[13];
            jsonTemp.SpecificationCode = arr[14];
            jsonTemp.UnitOfPackag = arr[43];
            jsonTemp.UnitOfValuation = arr[40];
            jsonTemp.StartDate = convertArrayNull(arr[37]);
            jsonTemp.EndDate = convertArrayNull(arr[38]);
            jsonTemp.PinyinSearchCode = arr[51];
            jsonTemp.Instructions = arr[36];
            jsonTemp.ExceptContent = "";
            jsonTemp.Connotation = "";
            jsonTemp.ValidFlag = 1;// convertArrayNull(arr[79]);
            jsonTemp.Note = arr[78];
            jsonTemp.VersionNO = arr[83];
            jsonTemp.VersionName = arr[84];
            jsonTemp.UseFlag = 1;
            jsonTemp.DrugSafetyStandardCode = arr[9];
            jsonTemp.ApprovalNO = arr[56];
            jsonTemp.SpecialFlag = convertArrayNull(arr[62]);
            jsonTemp.LimitFlag = convertArrayNull(arr[58]);
            jsonTemp.LimitRange = arr[57];
            jsonTemp.UniqueRecordNO = arr[79];
            jsonTemp.Manufacturers = arr[53];
            return jsonTemp;
        }

        /// <summary>
        /// 从TXT文件中获取诊疗数据，并组装成JSON
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private JObject GetMedicalServiceJsonByTxt(string[] arr)
        {
            dynamic jsonTemp = new JObject();
            jsonTemp.ID = "";
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.InterfaceDr = GlobalVariables.interfaceDr_Download;
            jsonTemp.Code = arr[0];
            jsonTemp.Name = arr[9];
            jsonTemp.HisType = "2";
            jsonTemp.HisTypeName = "诊疗";
            jsonTemp.LocateCode = "";
            jsonTemp.LocateName = "";
            jsonTemp.DosageFormCode = arr[9];
            jsonTemp.DosageFormName = arr[10];
            jsonTemp.CategoryCode = arr[8];
            jsonTemp.CategoryName = arr[12];
            jsonTemp.Specification = "";
            jsonTemp.SpecificationCode = "";
            jsonTemp.UnitOfPackag = "";
            jsonTemp.UnitOfValuation = convertArrayNull(arr[3]);
            jsonTemp.StartDate = convertArrayNull(arr[11]);
            jsonTemp.EndDate = convertArrayNull(arr[12]);
            ////jsonTemp.PinyinSearchCode = SpellCodeHelper.GetFirstPYLetter(arr[9]);
            jsonTemp.Instructions = arr[3];
            jsonTemp.ExceptContent = arr[4];
            jsonTemp.Connotation = arr[5];
            jsonTemp.ValidFlag = arr[6];
            jsonTemp.Note = arr[7];
            jsonTemp.VersionNO = arr[14];
            jsonTemp.VersionName = arr[15];
            jsonTemp.UseFlag = 1;
            jsonTemp.DrugSafetyStandardCode = "";
            jsonTemp.ApprovalNO = "";
            jsonTemp.SpecialFlag = "";
            jsonTemp.LimitFlag = "";
            jsonTemp.LimitRange = "";
            jsonTemp.UniqueRecordNO = arr[13];
            return jsonTemp;
        }

        /// <summary>
        /// 从TXT文件中获取材料数据，并组装成JSON
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private JObject GetMaterialJsonByTxt(string[] arr)
        {
            dynamic jsonTemp = new JObject();
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.ID = "";
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.InterfaceDr = GlobalVariables.interfaceDr_Download;
            jsonTemp.Code = arr[0];
            jsonTemp.Name = arr[5];
            jsonTemp.HisType = "3";
            jsonTemp.HisTypeName = "材料";
            jsonTemp.LocateCode = "";
            jsonTemp.LocateName = "";
            jsonTemp.DosageFormCode = "";
            jsonTemp.DosageFormName = "";
            jsonTemp.CategoryCode = "";
            jsonTemp.CategoryName = "";
            jsonTemp.Specification = arr[7];
            jsonTemp.SpecificationCode = arr[6];
            jsonTemp.UnitOfPackag = arr[15];
            jsonTemp.UnitOfValuation = convertArrayNull(arr[35]);
            jsonTemp.StartDate = convertArrayNull(arr[46]);
            jsonTemp.EndDate = convertArrayNull(arr[47]);
            //jsonTemp.PinyinSearchCode = SpellCodeHelper.GetFirstPYLetter(arr[5]);
            jsonTemp.Instructions = arr[27];
            jsonTemp.ExceptContent = "";
            jsonTemp.Connotation = "";
            jsonTemp.ValidFlag = arr[67];
            jsonTemp.Note = arr[7];
            jsonTemp.VersionNO = arr[69];
            jsonTemp.VersionName = arr[70];
            jsonTemp.UseFlag = 1;
            jsonTemp.DrugSafetyStandardCode = "";
            jsonTemp.ApprovalNO = "";
            jsonTemp.SpecialFlag = "";
            jsonTemp.LimitFlag = convertArrayNull(arr[33]);
            jsonTemp.LimitRange = arr[34];
            jsonTemp.UniqueRecordNO = arr[68];
            jsonTemp.Manufacturers = arr[59];
            return jsonTemp;
        }

        /// <summary>
        /// 从TXT文件中获取诊断数据，并组装成JSON
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private JObject GetDiagnoseJsonByTxt(string[] arr)
        {
            dynamic jsonTemp = new JObject();
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.ID = "";
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.InterfaceDr = GlobalVariables.interfaceDr_Download;
            jsonTemp.Code = arr[10];
            jsonTemp.Name = arr[11];
            jsonTemp.HisType = "4";
            jsonTemp.HisTypeName = "诊断";
            jsonTemp.LocateCode = "";
            jsonTemp.LocateName = "";
            jsonTemp.DosageFormCode = "";
            jsonTemp.DosageFormName = "";
            jsonTemp.CategoryCode = "";
            jsonTemp.CategoryName = "";
            jsonTemp.Specification = "";
            jsonTemp.SpecificationCode = "";
            jsonTemp.UnitOfPackag = "";
            jsonTemp.UnitOfValuation = "";
            jsonTemp.StartDate = "";
            jsonTemp.EndDate = "";
            //jsonTemp.PinyinSearchCode = SpellCodeHelper.GetFirstPYLetter(arr[11]);
            jsonTemp.Instructions = "";
            jsonTemp.ExceptContent = "";
            jsonTemp.Connotation = "";
            jsonTemp.ValidFlag = arr[18];
            jsonTemp.Note = arr[17];
            jsonTemp.VersionNO = arr[22];
            jsonTemp.VersionName = arr[23];
            jsonTemp.UseFlag = 1;
            jsonTemp.DrugSafetyStandardCode = "";
            jsonTemp.ApprovalNO = "";
            jsonTemp.SpecialFlag = "";
            jsonTemp.LimitFlag = "";
            jsonTemp.LimitRange = "";
            jsonTemp.UniqueRecordNO = arr[19];
            jsonTemp.Manufacturers = "";
            return jsonTemp;
        }

        /// <summary>
        /// 慢性病
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private JObject GetChronicDiseaseJsonByTxt(string[] arr)
        {
            dynamic jsonTemp = new JObject();
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.ID = "";
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.InterfaceDr = GlobalVariables.interfaceDr_Download;
            jsonTemp.Code = arr[0];
            jsonTemp.Name = arr[1];
            jsonTemp.HisType = "6";
            jsonTemp.HisTypeName = "慢性病";
            jsonTemp.LocateCode = "";
            jsonTemp.LocateName = "";
            jsonTemp.DosageFormCode = "";
            jsonTemp.DosageFormName = "";
            jsonTemp.CategoryCode = arr[14];
            jsonTemp.CategoryName = arr[15];
            jsonTemp.Specification = "";
            jsonTemp.SpecificationCode = "";
            jsonTemp.UnitOfPackag = "";
            jsonTemp.UnitOfValuation = "";
            jsonTemp.StartDate = "";
            jsonTemp.EndDate = "";
            //jsonTemp.PinyinSearchCode = SpellCodeHelper.GetFirstPYLetter(arr[2]);
            jsonTemp.Instructions = "";
            jsonTemp.ExceptContent = "";
            jsonTemp.Connotation = arr[10];
            jsonTemp.ValidFlag = arr[5];
            jsonTemp.Note = arr[4];
            jsonTemp.VersionNO = arr[9];
            jsonTemp.VersionName = arr[11];
            jsonTemp.UseFlag = 1;
            jsonTemp.DrugSafetyStandardCode = "";
            jsonTemp.ApprovalNO = "";
            jsonTemp.SpecialFlag = "";
            jsonTemp.LimitFlag = "";
            jsonTemp.LimitRange = "";
            jsonTemp.UniqueRecordNO = arr[6];
            jsonTemp.Manufacturers = "";
            return jsonTemp;
        }

        /// <summary>
        /// 从TXT文件中获取手术数据，并组装成JSON
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private JObject GetOperationJsonByTxt(string[] arr)
        {
            dynamic jsonTemp = new JObject();
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.ID = "";
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.InterfaceDr = GlobalVariables.interfaceDr_Download;
            jsonTemp.Code = arr[10];
            jsonTemp.Name = arr[11];
            jsonTemp.HisType = "5";
            jsonTemp.HisTypeName = "手术";
            //jsonTemp.PinyinSearchCode = SpellCodeHelper.GetFirstPYLetter(arr[11]);
            jsonTemp.ValidFlag = arr[18];
            jsonTemp.Note = arr[17];
            jsonTemp.VersionNO = arr[22];
            jsonTemp.VersionName = arr[23];
            jsonTemp.UseFlag = 1;
            jsonTemp.UniqueRecordNO = arr[19];
            return jsonTemp;
        }

        /// <summary>
        /// DRGs
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private JObject GetDRGsJsonByTxt(string[] arr)
        {
            dynamic jsonTemp = new JObject();
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.ID = "";
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.InterfaceDr = GlobalVariables.interfaceDr_Download;
            jsonTemp.Code = arr[1];
            jsonTemp.Name = arr[2];
            jsonTemp.HisType = "7";
            jsonTemp.HisTypeName = "DRGs";
            jsonTemp.Connotation = arr[10];
            //jsonTemp.PinyinSearchCode = SpellCodeHelper.GetFirstPYLetter(arr[11]);
            jsonTemp.ValidFlag = arr[5];
            jsonTemp.Note = arr[11];
            jsonTemp.VersionNO = arr[9];
            jsonTemp.VersionName = arr[12];
            jsonTemp.UseFlag = 1;
            jsonTemp.UniqueRecordNO = arr[6];
            return jsonTemp;
        }

        private JObject GetDaySurgeryJsonByTxt(string[] arr)
        {
            dynamic jsonTemp = new JObject();
            jsonTemp.updateUserID = GlobalVariables.operatorNO;
            jsonTemp.ID = "";
            jsonTemp.HospitalDr = GlobalVariables.hospitalDr;
            jsonTemp.InterfaceDr = GlobalVariables.interfaceDr_Download;
            jsonTemp.Code = arr[1];
            jsonTemp.Name = arr[2];
            jsonTemp.HisType = "8";
            jsonTemp.HisTypeName = "日间手术";
            jsonTemp.Connotation = arr[8];
            //jsonTemp.PinyinSearchCode = SpellCodeHelper.GetFirstPYLetter(arr[11]);
            jsonTemp.ValidFlag = arr[3];
            jsonTemp.Note = arr[9];
            jsonTemp.VersionNO = arr[7];
            jsonTemp.VersionName = arr[10];
            jsonTemp.UseFlag = 1;
            jsonTemp.UniqueRecordNO = arr[4];
            return jsonTemp;
        }

        /// <summary>
        /// 提交数据给IRIS
        /// </summary>
        /// <param name="code"></param>
        /// <param name="jaParam"></param>
        /// <returns></returns>
        private JObject applyDataToIris(string code, JArray jaParam)
        {
            JObject joIn = new JObject();
            JObject joRtn = new JObject();
            string outParam = "";
            try
            {
                
                joIn.Add(new JProperty("params", jaParam));
                joIn.Add("code", code);
                joIn.Add("updateUserID", GlobalVariables.operatorNO);
                InvokeHelper invoker = new InvokeHelper();
                string sInput = joIn.ToString();
                joRtn = invoker.invokeInsuService(sInput, "applyDataToIris");
                outParam = joRtn.ToString();
                return joRtn;
            }
            catch (Exception ex)
            {
                joRtn = JsonHelper.getIrisExceptionJson(-1, "applyDataToIris", ex.Message);
                outParam = joRtn.ToString();
                return joRtn;
            }           
        }
        /// <summary>
        /// 从TXT里导数据到IRIS
        /// </summary>
        /// <param name="txtPath"></param>
        /// <param name="singleRows"></param>
        /// <param name="direcType"></param>
        /// <param name="processBar"></param>
        /// <returns></returns>
        public JObject importDataToIrisByTxt(string txtPath, int size, int direcType, Sunny.UI.UIProcessBar processBar)
        {
            int errorCount = 0;
            string errorMsg = "";
            try
            {
                /*据说速度更快 
                 * https://www.cnblogs.com/eniac12/p/4398310.html
                 * using (StreamReader sr = File.OpenText(fileName))
                {
                        string s = String.Empty;
                        while ((s = sr.ReadLine()) != null)
                        {
                               //do what you have to here
                        }
                }

                Convert.ToString(a)
                */

                string[] lines = System.IO.File.ReadAllLines(txtPath);
                dynamic jaParams = new JArray();
                int rows = lines.Length;
                processBar.Maximum = rows;
                for (int i = 0; i < rows; i++)
                {
                    processBar.Value = i + 1;
                    Application.DoEvents();

                    string lineTmp = lines[i];

                    string[] arr = lineTmp.Split('\t');
                    //判断是哪种目录类型
                    string code = string.Empty;
                    switch (direcType)
                    {
                        //药品
                        case 1:
                            {
                                jaParams.Add(GetDrugsJsonByTxt(arr));
                                break;
                            }
                        //诊疗
                        case 2:
                            {
                                jaParams.Add(GetMedicalServiceJsonByTxt(arr));
                                break;
                            }
                        //材料
                        case 3:
                            {
                                jaParams.Add(GetMaterialJsonByTxt(arr));
                                break;
                            }
                        //诊断
                        case 4:
                            {
                                jaParams.Add(GetDiagnoseJsonByTxt(arr));
                                break;
                            }
                        //手术
                        case 5:
                            {
                                jaParams.Add(GetOperationJsonByTxt(arr));
                                break;
                            }
                        //慢性病
                        case 6:
                            {
                                jaParams.Add(GetChronicDiseaseJsonByTxt(arr));
                                break;
                            }
                        //DRGs
                        case 7:
                            {
                                jaParams.Add(GetDRGsJsonByTxt(arr));
                                break;
                            }

                        //日间手术
                        case 8:
                            {
                                jaParams.Add(GetDaySurgeryJsonByTxt(arr));
                                break;
                            }
                    }

                    code = "09010035";
                    //每50行提交一次给后台
                    int currentRows = i + 1;
                    if ((currentRows % size == 0) && (i != 0))
                    {
                        JObject joRtn = applyDataToIris(code, jaParams);
                        if (joRtn["errorCode"].ToString() != "0")
                        {
                            errorCount = errorCount + 1;
                            errorMsg = "\r\n" +errorMsg + joRtn["errorMessage"].ToString();
                        }
                        jaParams = new JArray();
                    }

                    if ((currentRows == rows) && (currentRows % size != 0))
                    {
                        JObject joRtn = applyDataToIris(code, jaParams);
                        if (joRtn["errorCode"].ToString() != "0")
                        {
                            errorCount = errorCount + 1;
                            errorMsg = "\r\n" + errorMsg + joRtn["errorMessage"].ToString();
                        }
                        jaParams = new JArray();
                    }
                   
                }
                return JsonHelper.getIrisReturnJson(0 - errorCount, errorMsg, new JObject());
            }
            catch (Exception ex)
            {
                return JsonHelper.getIrisExceptionJson(-1, "importDataToIrisByTxt", ex.Message);
            }
            
        }

        public JObject importDictinary(Sunny.UI.UIProcessBar uiProcessBar,JArray jaList)
        {
            int errorCount = 0;
            string errorMsg = "",outParam = "";
            JObject joReturn = new JObject();
            try
            {
                JArray jaParams = new JArray();
                int rows = jaList.Count ;
                uiProcessBar.Maximum = rows;
                for (int i = 0; i < jaList.Count ; i++)
                {
                    uiProcessBar.Value = i + 1;
                    dynamic joTmp = new JObject();
                    joTmp.ID = "";
                    joTmp.updateUserID = GlobalVariables.operatorNO;
                    joTmp.HospitalDr = GlobalVariables.hospitalDr;
                    joTmp.InterfaceDr = GlobalVariables.interfaceDr_Download;
                    joTmp.Type = jaList[i]["type"].ToString();
                    joTmp.Code = jaList[i]["value"].ToString();
                    joTmp.Name = jaList[i]["label"].ToString();
                    joTmp.Description = jaList[i]["parent_value"].ToString();
                    joTmp.PinyinSearchCode = "";
                    joTmp.ValiFlag = jaList[i]["vali_flag"].ToString();
                    joTmp.UseFlag = 1;
                    jaParams.Add(joTmp);

                    //每50行提交一次给后台
                    int currentRows = i + 1;
                    string code = "09010011";
                    if ((currentRows % 50 == 0) && (i != 0))
                    {
                        JObject joRtn = applyDataToIris(code, jaParams);
                        if (joRtn["errorCode"].ToString() != "0")
                        {
                            errorCount = errorCount + 1;
                            errorMsg = "\r\n" + errorMsg + joRtn["errorMessage"].ToString();
                        }
                        jaParams = new JArray();
                    }

                    if ((currentRows == rows) && (currentRows % 50 != 0))
                    {
                        JObject joRtn = applyDataToIris(code, jaParams);
                        if (joRtn["errorCode"].ToString() != "0")
                        {
                            errorCount = errorCount + 1;
                            errorMsg = "\r\n" + errorMsg + joRtn["errorMessage"].ToString();
                        }
                        jaParams = new JArray();
                    }
                }
                joReturn = JsonHelper.getIrisReturnJson(0 - errorCount, errorMsg, new JObject());
                outParam = joReturn.ToString();
                return joReturn;
            }
            catch (Exception ex)
            {
                joReturn = JsonHelper.getIrisExceptionJson(-1, "importDictinary", ex.Message);
                outParam = joReturn.ToString();
                return joReturn;
            }
            finally
            {
                GlobalVariables.writeLog("importDictinary", jaList.ToString(),outParam);
            }

        }

    }


}
