using Newtonsoft.Json;
using RB_MES_API.Context;
using RB_MES_API.Controllers;
using RB_MES_API.Controllers.Cloud;
using RB_MES_API.Models;
using RB_MES_API.Models.Cloud;
using RB_MES_APICore.Models.Pangu;
using System.Data;
using System.Reflection;

namespace RB_MES_APICore.Controllers.Interface
{
    public class MesApiSTKTransferDirectsService : IMesApiSTKTransferDirectsService
    {
        private readonly IShareController _shareController;
        private readonly IChiledSelect _chiledselect;
        private readonly IKDSqlHelper _kdsqlhelper;
        public MesApiSTKTransferDirectsService(IShareController shareController, IChiledSelect chiledSelect, IKDSqlHelper kdsqlhelper )
        {
            _shareController = shareController;
            _chiledselect = chiledSelect;
            _kdsqlhelper = kdsqlhelper;
        }


        //private async Task<BreakData> SaveBatchSTKTransferDirectsAsync(DataTable dataTable, int fid, int postmid, string data)
        //{
        //    BreakData breakData = new BreakData() { Status = false, DataSet = JsonConvert.DeserializeObject(data) };
        //    string reason = string.Empty;
        //    List<R011>? mes_POInStocks = _shareController.DataConvertClass<R011>(data, ref reason);
        //    if (mes_POInStocks != null)
        //    {
        //        //推送数据
        //        var dsb = await _shareController.GetAPIList<DataSaveBatch>();
        //        DataSaveBatch? dataSave = dsb.Where(s => s.GetForm.FFunctionID == fid && s.FDocTypeID == postmid)
        //            .FirstOrDefault();
        //        breakData.Message = string.Empty;
        //        //校验是否有重复推单
        //        breakData = ExistsDoubleQueid(mes_POInStocks, dataSave.GetForm.FDocType);
        //        if (breakData.Status || !string.IsNullOrEmpty(breakData.Message.ToString()))
        //        {
        //            return breakData;
        //        }
        //        List<STK_TransferDirect> inStocks = CreateBatchSTKTransferDirects(mes_POInStocks, dataSave.FErpBillType, ref reason);

        //        if (inStocks.Count() > 0 && reason == "")
        //        {
        //            breakData = await SaveBatchAsync(dataSave, dataSave.GetForm.FDBName, inStocks);
        //            if (breakData.Status)
        //            {
        //                List<ReciveDataBack> dataBacks = new List<ReciveDataBack>();
        //                if (breakData.DataSet != null)
        //                {
        //                    //提取出创建好的单据编号
        //                    List<Dictionary<string, string>> billlist = (List<Dictionary<string, string>>)breakData.DataSet;
        //                    List<string> billnolist = GetNewBillNoList(dataSave.GetForm.FDocType, mes_POInStocks, billlist, ref dataBacks);
        //                    Thread thread = new Thread(_shareController.SaveReciveData);
        //                    //thread_1.IsBackground = true; //这意味着主程序可能不等它保存了...
        //                    thread.Start(dataBacks);
        //                }
        //                else
        //                {
        //                    dataBacks = await DataBacks(postmid, mes_POInStocks);
        //                    if (dataBacks.Count != 0)
        //                    {
        //                        Thread thread_1 = new Thread(_shareController.SaveReciveData);
        //                        //thread_1.IsBackground = true; //这意味着主程序可能不等它保存了...
        //                        thread_1.Start(dataBacks);
        //                    }
        //                    else
        //                    {
        //                        breakData.Status = false;
        //                        breakData.Message = "不可控因素，请稍后再次提交";
        //                    }
        //                }
        //                breakData.DataSet = dataBacks;
        //            }
        //        }
        //        else
        //        {
        //            breakData.Message = reason;
        //        }
        //    }
        //    else
        //    {
        //        breakData.Message = string.IsNullOrEmpty(reason) ? "输入数据转换出错" : reason;
        //    }

        //    return breakData;
        //}



        ///// <summary>
        ///// 创建调拨单信息，并转换成Cloud的实体类 
        ///// </summary>
        ///// <param name="R011cs">接收到的数据</param>
        ///// <param name="billtype">FBillTypeID的FNumber属性</param>
        ///// <param name="reason">如果错误，则返回消息</param>
        ///// <returns></returns>
        //public List<STK_TransferDirect> CreateBatchSTKTransferDirects(List<R011> R011cs, string billtype, ref string reason)
        //{
        //    reason = "";
        //    List<STK_TransferDirect> list = new List<STK_TransferDirect>();
        //    var R011 = (from a in R011cs
        //                group a by a.TRX_DATE into b
        //                select b).Distinct().ToList();

