using FactorySystemCommon;
using FactorySystemModel.SqlSugarModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using FactorySystemModel.EnumModel;
using FactorySystemModel.RequestModel;
using FactorySystemModel.ResponseModel;

namespace FactorySystemBll
{
    public class FormulaBll
    {
        /// <summary>
        /// 获取配置信息
        /// </summary>
        public object GetBasicList(int type)
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<TBasicCode>().Where(s => s.FType == type && s.FState == 1).ToList();
        }

        /// <summary>
        /// 获取配置信息
        /// </summary>
        public static List<TFS_Formula> GetFormulaList()
        {
            int isDelete = (int)Constant.DeleteCode.已删除;
            return AppSettingsHelper.GetSqlSugar().Queryable<TFS_Formula>().Where(s => s.FDeleted != isDelete).Distinct().ToList();
        }

        public object GetFormulaByFTestCode(string code) 
        {
            int isDelete = (int)Constant.DeleteCode.已删除;
            return AppSettingsHelper.GetSqlSugar().Queryable<TFS_Formula>().Where(s => s.FDeleted != isDelete&&s.FTestCode==code).First();
        }


        public List<FormulaRow> GetList(FormulaQuery tr, out int totalNumber)
        {
            totalNumber = 0;
            var db = AppSettingsHelper.GetSqlSugar();
            return db.Queryable<TFS_Formula>().Where(s => s.FTestCode != "")
                .WhereIF(tr.FName != null, s => s.FName.Contains(tr.FName) || s.FPlmCode.Contains(tr.FPlmCode) || s.FTestCode.Contains(tr.FTestCode) || s.FVersionCode.Contains(tr.FVersionCode))
                .Select<FormulaRow>("*").ToPageList(tr.FPageIndex, tr.FPageSize, ref totalNumber);
        }

