using Microsoft.Data.SqlClient;
using System.Collections;
using System.Data;
using System.Reflection;
using RB_MES_API.Context;
using RB_MES_API.Models;
using Nancy.Json;
using RB_MES_API.Models.Cloud;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RB_MES_APICore.Models.Cloud;
using System.Text;
using Microsoft.VisualBasic;
using RB_MES_APICore.Models;
using Kingdee.CDP.WebApi.SDK;
//using Nancy.Extensions;

namespace RB_MES_API.Controllers
{
    /// <summary>
    /// 公共方法
    /// </summary>
    public class ShareController : IShareController
    {
        private readonly RBContext _context;
        private readonly IKDSqlHelper _kDSqlHelper;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="context"></param>
        /// <param name="kDSqlHelper"></param>
        public ShareController(RBContext context, IKDSqlHelper kDSqlHelper)
        {
            _context = context;
            _kDSqlHelper = kDSqlHelper;
        }
        public async void PostRequestBack(string intface, string doctype, string data)
        {
            string iby = LocalStaticRequest.GetSystemProfile(2, "InterfaceBakType");
            if (iby == "1")
            {
                try
                {
                    MesRequestStatu mes = new MesRequestStatu()
                    {
                        FInterface = intface,
                        FDocType = doctype,
                        FRequestJson = data.ToString(),
                    };
                    var optionsBuilder = new DbContextOptionsBuilder<DbContext>();
                    optionsBuilder.UseSqlServer(_context.Database.GetConnectionString()!);
                    optionsBuilder.UseModel(_context.Model);
                    using (var context = new DbContext(optionsBuilder.Options))
                    {
                        context.Database.EnsureCreated();
                        context.Database.Migrate();
                        context.Set<MesRequestStatu>().AddRange(mes);
                        context.SaveChanges(true);
                        context.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(string.Format("备份ReciveDataBack时发生错误：{0}\n" + "保存的数据为\n{1}" + ex.Message, data.ToString()));
                }
            }
        }
        /// <inheritdoc/>
        public string? GetDropDownText<T>(int saveval)
        {
            Type type = typeof(T);
            string myenum = Enum.GetName(type, saveval);
            return myenum;
        }
        /// <summary>
        /// 字符串转decimal，错误时返回0
        /// </summary>
        /// <param name="sqty">待转换的代表数量</param>
        /// <returns></returns>
        public decimal DecimalPar(string sqty)
        {
            decimal result = 0;
            decimal.TryParse(sqty, out result);
            return result;
        }
        /// <summary>
        /// 将JSON转为实体类
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="data">Json数据包</param>
        /// <param name="reason">错误消息</param>
        /// <returns></returns>
        public List<T>? DataConvertClass<T>(string data, ref string reason) where T : class
        {
            reason = "";
            List<T> list = new List<T>();
            if (string.IsNullOrEmpty(data)) { return list; }
            try
            {
                list = JsonConvert.DeserializeObject<List<T>>(data)!;
            }
            catch (Exception ex)
            {
                reason = string.Format("错误在DataConvertClass中发生：{0}", ex.Message);
                LogHelper.WriteLog(reason);
            }
            return list;
        }
        public T DataToClass<T>(string data, ref string reason) where T : class, new()
        {
            reason = "";
            T newrow = new T();
            if (string.IsNullOrEmpty(data)) { return newrow; }
            JObject keyValuePairs = Newtonsoft.Json.Linq.JObject.Parse(data);
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                string key = property.Name;
                if (keyValuePairs.ContainsKey(key))
                {
                    Type itemtype = property.PropertyType;
                    string val = keyValuePairs.GetValue(key).ToString();
                    property.SetValue(newrow, Convert.ChangeType(val, itemtype));
                }
            }
            return newrow;
        }
        /// <summary>
        /// 取查询接口名称
        /// </summary>
        /// <param name="id">接口ID</param>
        /// <returns></returns>
        public string? InterfaceName(int id)
        {
            string? intname = null;
            try
            {
                var sjid = GetAPIList<SelectJoinID>().Result;
                SelectJoinID? sobj = sjid.Any() ? sjid.Find(s => s.FID == id) : null;
                intname = sobj == null ? null : sobj.FDocType;
            }
            catch (Exception)
            {
                throw;
            }
            return intname;
        }
        /// <summary>
        /// 取推送接口的K3单据名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string? K3BillName(int id)
        {
            string? billname = string.Empty;
            try
            {
                List<ReceiveStockBillType> receives = GetAPIList<ReceiveStockBillType>().Result;
                ReceiveStockBillType? stockBillType = receives.Where(s => s.ErpBillTypeID == id.ToString()).FirstOrDefault();
                billname = stockBillType == null ? null : stockBillType.ErpBillName;
            }
            catch (Exception)
            {
                throw;
            }
            return billname;
        }
        /// <summary>
        /// 转XML
        /// </summary>
        /// <param name="tb"></param>
        /// <param name="tbName"></param>
        /// <returns></returns>
        public string? DatatableToXml(DataTable tb, string? tbName = null)
        {
            tb.TableName = tbName == null ? tb.TableName : tbName;  //可以二次命名
            StringWriter XmlWrit = new StringWriter();
            tb.WriteXml(XmlWrit);
            string StrXml = XmlWrit.ToString();
            XmlWrit.Close();
            return StrXml;
        }
        /// <summary>
        /// RB数据库日志
        /// </summary>
        public void _SqlloggerInvoke(int intfc, string doctypd, string mess, string sour, bool staus = false, string guid = "")
        {
            string mestxt = string.Empty;
            try
            {
                RBLog log = new RBLog()
                {
                    FFunctionID = intfc,
                    FDocType = string.IsNullOrEmpty(doctypd) ? "" : doctypd,
                    FDateTime = DateTime.Now,
                    FStatus = staus,
                    FMess = string.IsNullOrEmpty(mess) ? "" : mess,
                    FSource = string.IsNullOrEmpty(sour) ? "" : sour,
                    FGUID = string.IsNullOrWhiteSpace(guid) ? Guid.NewGuid().ToString("B") : guid
                };
                mestxt = JsonConvert.SerializeObject(log);
                List<RBLog> data = new List<RBLog>() { log };
                string erstr = string.Empty;
                RBSql(data, ref erstr);
                if (!string.IsNullOrEmpty(erstr))
                {
                    LogHelper.WriteLog(string.Format("下列错误未保存到数据库：{0}，\n原因是：{1}", mestxt, erstr));
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(string.Format("下列错误未保存到数据库：{0}，\n原因是：{1}", mestxt, ex.Message));
            }
        }
        /// <summary>
        /// 查询接口使用的SQL脚本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetSelectSql(int id)
        {
            string? errstr = null;
            List<string> stringBuilder = new List<string>();
            SqlParameter[] sp = new SqlParameter[] {
                new SqlParameter("ifcid",id)
            };

            string sql = "select * from r_JoinTb where FSID=@ifcid order by FSID,FCtlID \n";
            sql += "select * from r_SCol where FSID=@ifcid order by FSID,FCtlID";
            DataSet? ds = _kDSqlHelper.GetDataSet(CommandType.Text, sql, sp, ref errstr, false);
            if (errstr != null)
            {
                _SqlloggerInvoke(1, "GetSelectSql", errstr, "");
                return stringBuilder.ToString();
            }
            if (ds != null)
            {
                if (ds.Tables.Count > 0)
                {
                    DataTable table1 = ds.Tables[0];
                    if (table1.Rows.Count > 0)
                    {
                        string BuilderRow = string.Empty;
                        var tbids = (from a in table1.AsEnumerable()
                                     select new
                                     {
                                         TableID = a.Field<int>("FTableID")
                                     }).Distinct().ToList().OrderBy(s => s.TableID);
                        foreach (var tbid in tbids)
                        {
                            string joinstr = "\n";
                            DataRow[] dataRows1 = table1.Select(string.Format("FTableID={0}", tbid.TableID));
                            foreach (DataRow dr in dataRows1)
                            {
                                string? tbname = dr["FTbName"] == DBNull.Value ? "" : dr["FTbName"].ToString();
                                string? asname = dr["FAsName"] == DBNull.Value ? "" : dr["FAsName"].ToString();
                                string? jtype = dr["FJoinType"] == DBNull.Value ? "" : dr["FJoinType"].ToString();
                                string? jmodel = dr["FJoinSymbol"] == DBNull.Value ? "" : dr["FJoinSymbol"].ToString();
                                string? wstr = dr["FCondition"] == DBNull.Value ? "" : dr["FCondition"].ToString();
                                if (jtype != "") joinstr += jtype + " ";
                                if (tbname != "") joinstr += tbname + " ";
                                if (asname != "") joinstr += asname + " ";
                                if (jmodel != "") joinstr += jmodel + " ";
                                if (wstr != "") joinstr += wstr + "\n";
                            }
                            ArrayList sellist = new ArrayList();
                            DataTable table2 = ds.Tables[1];
                            if (table2.Rows.Count > 0)
                            {
                                DataRow[] dataRows2 = table2.Select(string.Format("FTableID={0}", tbid.TableID));
                                foreach (DataRow dr in dataRows2)
                                {
                                    string selstr = string.Empty;
                                    string? asname = dr["FAsTable"] == DBNull.Value ? "" : dr["FAsTable"].ToString();   //与表1中FAsName相同
                                    string? colname = dr["FColName"] == DBNull.Value ? "" : dr["FColName"].ToString();
                                    string? defaultval = dr["FDeaful"] == DBNull.Value ? "" : dr["FDeaful"].ToString();
                                    string? captionname = dr["FAsName"] == DBNull.Value ? "" : dr["FAsName"].ToString();
                                    if (asname != "" && colname != "" && defaultval != "")
                                    {
                                        selstr += string.Format("isnull({0},{1})", asname + "." + colname, defaultval);
                                    }
                                    else
                                    {
                                        if (asname != "") selstr += asname + ".";
                                        if (colname != "") selstr += colname + " ";
                                    }
                                    if (asname == "" && colname == "" && defaultval != "")
                                    {
                                        selstr += defaultval + " ";
                                    }
                                    if (captionname != "")
                                    {
                                        selstr += captionname;
                                    }
                                    if (selstr.Length > 0) sellist.Add(selstr);
                                }
                            }
                            if (sellist.Count > 0) BuilderRow = "select " + string.Join(",", sellist.ToArray());
                            if (joinstr.Trim().Length > 0) BuilderRow += joinstr;
                            stringBuilder.Add(BuilderRow);
                        }
                    }
                }
            }
            return string.Join("\n", stringBuilder.ToArray());
        }
        /// <summary>
        /// 通过输入表单返回实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public List<T> GetClassList<T>(DataTable dataTable) where T : class, new()
        {
            List<T> ts = new List<T>();
            Type type = typeof(T);
            PropertyInfo[] propertyInfos = type.GetProperties();
            foreach (DataRow row in dataTable.Rows)
            {
                T obj = new T();
                foreach (PropertyInfo property in propertyInfos)
                {
                    string name = property.Name;
                    if (dataTable.Columns.Contains(name))
                    {
                        object value = row[name];
                        Type protype = property.PropertyType;
                        property.SetValue(obj, Convert.ChangeType(value, protype));
                    }
                }
                ts.Add(obj);
            }
            return ts;
        }
        private ArrayList GetTypeFiledNames(Type type)
        {
            ArrayList filedNames = new ArrayList() { "FID" };
            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                filedNames.Add(property.Name);
            }
            return filedNames;
        }
        /// <summary>
        /// 64位解密
        /// </summary>
        /// <param name="B64"></param>
        /// <returns></returns>
        public string UnBase64Decode(string B64)
        {
            string NewStr = Encoding.GetEncoding("utf-8").GetString(Convert.FromBase64String(B64));
            return NewStr;
        }
        /// <summary>
        /// 64位加密
        /// </summary>
        /// <param name="B64"></param>
        /// <returns></returns>
        public string Base64Decode(string B64)
        {
            byte[] NewStr = Encoding.Default.GetBytes(B64);
            return Convert.ToBase64String(NewStr);
        }
        /// <summary>
        /// 在目标ints中，通过组合，检验是否包含参数v
        /// </summary>
        /// <param name="ints">要校验的参数值范围</param>
        /// <param name="v">要判断的枚举值</param>
        /// <param name="setv">当前设置的值</param>
        /// <returns></returns>
        public bool SCombination(List<int> ints, int v, int setv)
        {
            if (setv < v)
            {
                return false;
            }
            if (setv == v)
            {
                return true;
            }
            bool isok = false;
            for (int i = 1; i <= ints.Count; i++)
            {
                string result = string.Empty;
                List<string> stringBuilder = new List<string>();
                GetSetGroup(ints, result, 0, i, ref stringBuilder);
                if (stringBuilder.Count > 0)
                {
                    foreach (string str in stringBuilder)
                    {
                        int zhval = 0;
                        string[] zh = str.Split(',');
                        for (int j = 0; j < zh.Length; j++)
                        {
                            if (zh[j].ToString() != "")
                            {
                                int setval = int.Parse(zh[j].ToString());
                                zhval += setval;
                            }
                        }
                        if (v + zhval == setv)
                        {
                            isok = true;
                            break;
                        }
                    }
                }
                if (isok) { break; }
            }
            return isok;
        }
        public List<int> GetSetInts<T>(int exceptobj) where T : struct, Enum
        {
            var fileds = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static);
            List<int> ints = new List<int>();
            foreach (FieldInfo field in fileds)
            {
                string enumname = field.Name;
                int val = (int)Enum.Parse(typeof(T), enumname);
                if (val != 0)
                {
                    int newv = int.Parse(val.ToString());
                    if (newv > 0 && newv != exceptobj)
                    {
                        ints.Add(newv);
                    }
                }
            }
            return ints;
        }
        private void GetSetGroup(List<int> ints, string result, int start, int length, ref List<string> sb)
        {
            if (length == 0)
            {
                sb.Add(result);
            }
            else if (length <= (ints.Count - start))
            {
                GetSetGroup(ints, result, start + 1, length, ref sb);
                result += result == "" ? ints[start].ToString() : "," + ints[start].ToString();
                GetSetGroup(ints, result, start + 1, length - 1, ref sb);
            }
        }
        /// <summary>
        /// 将DataTable对象转为JSON，带字段名
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public string ObjectToJSON(DataTable table)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
            foreach (DataRow row in table.Rows)
            {
                Dictionary<string, object> childRow = new Dictionary<string, object>();
                foreach (DataColumn col in table.Columns)
                {
                    childRow.Add(col.ColumnName, row[col]);
                }
                parentRow.Add(childRow);
            }
            return jsSerializer.Serialize(parentRow);
        }

        /// <summary>
        /// 判断是否批量保存成功
        /// </summary>
        /// <param name="result">需要分析的json</param>
        /// <param name="needfileds">必须返回的字段</param>
        /// <param name="message">如果不成功，代表错误消息；否则代表返回的单据编号</param>
        /// <returns></returns>
        public bool CloudExecuteBatchSaveStatus(string result, string needfileds, ref List<Dictionary<string, string>> message)
        {
            message = new List<Dictionary<string, string>>();
            if (result != "")
            {
                try
                {
                    JObject iResultStr = (JObject)JsonConvert.DeserializeObject(result)!;
                    string E2 = (string)iResultStr["Result"]!["ResponseStatus"]!["IsSuccess"]!;
                    if (E2.ToLower() == "false")
                    {
                        JArray E3 = (JArray)iResultStr["Result"]!["ResponseStatus"]!["Errors"]!;
                        JObject E4 = JObject.Parse(JsonConvert.SerializeObject(E3[0]));
                        message.Add(new Dictionary<string, string> { { "Message", (string)E4["Message"]! } });
                        return false;
                    }
                    else
                    {
                        string[] strings = needfileds.Split(',');
                        JArray E5 = (JArray)iResultStr["Result"]!["NeedReturnData"]!;
                        if (needfileds.Contains('.'))
                        {
                            string entryname = string.Empty;
                            foreach (string s in strings)
                            {
                                string[] Hstr = s.Split('.');
                                if (Hstr.Length == 2)
                                {
                                    entryname = Hstr[0];
                                    break;
                                }
                            }
                            foreach (var HE in E5)
                            {
                                JArray HE1 = (JArray)HE[entryname]!;
                                foreach (JToken HE_N in HE1)
                                {
                                    Dictionary<string, string> HkeyValues = new Dictionary<string, string>();
                                    foreach (string s in strings)
                                    {
                                        string[] chstr = s.Split('.');
                                        if (chstr.Length == 2)
                                        {
                                            string Hkey = chstr[1];
                                            JToken keyValues = HE_N.SelectToken(string.Format("$..{0}", Hkey));
                                            if (keyValues != null)
                                            {
                                                string Hkey2 = JsonConvert.SerializeObject(HE_N[Hkey]);
                                                Type type = HE_N[Hkey].GetType();

                                                if (type.Name.ToLower() == "jobject")
                                                {
                                                    JObject keyValuePairs = (JObject)JsonConvert.DeserializeObject(Hkey2)!;
                                                    foreach (var kv in keyValuePairs)
                                                    {
                                                        string newkv = (string)kv.Value!;
                                                        HkeyValues.Add(Hkey, newkv);
                                                    }
                                                }
                                                else
                                                {
                                                    HkeyValues.Add(Hkey, Hkey2);
                                                }
                                            }
                                            else
                                            {
                                                HkeyValues.Add(Hkey, HE_N[Hkey]!.ToString());
                                            }
                                        }
                                        else
                                        {
                                            HkeyValues.Add(s, HE[s].ToString());
                                        }
                                    }
                                    message.Add(HkeyValues);
                                }
                            }
                        }
                        else
                        {
                            foreach (var HE in E5)
                            {
                                Dictionary<string, string> HkeyValues = new Dictionary<string, string>();
                                Type type = HE.GetType();
                                if (type.IsArray)
                                {
                                    foreach (var obj in HE)
                                    {
                                        foreach (string s in strings)
                                        {
                                            HkeyValues.Add(s, obj[s]!.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    foreach (string s in strings)
                                    {
                                        HkeyValues.Add(s, HE[s]!.ToString());
                                    }
                                }

                                if (HkeyValues.Count > 0) { message.Add(HkeyValues); }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    message.Add(new Dictionary<string, string> { { "Message", ex.Message } });
                    LogHelper.WriteLog(string.Format("Cloud判断是否批量保存成功的CloudExecuteBatchSaveStatus方法发生错误：{0}", ex.Message));
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 判断是否保存成功
        /// </summary>
        /// <param name="result">需要分析的json</param>
        /// <param name="message">如果不成功，代表错误消息；否则代表返回的单据编号</param>
        /// <returns></returns>
        public bool CloudExecuteSaveStatus(string result, ref string message)
        {
            if (result == null) { return false; }
            try
            {
                JObject iResultStr = (JObject)JsonConvert.DeserializeObject(result)!;
                var resultJObject = JObject.Parse(result);
                var queryNode = resultJObject.SelectToken("$..IsSuccess");
                if (queryNode == null)
                {
                    message = "返回异常";
                }
                var isSuccess = queryNode.Value<Boolean>();
                if (!isSuccess)
                {
                    JArray E3 = JArray.Parse(JsonConvert.SerializeObject(resultJObject.SelectToken("$..Errors")));
                    JObject E4 = (JObject)E3[0];
                    message = (string)E4["Message"]!;
                    return false;
                }
                else
                {
                    JArray E5 = (JArray)iResultStr["Result"]!["ResponseStatus"]!["SuccessEntitys"]!;
                    JObject E6 = JObject.Parse(JsonConvert.SerializeObject(E5[0]));
                    message = (string)E6["Number"]!;
                }
            }
            catch (Exception e)
            {
                message = e.Message;
                LogHelper.WriteLog(string.Format("Cloud判断是否保存成功的CloudExecuteSaveStatus方法发生错误：{0}", e.Message));
                return false;
            }

            return true;
        }
        /// <inheritdoc/>

        public List<T> GetNewObj<T>(int fid, string dectablename, string inputjson, ref string reason) where T : class, new()
        {
            reason = string.Empty;
            List<T> list = new List<T>();
            List<SelectClumnConvert> selectClumnConvert = GetAPIList<SelectClumnConvert>().Result;
            var selectconvert = selectClumnConvert.Where(s => s.FFunctionID == fid && s.FDesTableName.Equals(dectablename))
                .Select(s => new { s.FIndexID, s.FSourceName })
                .DistinctBy(s => new { s.FIndexID, s.FSourceName })
                .OrderBy(s => s.FIndexID)
                .ToList();
            if (selectconvert.Count == 0)
            {
                reason = "r_ClumnConvert中不存在" + dectablename; return list;
            }
            //准备序列化数据集
            JArray jArray = (JArray)JsonConvert.DeserializeObject(inputjson);  //特别注意！！！
            if (jArray == null || jArray.Count == 0)
            {
                reason = "没有可用数据";
                return list;
            }
            Type type = typeof(T);
            PropertyInfo[] propertyInfos = type.GetProperties();
            ArrayList arrayList = new ArrayList();
            foreach (JProperty jProperty in jArray.FirstOrDefault())
            {
                arrayList.Add(jProperty.Name);
            }
            foreach (var item in jArray)
            {
                if (item.Count() != selectconvert.Count())
                {
                    reason = "r_ClumnConvert配置的FSourceName数目与数据集字段不符";
                    break;  //直接退出循环
                }
                T newobj = new T();
                for (int i = 0; i < item.Count(); i++)
                {
                    string sname = selectconvert[i].FSourceName;
                    var dlist = from a in selectClumnConvert.Where(s => s.FSourceName == sname)
                                join b in propertyInfos on a.FDesName equals b.Name
                                select new
                                {
                                    a.FDesName
                                };
                    if (dlist.Any())
                    {
                        string dname = arrayList[i].ToString();
                        foreach (var s in dlist)
                        {
                            var property = propertyInfos.Where(v => v.Name == s.FDesName).FirstOrDefault();
                            if (property != null)
                            {

                                object v = item[dname] == null ? "" : item[dname];
                                Type itemtype = property.PropertyType;
                                property.SetValue(newobj, Convert.ChangeType(v, itemtype));
                            }
                        }
                    }
                }
                list.Add(newobj);
            }
            return list;
        }
        public List<T> GetNewObjForChild<T>(string fieldkeys, string inputjson, ref string reason) where T : class, new()
        {
            reason = "";
            List<T> list = new List<T>();
            Type type = typeof(T);
            try
            {

                string[] strings = fieldkeys.Split(',');
                PropertyInfo[] propertyInfos = type.GetProperties();
                JArray jArray = (JArray)JsonConvert.DeserializeObject(inputjson);  //特别注意！！！
                if (jArray == null)
                {
                    reason = "没有可用数据";
                    return list;
                }
                foreach (var item in jArray)
                {
                    JObject keyValuePairs = item as JObject;
                    int itemtotal = keyValuePairs.Count;
                    if (strings.Count() != itemtotal || propertyInfos.Count() != itemtotal)
                    {
                        reason = string.Format("r_ClumnConvert配置的fieldkeys数目与数据集{0}字段不符");
                        break;  //直接退出循环
                    }
                    T newobj = new T();
                    int i = 0;
                    foreach (var item1 in keyValuePairs)
                    {
                        PropertyInfo property = propertyInfos[i];   //不仅数量要吻合，字段也要吻合！！！
                        if (property != null)
                        {
                            object v = item1.Value;
                            Type itemtype = property.PropertyType;
                            if (v != null)
                            {
                                property.SetValue(newobj, Convert.ChangeType(v, itemtype));
                            }
                        }
                        i++;
                    }
                    list.Add(newobj);
                }
            }
            catch (Exception ex)
            {
                reason = string.Format("通过云星空表单查询接口返回的数据解析出错，请检查配置是否与子查询对象【{0}】是否匹配。错误报文如下：\r\n{1}", type.Name, ex.Message);
            }
            return list;
        }
        /// <inheritdoc/>

        public DataTable GetInputDataTable(int fid, string DocType, string data, ref string messtr)
        {
            DataTable dt = new DataTable();
            if (data == null) { return dt; }
            List<SelectClumnConvert> selectClumns = GetAPIList<SelectClumnConvert>().Result;
            var clumnConverts = (from a in selectClumns.Where(s => s.FFunctionID == fid && s.FDesTableName == DocType)
                                 select new { a.FSourceName, a.FIndexID })
                .Distinct()
                .OrderBy(s => s.FIndexID)
                .ToList();
            if (clumnConverts.Count > 0)
            {
                dt.Columns.Clear();
                foreach (var selectClumnConvert in clumnConverts)
                {
                    dt.Columns.Add(selectClumnConvert.FSourceName, typeof(string));
                }
            }
            else
            {
                return dt;
            }
            JArray jArray = (JArray)JsonConvert.DeserializeObject(data)!;  //特别注意！！！
            try
            {
                foreach (var item in jArray)
                {
                    Type type = item.GetType();
                    DataRow row = dt.NewRow();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string pstch = dt.Columns[i].ColumnName;
                        row[i] = item[pstch].ToString();
                    }
                    dt.Rows.Add(row);
                    dt.AcceptChanges();
                }
            }
            catch (Exception ex)
            {
                messtr = ex.Message;
            }
            return dt;
        }
        /// <inheritdoc/>

        public DataTable JsonConvertDatatable(string fieldkeys, string data, ref string messtr)
        {
            messtr = string.Empty;
            DataTable table = new DataTable();
            if (string.IsNullOrEmpty(fieldkeys))
            {
                messtr = "参数fieldkeys不能为空";
                return table;
            }
            if (string.IsNullOrEmpty(data))
            {
                messtr = "参数data不能为空";
                return table;
            }
            string[] fields = fieldkeys.Split(',');
            try
            {
                foreach (string s in fields)
                {
                    if (s == "" || string.IsNullOrEmpty(s)) { continue; }
                    table.Columns.Add(s, typeof(string));
                }
                table.AcceptChanges();
                JArray jArray = (JArray)JsonConvert.DeserializeObject(data)!;  //特别注意！！！
                Type type = jArray.GetType();
                foreach (var item in jArray)
                {
                    if (item.Count() != table.Columns.Count) { continue; }
                    DataRow row = table.NewRow();
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        if (!type.Equals(item.GetType()))
                        {
                            row[i] = item[table.Columns[i].ColumnName];
                        }
                        else
                        {
                            row[i] = item[i];
                        }
                    }
                    table.Rows.Add(row);
                }
                table.AcceptChanges();
            }
            catch (Exception ex)
            {
                messtr = ex.Message;
                LogHelper.WriteLog(string.Format("根据字段顺序，将JSON数据集转为DataTable的JsonConvertDatatable方法发生错误：{0}", ex.Message));
            }
            return table;
        }
        /// <inheritdoc/>

        public List<Dictionary<string, string>> GetClassList(DataTable table)
        {
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            if (table != null && table.Rows.Count > 0)
            {
                foreach (DataRow row in table.Rows)
                {
                    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
                    foreach (DataColumn clumn in table.Columns)
                    {
                        string colname = clumn.ColumnName.ToUpper();
                        keyValuePairs.Add(colname, row[colname].ToString());
                    }
                    list.Add(keyValuePairs);
                }
            }
            return list;
        }
        /// <inheritdoc/>

        public List<Dictionary<string, object>> GetClassList(JArray arrjson)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (JObject item in arrjson)
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                foreach (var obj in item)
                {
                    keyValuePairs.Add(obj.Key, obj.Value.ToString());
                }
                list.Add((keyValuePairs));
            }
            return list;
        }
        /// <summary>
        /// 为确保计量单位不会丢失，如果定时任务更新不成功，导致无缓存，则直接从本地查询缓存起来
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private async Task<List<BD_UNIT>> GetunitLists(string name)
        {
            List<BD_UNIT> unitList = new List<BD_UNIT>();
            try
            {
                string messstr = string.Empty;
                string costomsql = ApiSettingsHelper.GetConfig("CustomRequestRemoteSql");
                if (costomsql.ToUpper() == "Y")
                {
                    BillQuery query = new BillQuery()
                    {
                        FieldKeys = "FUNITID,FNumber,FName,FIsBaseUnit,FPrecision,FDocumentStatus,FForbidStatus,FConvertDenominator,FConvertNumerator,FRoundType",
                        FormId = "BD_UNIT",
                        FilterString = "FDOCUMENTSTATUS='C' AND FFORBIDSTATUS='A'"
                    };
                    string queryJson = JsonConvert.SerializeObject(query);
                    //从云星空查询
                    string result = LocalStaticRequest.cloudApi.BillQuery(queryJson);
                    if (!string.IsNullOrEmpty(result))
                    {
                        unitList = GetNewObjForChild<BD_UNIT>(query.FieldKeys, result, ref messstr);
                        if (unitList.Count > 0)
                        {
                            CacheHelper.Set_AbsluteExpire("BD_UNIT", unitList);
                        }
                    }
                }
                else
                {
                    SqlParameter[] sqls = new SqlParameter[]
                    {
                    new SqlParameter("@a","A"),
                    new SqlParameter("@c","C")
                    };
                    string fileds = "SELECT DISTINCT u1.FUNITID,FNumber,FName,FIsBaseUnit,FPrecision,u1.FDocumentStatus,u1.FForbidStatus,FConvertDenominator,FConvertNumerator,FRoundType\r\n";
                    fileds += "FROM T_BD_UNIT u1 INNER JOIN T_BD_UNIT_L u2 on u2.FUNITID=u1.FUNITID\r\n";
                    fileds += "\tinner join T_BD_UNITCONVERTRATE u3 on u3.FUNITID=U1.FUNITID\r\n";
                    fileds += "WHERE u1.FDOCUMENTSTATUS=@c AND u1.FFORBIDSTATUS=@a";
                    DataSet set = _kDSqlHelper.GetDataSet(CommandType.Text, fileds, sqls, ref messstr, true);
                    if (string.IsNullOrEmpty(messstr))
                    {
                        if (set != null)
                        {
                            if (set.Tables.Count != 0)
                            {
                                DataTable dataTable = set.Tables[0];
                                unitList = GetClassList<BD_UNIT>(dataTable);
                                if (unitList.Count > 0)
                                {
                                    CacheHelper.Set_AbsluteExpire(name, unitList);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(string.Format("ShareController的GetunitLists发生错误：{0}", e.Message));
            }
            return unitList;
        }
        public async Task<List<T>> GetAPIList<T>() where T : class, new()
        {
            Type type = typeof(T);
            string name = type.Name;
            List<T>? list = CacheHelper.GetCache<List<T>>(name);
            if (list == null || list.Count == 0)
            {
                switch (name.ToLower())
                {
                    case "bd_unit":
                        list = await GetunitLists(name) as List<T>;
                        //list = LocalStaticRequest.unites as List<T>;
                        break;
                    case "functionlist":
                        list = await GetfunctionLists(name) as List<T>;
                        break;
                    case "cloudbillquery":
                        list = await Getcloudbillquery(name) as List<T>;
                        break;
                    case "selectjoinid":
                        list = await Getselectjoinid(name) as List<T>;
                        break;
                    case "datasavebatch":
                        list = await Getdatasvaebatch(name) as List<T>;
                        break;
                    case "formidtype":
                        list = await Getformidtype(name) as List<T>;
                        break;
                    case "selectclumnconvert":
                        list = await Getselectclumnconvert(name) as List<T>;
                        break;
                    case "receivestockbilltype":
                        list = await Getreceivestockbilltypet(name) as List<T>;
                        break;
                    case "billtyperules":
                        list = await Getbilltypesource(name) as List<T>;
                        break;
                    case "apihostservice":
                        list = await GetTimedHostedService(name) as List<T>;
                        break;
                    case "customservice":
                        list = await GetCustomService(name) as List<T>;
                        break;
                    default:
                        break;
                }
            }
            list = list ?? new List<T>();
            return list;
        }
        private async Task<List<CustomService>> GetCustomService(string name)
        {
            var list = await _context.r_CustomServices!.AsNoTracking().ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }
        private async Task<List<ApiHostService>> GetTimedHostedService(string name)
        {
            var list = await (from a in _context.r_ApiHostServices!.Where(s => s.FTimer > 0)
                              join b in _context.r_FormIDType!.Include(s => s.functions).Where(s => s.FUsing && s.FIsHostService)
                              on a.FDocType equals b.FDocType
                              select a).AsNoTracking().ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }
        private async Task<List<FunctionList>> GetfunctionLists(string name)
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var list = await _context.r_FunctionList!
                .Where(s => s.FUsing && s.FGoupID == int.Parse(apiid))
                .AsNoTracking().OrderBy(s => s.FID).ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }
        private async Task<List<CloudBillQuery>> Getcloudbillquery(string name)
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var list = await _context.r_CloudBillQuery!
                                .Include(s => s.GetFormID).ThenInclude(s => s.functions).ThenInclude(s => s.apigroup)
                                .Where(s => s.GetFormID.FUsing && s.GetFormID.functions.FUsing)
                                .Where(s => s.GetFormID.functions.apigroup.FID == int.Parse(apiid))
                                .AsNoTracking().ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }
        private async Task<List<SelectJoinID>> Getselectjoinid(string name)
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var list = await _context.r_SelectJoinID!
                                .Include(s => s.functions).ThenInclude(s => s.apigroup)
                                .Where(s => s.functions.FUsing && s.functions.apigroup.FID == int.Parse(apiid))
                                .AsNoTracking().ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }
        private async Task<List<DataSaveBatch>> Getdatasvaebatch(string name)
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var list = await _context.r_DataSaveBatch!
                                .Include(s => s.GetForm).ThenInclude(s => s.functions).ThenInclude(s => s.apigroup)
                                .Where(s => s.GetForm.FUsing)
                                .Where(s => s.GetForm.functions.FUsing && s.GetForm.functions.apigroup.FID == int.Parse(apiid))
                                .AsNoTracking().ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }
        private async Task<List<FormIDType>> Getformidtype(string name)
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var list = await _context.r_FormIDType!
                                .Include(s => s.functions).ThenInclude(s => s.apigroup)
                                .Where(s => s.FUsing)
                                .Where(s => s.functions.apigroup.FID == int.Parse(apiid))
                                .AsNoTracking().ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }
        private async Task<List<SelectClumnConvert>> Getselectclumnconvert(string name)
        {
            var list = await _context.r_ClumnConvert!.AsNoTracking().ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }
        private async Task<List<ReceiveStockBillType>> Getreceivestockbilltypet(string name)
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var list = await _context.r_ReceiveStockBillTypes!
                .Include(s => s.functions).ThenInclude(s => s.apigroup)
                .Where(s => s.functions.FUsing && s.functions.apigroup.FID == int.Parse(apiid))
                .AsNoTracking().ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }
        private async Task<List<BillTypeRules>> Getbilltypesource(string name)
        {
            var list = await _context.r_BillTypeRules!.AsNoTracking().ToListAsync();
            CacheHelper.Set_AbsluteExpire(name, list);
            return list;
        }

        /// <summary>
        /// 将计量单位添加到缓存
        /// </summary>
        public void AddUnitCache()
        {
            //清除缓存
            CacheHelper.Remove("BD_UNIT");
            List<BD_UNIT> units = CacheHelper.GetCache<List<BD_UNIT>>("BD_UNIT");
            if (units == null)
            {
                string sql = "SELECT * FROM kdCloud_BD_UNIT WHERE FDocumentStatus=@C AND FForbidStatus=@A";
                SqlParameter[] sqlParameters = new SqlParameter[]
                {
                new SqlParameter("@C","C"),
                new SqlParameter("@A","A")
                };
                string reason = string.Empty;
                DataSet dataSet = _kDSqlHelper.GetDataSet(CommandType.Text, sql, sqlParameters, ref reason);
                if (dataSet != null)
                {
                    if (dataSet.Tables.Count > 0)
                    {
                        DataTable table = dataSet.Tables[0];
                        units = GetClassList<BD_UNIT>(table);
                        CacheHelper.Set_AbsluteExpire("BD_UNIT", units);
                    }
                }
            }

        }

        public string GetDesFormID(string postdoctype, string sourtype)
        {
            string formid = string.Empty;
            List<BillTypeRules> list = GetAPIList<BillTypeRules>().Result;
            var item = list.Where(s => s.FPostTypeID == postdoctype && s.FSBillTypeNumber == sourtype);
            if (item.Count() > 0)
            {
                formid = item.FirstOrDefault().FDBillTypeNumber;
            }
            return formid;
        }
        /// <inheritdoc/>

        public DataTable JsonToDatatable(string data, ref string messtr)
        {
            DataTable dt = new DataTable();

            try
            {
                JArray jArray = new JArray();
                object OBJ = JsonConvert.DeserializeObject(data)!;
                if (OBJ.GetType().Name.ToLower() == "jobject")
                {
                    JObject jObject = (JObject)JsonConvert.DeserializeObject(data)!;
                    foreach (var obj in jObject)
                    {
                        jArray.Add(obj.Value);
                    }
                }
                else
                {
                    jArray = (JArray)JsonConvert.DeserializeObject(data)!;
                }

                List<Dictionary<string, object>> Dics = GetClassList(jArray);
                foreach (Dictionary<string, object> keyValues in Dics)
                {
                    foreach (var x in keyValues)
                    {
                        if (!string.IsNullOrEmpty(x.Key))
                        {
                            if (!dt.Columns.Contains(x.Key))
                            {
                                dt.Columns.Add(new DataColumn(x.Key, x.Value.GetType()));
                            }
                        }
                    }
                }
                foreach (Dictionary<string, object> keyValues in Dics)
                {
                    DataRow row = dt.NewRow();
                    foreach (var item in keyValues)
                    {
                        string colname = item.Key;
                        object val = item.Value;
                        row[colname] = val;
                    }
                    dt.Rows.Add(row);
                    dt.AcceptChanges();
                }
            }
            catch (Exception ex)
            {
                messtr = ex.Message;
                //throw;
            }
            return dt;
        }

        /// <summary>
        /// JSON转动态对象列表
        /// </summary>
        /// <param name="spacename">命名空间名称</param>
        /// <param name="clssname">模型名称</param>
        /// <param name="data">能转为JArray的JSON</param>
        /// <param name="reason">错误说明</param>
        /// <returns></returns>
        public List<T>? DataConvertClass<T>(string spacename, string clssname, string data, ref string reason) where T : class, new()
        {
            reason = "";
            List<T> list = new List<T>();
            var typelist = Assembly.GetExecutingAssembly().GetTypes()
                .Where(s => s.Namespace == spacename)
                .Where(p => p.Name == clssname);
            if (typelist.Any())
            {
                Type? type = typelist.FirstOrDefault();
                try
                {
                    PropertyInfo[] propertyInfos = type.GetProperties();
                    JArray jArray = (JArray)JsonConvert.DeserializeObject(data)!;
                    foreach (var item in jArray)
                    {
                        T obj = (T)Activator.CreateInstance(type);
                        string chileval = JsonConvert.SerializeObject(item);
                        JObject keyValues = JObject.Parse(chileval);
                        foreach (var key in keyValues)
                        {
                            string name = key.Key;
                            var colobj = propertyInfos.Where(s => s.Name == name);
                            if (colobj.Any())
                            {
                                PropertyInfo propertyInfo = colobj.FirstOrDefault();
                                Type itemtype = propertyInfo.PropertyType;
                                JValue jValue = (JValue)key.Value;
                                propertyInfo.SetValue(obj, Convert.ChangeType(jValue.Value, itemtype));
                            }
                        }
                        list.Add(obj);
                    }
                }
                catch (Exception ex)
                {
                    string typename = spacename + "." + clssname;
                    reason = string.Format("DataConvertClass在{0}中发生错误：{1}\n传入的数据：{2}", typename, ex.Message, data);
                    //throw;
                    LogHelper.WriteLog(reason);
                }
            }
            return list;
        }
        /// <inheritdoc/>

        public bool KDCloudExecuteBatchSaveStatus(string result, string needfileds, ref int errcord, ref List<Dictionary<string, string>> message)
        {
            bool isok = false;
            try
            {
                CloudResult kdresult = JsonConvert.DeserializeObject<CloudResult>(result);
                if (kdresult == null)
                {
                    LogHelper.WriteLog("返回格式无法解析，可能导致重复推送：\n" + result);
                    return true;
                }
                isok = kdresult.Result.ResponseStatus.IsSuccess;
                errcord = kdresult.Result.ResponseStatus.MsgCode;
                if (!isok)
                {
                    if (errcord == 1) { isok = true; }
                    string errstr = JsonConvert.SerializeObject(kdresult.Result.ResponseStatus.Errors);
                    message.Add(new Dictionary<string, string> { { "Message", errstr } });
                }
                else if (!string.IsNullOrEmpty(needfileds))
                {

                    string[] fileds = needfileds.Split(",");
                    if (fileds.Length > 0)
                    {
                        message = new List<Dictionary<string, string>>();
                        string data = JsonConvert.SerializeObject(kdresult.Result.NeedReturnData);
                        try
                        {
                            JArray darray = JArray.Parse(data);
                            foreach (var dr in darray)
                            {
                                JObject jobject = JObject.Parse(dr.ToString());
                                List<string> filedname = new List<string>();
                                foreach (string r1_fileds in fileds)
                                {
                                    if (r1_fileds.Contains("."))
                                    {
                                        string[] r2_fileds = r1_fileds.Split(".");
                                        if (r2_fileds.Length == 2)
                                        {
                                            if (!filedname.Contains(r2_fileds[0]))
                                            {
                                                JArray jArray = (JArray)jobject.GetValue(r2_fileds[0]);
                                                foreach (var item in jArray)
                                                {
                                                    JObject jitem = (JObject)item;
                                                    message.Add(new Dictionary<string, string>() { { r2_fileds[1], jitem.GetValue(r2_fileds[1]).ToString() } });
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        message.Add(new Dictionary<string, string>() { { r1_fileds, jobject.GetValue(r1_fileds).ToString() } });
                                    }
                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            isok = true;
                            LogHelper.WriteLog(string.Format("解析返回字段时格式不正确（{0}），导致发生错误：{1}", data, ex.Message));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                isok = false;
                message.Add(new Dictionary<string, string> { { "Message", ex.Message } });
                LogHelper.WriteLog(ex.Message);
            }

            return isok;
        }
        /// <inheritdoc/>

        public bool CheckRequired<T>(List<T> ts, ref string reason)
        {
            bool isok = true;
            StringBuilder stringBuilder = new StringBuilder();
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            foreach (T item in ts)
            {
                foreach (PropertyInfo property in properties)
                {
                    string name = property.Name;
                }
            }
            return isok;
        }

        public int GetSalePriceID(string reason)
        {
            int id = 0;
            string number = LocalStaticRequest.GetSystemProfile(5, "SalesPricePlanNumber");
            if (string.IsNullOrEmpty(number))
            {
                return id;
            }
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("no",number)
            };
            string sql = "SELECT FInterID FROM ICPrcPly WHERE FNumber=@no";
            object plyid = _kDSqlHelper.ExecuteScalar(CommandType.Text, sql, parameters, ref reason, true);
            if (plyid != null)
            {
                int.TryParse(plyid.ToString(), out id);
            }
            return id;
        }
        /// <inheritdoc/>

        public void ASCCarry(ref string s, int len, string coverstr)
        {
            if (string.IsNullOrEmpty(s))
            {
                s = "1".PadLeft(len, char.Parse(coverstr));
            }
            string laststr = s.Substring(s.Length - 1);
            int asc = Strings.Asc(laststr);
            NewASC(ref s, len, 1, asc);
        }
        private void NewASC(ref string s, int len, int r_star, int asc, int step = 1)
        {
            try
            {
                if (asc > 47 && asc < 58)
                {
                    if (asc == 57)
                    {
                        s = GetReplaceStr(s, r_star, Strings.Chr(48).ToString());
                        r_star += 1;
                        RecursionNewASC(ref s, len, r_star, asc, step);
                        if (string.IsNullOrEmpty(s)) { return; }
                    }
                    else
                    {
                        asc += step;
                        s = GetReplaceStr(s, r_star, Strings.Chr(asc).ToString());
                    }
                }
                else if (asc > 64 && asc < 91)
                {
                    if (asc == 90)
                    {
                        s = GetReplaceStr(s, r_star, Strings.Chr(65).ToString());
                        r_star += 1;
                        RecursionNewASC(ref s, len, r_star, asc, step);
                        if (string.IsNullOrEmpty(s)) { return; }
                    }
                    else
                    {
                        asc += step;
                        s = GetReplaceStr(s, r_star, Strings.Chr(asc).ToString());
                    }
                }
                else if (asc > 96 && asc < 123)
                {
                    if (asc == 122)
                    {
                        s = GetReplaceStr(s, r_star, Strings.Chr(97).ToString());
                        r_star += 1;
                        RecursionNewASC(ref s, len, r_star, asc, step);
                        if (!string.IsNullOrEmpty(s)) { return; }
                    }
                    else
                    {
                        asc += step;
                        s = GetReplaceStr(s, r_star, Strings.Chr(asc).ToString());
                    }
                }
            }
            catch (Exception)
            {
                s = "";
                throw;
            }
        }

        private void RecursionNewASC(ref string s, int len, int r_star, int asc, int step = 1)
        {
            if (r_star > len)
            {
                s = "";
                return;
            }
            else
            {
                string nextstr = s.Substring(len - r_star, 1);
                asc = Strings.Asc(nextstr);
                NewASC(ref s, len, r_star, asc, step);
            }
        }
        /// <summary>
        /// 替换指定位置的字符串
        /// </summary>
        /// <param name="str">地替换的字符串</param>
        /// <param name="position">从右开始的位置</param>
        /// <param name="pstr">新的字符串</param>
        /// <returns></returns>
        private string GetReplaceStr(string str, int position, string pstr)
        {
            int len = str.Length;
            int leftlen = len - position;
            string leftstr = str.Substring(0, leftlen);
            string rightstr = str.Substring(leftlen + 1, position - 1);
            string newstr = leftstr + pstr + rightstr;
            return newstr;
        }

        /// <inheritdoc/>
        [Obsolete]
        public void SaveReciveData(object dataBacks)
        {
            try
            {
                List<ReciveDataBack> data = (List<ReciveDataBack>)dataBacks;
                if (data.Count > 0)
                {
                    string erstr = string.Empty;
                    RBSql(data, ref erstr);
                }
            }
            catch (Exception ex)
            {
                string bak = JsonConvert.SerializeObject(dataBacks);
                LogHelper.WriteLog(string.Format("备份ReciveDataBack时发生错误：{0}\n" + ex.Message, bak));
            }
        }
        [Obsolete]
        public void _SqllogInvoke(RBLog log)
        {
            try
            {
                if (log != null)
                {
                    string erstr = string.Empty;
                    List<RBLog> data = new List<RBLog>() { log };
                    RBSql(data, ref erstr);
                }
            }
            catch (Exception ex)
            {
                string bak = JsonConvert.SerializeObject(log);
                LogHelper.WriteLog(string.Format("备份ReciveDataBack时发生错误：{0}\n" + ex.Message, bak));
            }
        }
        private void RBSql<T>(List<T> obj, ref string errstr) where T : class, new()
        {
            Type type = typeof(T);
            string tbname = _context.Model.FindEntityType(type).GetTableName();
            if (obj == null || obj.Count == 0)
            {
                errstr = "无法分析空的对象";
                return;
            }
            PropertyInfo[] fileInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            try
            {
                for (int i = 0; i < obj.Count; i++)
                {
                    T item = obj[i];
                    List<string> colnames = new List<string>();
                    List<string> values = new List<string>();
                    List<SqlParameter> param = new List<SqlParameter>();
                    foreach (PropertyInfo property in fileInfo)
                    {
                        if (property.CustomAttributes.Any())
                        {
                            bool iskey = false;
                            bool isneed = false;
                            string displayname = string.Empty;
                            foreach (var info in property.CustomAttributes)
                            {
                                if (info.AttributeType.Name == "KeyAttribute")
                                {
                                    iskey = true;
                                    break;
                                }
                                if (info.AttributeType.Name == "DisplayNameAttribute")
                                    displayname = info.ConstructorArguments.FirstOrDefault().Value.ToString();
                                if (info.AttributeType.Name == "RequiredAttribute")
                                    isneed = true;
                            }
                            if (!iskey)
                            {
                                string colname = property.Name;
                                object value = property.GetValue(item);
                                if (isneed && string.IsNullOrWhiteSpace(value.ToString()))
                                {
                                    errstr += string.Format("字段【{0}】为必填！", string.IsNullOrEmpty(displayname) ? colname : displayname);
                                }
                                else if (!string.IsNullOrWhiteSpace(value.ToString()))
                                {
                                    colnames.Add(colname);
                                    string parname = "@" + colname + string.Format("_{0}", i);
                                    param.Add(new SqlParameter(parname, value));
                                    values.Add(parname);
                                }
                            }
                        }
                    }
                    string _sql = string.Format("insert into {0}({1}) values({2})", tbname, string.Join(",", colnames.ToArray()), string.Join(",", values.ToArray()));
                    _kDSqlHelper.ExecuteNonQueryAsync(_sql, CommandType.Text, param.ToArray(), false);
                }
            }
            catch (Exception ex)
            {
                errstr = ex.Message;
                throw new Exception(errstr);
            }
        }

    }
}