        //    List<BD_UNIT> units = _shareController.GetAPIList<BD_UNIT>().Result;
        //    foreach (var head in R011)
        //    {
        //        //创建单据头
        //        STK_TransferDirect inStock = new()
        //        {
        //            FBillTypeID = new Dictionary<string, string>() { { "FNUMBER", billtype } },
        //            FDate = head.Key,
        //            FOwnerOutIdHead = new Dictionary<string, string>() { { "FNUMBER", LocalStaticRequest.DefaultOrg } },
        //            F_SBMI_QUEUE_ID = string.Format("R011:{0}", R011cs.FirstOrDefault().QUEUE_ID) //如果不是盘古，建议放在单据体！！！
        //        };


        //        //收集物料清单，一起查询
        //        var mary = from a in R011cs select a.MTRL_ID;
        //        List<BD_Material> marylist = _chiledselect.materialsAsync(mary.ToList()).Result;
        //        if (marylist.Count == 0)
        //        {
        //            reason = "输入的物料编码不存在";
        //            break;
        //        }
        //        //添加单据体，按订单号找到它的明细数据                
        //        List<STK_TransferDirect.BillEntry> entries = (from a in head
        //                                                      join b in R011cs on a.TRX_DATE equals b.TRX_DATE
        //                                                      join c in marylist on b.MTRL_ID equals c.FNumber
        //                                                      join d in units on c.FStoreUnitID equals d.FUNITID
        //                                                      join e in units on c.FBaseUnitId equals e.FUNITID
        //                                                      select new STK_TransferDirect.BillEntry
        //                                                      {
        //                                                          FMaterialId = new Dictionary<string, string>() { { "FNumber", b.MTRL_ID } },
        //                                                          FNoteEntry = b.REMARK,
        //                                                          FLot = new Dictionary<string, string>() { { "FNumber", b.ERP_LOTNO } },
        //                                                          FDestLot = new Dictionary<string, string>() { { "FNumber", b.ERP_LOTNO } },
        //                                                          FQty = decimal.Parse(b.QUANTITY),
        //                                                          FDestStockId = new Dictionary<string, string>() { { "FNumber", b.TOSTORE_ID } },
        //                                                          FUnitID = new Dictionary<string, string>() { { "FNumber", c.FUnitNumber } },
        //                                                          FBaseUnitId = new Dictionary<string, string>() { { "FNumber", c.FBaseUnitNumber } },
        //                                                          FSrcStockId = new Dictionary<string, string>() { { "FNumber", b.STORE_ID } },
        //                                                          FSaleQty = decimal.Parse(b.QUANTITY),
        //                                                          FSaleUnitId = new Dictionary<string, string>() { { "FNumber", c.FUnitNumber } },
        //                                                          FActQty = decimal.Parse(b.QUANTITY),
        //                                                          FSalBaseQty = Math.Round(decimal.Parse(b.QUANTITY) / (d.FConvertNumerator / d.FConvertDenominator), d.FPrecision),
        //                                                          FBaseQty = Math.Round(decimal.Parse(b.QUANTITY) / (d.FConvertNumerator / d.FConvertDenominator), d.FPrecision),
        //                                                          FOwnerOutId = new Dictionary<string, string>() { { "FNumber", LocalStaticRequest.DefaultOrg } },
        //                                                          FAuxPropId = string.IsNullOrEmpty(b.MTRL_VER) ? null : new STK_TransferDirect.BillEntry.AuxpropId() { FAUXPROPID__FF100001 = new Dictionary<string, string>() { { "FNumber", b.MTRL_VER } } }
        //                                                      }
        //                                                 ).Distinct().ToList()
        //                                                 ;
        //        var q = entries.Where(s => s.FQty <= 0).ToList();
        //        if (q.Count > 0)
        //        {
        //            reason = "入库单数量必须大于0";
        //            break;
        //        }
        //        string s = JsonConvert.SerializeObject(entries);
        //        inStock.FBillEntry = entries;
        //        //财务费用，隶属于单据体
        //        list.Add(inStock);

        //    }
        //    return list;
        //}

        //public async Task<BreakData> SaveBatchSTKTransferDirectsAsync(DataTable dataTable, int fid, int postmid, string data)
        //{
        //    BreakData breakData = new BreakData() { Status = false, DataSet = JsonConvert.DeserializeObject(data) };
        //    string reason = string.Empty;
        //    List<R011>? mes_POInStocks = _shareController.DataConvertClass<R011>(data, ref reason);
        //    if (mes_POInStocks != null)
        //    {
        //        //推送数据
        //        var dsb = await _shareController.GetAPIList<DataSaveBatch>();
        //        DataSaveBatch? dataSave = dsb.Where(s => s.GetForm.FFunctionID == fid && s.FDocTypeID == postmid)
        //            .FirstOrDefault();
        //        breakData.Message = string.Empty;
        //        //校验是否有重复推单
        //        breakData = ExistsDoubleQueid(mes_POInStocks, dataSave.GetForm.FDocType);
        //        if (breakData.Status || !string.IsNullOrEmpty(breakData.Message.ToString()))
        //        {
        //            return breakData;
        //        }
        //        List<STK_TransferDirect> inStocks = CreateBatchSTKTransferDirects(mes_POInStocks, dataSave.FErpBillType, ref reason);