        /// <summary>
        /// 配方数据比对
        /// </summary>
        public int DockingRecipeData(List<TFS_Formula> formulaList, int userId)
        {
            formulaList = formulaList.Where(s => !string.IsNullOrEmpty(s.FPlmCode)).ToList();
            if (formulaList.Count == 0) return 1;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_Formula> updateList = new List<TFS_Formula>();
            List<TFS_Formula> insertList = new List<TFS_Formula>();
            List<TFS_Factory> factorys = db.Queryable<TFS_Factory>().OrderBy(s => s.FDeleted).ToList();
            List<TFS_Material> materials = db.Queryable<TFS_Material>().OrderBy(s => s.FDeleted).ToList();

            List<TBasicCode> typeList = db.Queryable<TBasicCode>().Where(s => s.FType == (int)Constant.BasicCode.配方种类).ToList();
            //根据PLM码分组
            foreach (var item in formulaList.GroupBy(s => s.FPlmCode))
            {
                List<TFS_Formula> formulas = db.Queryable<TFS_Formula>().Where(s => s.FPlmCode == item.Key
                && s.FDeleted != (int)Constant.DeleteCode.已删除).ToList();
                List<TFS_Formula> temps = item.Where(s1 => !string.IsNullOrEmpty(s1.FVersionCode.Trim())).ToList();
                if (temps.Count > 0)//版本号非空
                {
                    //根据版本号分组
                    foreach (var item2 in item.GroupBy(ss => ss.FVersionCode.Trim()))
                    {
                        TFS_Formula formula = formulas.Find(d => d.FVersionCode == item2.Key.Trim());
                        if (formula == null) formula = formulas.Find(d => d.FVersionCode == "");
                        TFS_Formula temp = item2.FirstOrDefault();
                        if (formula != null)
                        {
                            formula.FName = temp.FName.Trim();
                            formula.FDesc = (string.IsNullOrEmpty(temp.FDesc) ? formula.FDesc : temp.FDesc).Trim();
                            formula.FType = (string.IsNullOrEmpty(temp.FType) ? formula.FType : temp.FType).Trim();
                            formula.FTestCode = (string.IsNullOrEmpty(temp.FTestCode) ? formula.FTestCode : temp.FTestCode).Trim();
                            formula.FProductCode = (string.IsNullOrEmpty(temp.FProductCode) ? formula.FProductCode : temp.FProductCode).Trim();
                            formula.FFactoryCode = (string.IsNullOrEmpty(temp.FFactoryCode) ? formula.FFactoryCode : temp.FFactoryCode).Trim();
                            formula.FVersionCode = (string.IsNullOrEmpty(temp.FVersionCode) ? formula.FVersionCode : temp.FVersionCode).Trim();
                            if (!string.IsNullOrEmpty(formula.FFactoryCode))
                            {
                                TFS_Factory factory = factorys.Find(s => s.FCode == formula.FFactoryCode);
                                if (factory == null) factory = factorys.Find(s => s.FName == formula.FFactoryCode);
                                if (factory == null) formula.FFactoryID = -1;
                                else formula.FFactoryID = factory.FID;
                            }
                            formula.FEditDate = DateTime.Now;
                            formula.FEditUser = userId;

                            /**
                             * 20230401 新增
                             * 表中增加：
                             * 转规格人员 FConversionPersonnel
                             * 开发日期 FDevDate
                             * BOM版本号 FBomVersionCode
                             * **/
                            formula.FConversionPersonnel = (string.IsNullOrEmpty(temp.FConversionPersonnel) ? formula.FConversionPersonnel : temp.FConversionPersonnel).Trim();
                            formula.FDevDate = DateTime.Now;
                            formula.FBomVersionCode = (string.IsNullOrEmpty(temp.FBomVersionCode) ? formula.FBomVersionCode : temp.FBomVersionCode).Trim();

                            // 20230401 根据试验号获取生产号
                            if (materials != null && materials.Count > 0)
                            {
                                TFS_Material material = materials.Find(m => m.FTestCode == formula.FTestCode);

                                if (material != null && !string.IsNullOrEmpty(material.FCode))
                                {
                                    formula.FProductCode = material.FCode;
                                }
                            }

                            // 按照协同物料清单下来的逻辑修改配方物料类型
                            string ftype = formula.FType.ToLower();
                            if(ftype == "f") 
                            {
                                formula.FType = "10";
                            }
                            else if (ftype == "a")
                            {
                                formula.FType = "20";
                            }
                            else if (ftype == "b" || ftype == "bb" || ftype == "i" || ftype == "iz")
                            {
                                formula.FType = "30";
                            }
                            else
                            {
                                formula.FType = "40";
                            }

                            TBasicCode bType = typeList.Find(s => s.FName == formula.FType || s.FValue == formula.FType);
                            if (bType != null) formula.FType = bType.FValue;
                            updateList.Add(formula);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(temp.FFactoryCode))
                            {
                                TFS_Factory factory = factorys.Find(s => s.FCode == temp.FFactoryCode);
                                if (factory == null) factory = factorys.Find(s => s.FName == temp.FFactoryCode);
                                if (factory == null) temp.FFactoryID = -1;
                                else temp.FFactoryID = factory.FID;
                            }
                            temp.FID = -1;
                            temp.FAddDate = temp.FEditDate = DateTime.Now;
                            temp.FEditUser = userId;

                            /**
                             * 20230401 新增
                             * 表中增加：
                             * 转规格人员 FConversionPersonnel
                             * 开发日期 FDevDate
                             * BOM版本号 FBomVersionCode
                             * **/
                            temp.FDevDate = DateTime.Now;

                            // 20230401 根据试验号获取生产号
                            if (materials != null && materials.Count > 0)
                            {
                                TFS_Material material = materials.Find(m => m.FTestCode == temp.FTestCode);

                                if (material != null && !string.IsNullOrEmpty(material.FCode))
                                {
                                    temp.FProductCode = material.FCode;
                                }
                            }

                            TBasicCode bType = typeList.Find(s => s.FName == temp.FType || s.FValue == temp.FType);
                            if (bType != null) temp.FType = bType.FValue;
                            insertList.Add(temp);
                        }
                    }
                }
                else if (formulas == null || formulas.Count == 0)
                {
                    TFS_Formula temp = item.FirstOrDefault();
                    temp.FAddDate = temp.FEditDate = DateTime.Now;
                    temp.FEditUser = userId;


                    // 按照协同物料清单下来的逻辑修改配方物料类型
                    string ftype = temp.FType.ToLower();
                    if (ftype == "f")
                    {
                        temp.FType = "10";
                    }
                    else if (ftype == "a")
                    {
                        temp.FType = "20";
                    }
                    else if (ftype == "b" || ftype == "bb" || ftype == "i" || ftype == "iz")
                    {
                        temp.FType = "30";
                    }
                    else
                    {
                        temp.FType = "40";
                    }

                    /**
                     * 20230401 新增
                     * 表中增加：
                     * 转规格人员 FConversionPersonnel
                     * 开发日期 FDevDate
                     * BOM版本号 FBomVersionCode
                     * **/
                    temp.FDevDate = DateTime.Now;

                    // 20230401 根据试验号获取生产号
                    if (materials != null && materials.Count > 0)
                    {
                        TFS_Material material = materials.Find(m => m.FTestCode == temp.FTestCode);

                        if (material != null && !string.IsNullOrEmpty(material.FCode))
                        {
                            temp.FProductCode = material.FCode;
                        }
                    }

                    insertList.Add(temp);
                }
            }
            try
            {
                db.BeginTran();
                if (updateList.Count > 0)
                {
                    for (int i = 0; i < updateList.Count; i++)
                    {
                        db.Updateable(updateList[i]).IgnoreColumns(true).ExecuteCommand();
                    }
                }
                if (insertList.Count > 0)
                {
                    for (int i = 0; i < insertList.Count; i++)
                    {
                        db.Insertable(insertList[i]).IgnoreColumns(true).ExecuteCommand();
                    }
                }
                db.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                db.RollbackTran();
            }
            return 0;
        }

        /// <summary>
        /// （对接）SAP配方同步
        /// </summary>
        public int DockSapFormula(List<TFS_Formula> formulaList)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            int okCount = 0;
            db.BeginTran();
            try
            {
                foreach (TFS_Formula item in formulaList)
                {
                    TFS_Formula temp = db.Queryable<TFS_Formula>().Where(s => s.FName == item.FName && s.FFactoryID == item.FFactoryID
                    && s.FTestCode == item.FTestCode).First();
                    if (string.IsNullOrEmpty(item.FType)) item.FType = "";
                    if (temp == null) okCount += db.Insertable(item).IgnoreColumns(true).ExecuteCommand();
                }
                db.CommitTran();
            }
            catch (Exception ex)
            {
                ExceptionHelper.AddSystemJournal(null, formulaList, ex.Message, -1, "DockSapFormulaDb");
                db.RollbackTran();
            }
            return okCount;
        }
    }
}