        //        if (inStocks.Count() > 0 && reason == "")
        //        {
        //            breakData = await SaveBatchAsync(dataSave, dataSave.GetForm.FDBName, inStocks);
        //            if (breakData.Status)
        //            {
        //                List<ReciveDataBack> dataBacks = new List<ReciveDataBack>();
        //                if (breakData.DataSet != null)
        //                {
        //                    //提取出创建好的单据编号
        //                    List<Dictionary<string, string>> billlist = (List<Dictionary<string, string>>)breakData.DataSet;
        //                    List<string> billnolist = GetNewBillNoList(dataSave.GetForm.FDocType, mes_POInStocks, billlist, ref dataBacks);
        //                    Thread thread = new Thread(_shareController.SaveReciveData);
        //                    //thread_1.IsBackground = true; //这意味着主程序可能不等它保存了...
        //                    thread.Start(dataBacks);
        //                }
        //                else
        //                {
        //                    dataBacks = await DataBacks(postmid, mes_POInStocks);
        //                    if (dataBacks.Count != 0)
        //                    {
        //                        Thread thread_1 = new Thread(_shareController.SaveReciveData);
        //                        //thread_1.IsBackground = true; //这意味着主程序可能不等它保存了...
        //                        thread_1.Start(dataBacks);
        //                    }
        //                    else
        //                    {
        //                        breakData.Status = false;
        //                        breakData.Message = "不可控因素，请稍后再次提交";
        //                    }
        //                }
        //                breakData.DataSet = dataBacks;
        //            }
        //        }
        //        else
        //        {
        //            breakData.Message = reason;
        //        }
        //    }
        //    else
        //    {
        //        breakData.Message = string.IsNullOrEmpty(reason) ? "输入数据转换出错" : reason;
        //    }

        //    return breakData;
        //}

        //private BreakData ExistsDoubleQueid<T>(List<T> inputdata, string DocType) where T : class
        //{
        //    BreakData breakData = new BreakData() { Status = false };
        //    //return breakData;
        //    Type type = typeof(T);
        //    PropertyInfo[] propertyInfos = type.GetProperties();
        //    var propertyInfo = propertyInfos.Where(s => s.Name == "QUEUE_ID");
        //    if (propertyInfo.Any())
        //    {
        //        try
        //        {
        //            List<string> strings = new List<string>();
        //            PropertyInfo infos = propertyInfo.FirstOrDefault()!;
        //            foreach (var obj in inputdata)
        //            {
        //                object v = infos.GetValue(obj)!;
        //                strings.Add(string.Format("'{0}'", v.ToString()));
        //            }
        //            string sql = string.Format("select * from r_ReciveDataBack where FDocType='{0}' and QUEUE_ID in ({1})", DocType, string.Join(',', strings.ToArray()));
        //            //直接SQL查询更快！！！
        //            string messstr = string.Empty;
        //            DataSet? dataSet = _kdsqlhelper.GetDataSet(CommandType.Text, sql, null, ref messstr!, false);
        //            if (dataSet != null || string.IsNullOrEmpty(messstr))
        //            {
        //                if (dataSet.Tables.Count != 0)
        //                {
        //                    DataTable dataTable = dataSet.Tables[0];
        //                    if (dataTable.Rows.Count != 0)
        //                    {
        //                        breakData.Status = true;
        //                        breakData.Message = "不可重复推单";
        //                        var dt = (from a in dataTable.AsEnumerable()
        //                                  select new
        //                                  {
        //                                      QUEUE_ID = a.Field<string>("QUEUE_ID").ToString(),
        //                                      FDocType = a.Field<string>("FDocType")!,
        //                                      FBillNo = a.Field<string>("FBillNo")!,
        //                                      FErpID = a.Field<int>("FErpID"),
        //                                      FSeq = a.Field<int>("FSeq")
        //                                  }).ToList();
        //                        breakData.DataSet = dt;
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                breakData.Message = messstr;
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            breakData.Message = "错误在ExistsDoubleQueid中发生：" + ex.Message;
        //            //throw;
        //        }
        //    }
        //    else
        //    {
        //        breakData.Message = "传入的数据中必须有字段【QUEUE_ID】";
        //    }
        //    return breakData;
        //}

    }
}
