using FactorySystemCommon;
using FactorySystemModel.SqlSugarModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FactorySystemModel.EnumModel;
using System.Data;

namespace FactorySystemBll
{
    public class MaterialBll
    {
        private readonly string[] NoSetField = "FID,FAddDate,FEditDate".Split(',');

        /// <summary>
        /// 物料主数据比对
        /// </summary>
        public int DockingRecipeData(List<TFS_Material> mainList, List<PropertyInfo> mainProp, int userId)
        {
            int result = 0;
            if (mainList.Count == 0) return result;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_Factory> factorys = db.Queryable<TFS_Factory>().OrderBy(s => s.FDeleted).ToList();
            //已存在
            List<string> codes = mainList.GroupBy(g => g.FCode).Select(ss => ss.Key).ToList();
            List<TFS_Material> mainsList = db.Queryable<TFS_Material>().Where(s => s.FDeleted != (int)Constant.DeleteCode.已删除 && codes.Contains(s.FCode)).ToList();
            //增改
            List<TFS_Material> updateList = new List<TFS_Material>();
            List<TFS_Material> insertList = new List<TFS_Material>();
            //根据物料号分组
            foreach (var item in mainList.GroupBy(s => s.FCode))
            {
                TFS_Material temp = mainsList.Find(d => d.FCode == item.Key);
                if (temp == null)
                {
                    temp = item.First();
                    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.FAddDate = temp.FEditDate = DateTime.Now;
                    temp.FEditUser = userId;
                    insertList.Add(temp);
                }
                else
                {
                    temp.FEditDate = DateTime.Now;
                    temp.FEditUser = userId;
                    string value;
                    foreach (PropertyInfo mProp in mainProp)
                    {
                        if (!NoSetField.Contains(mProp.Name) && mProp.PropertyType.Name != "Boolean")
                        {
                            object mPV = mProp.GetValue(item.First());
                            if (mPV != null && !string.IsNullOrEmpty(value = mPV.ToString()) && value != "null" && value != "0")
                            {
                                if (mProp.PropertyType.Name == "Int32")
                                {
                                    if (int.TryParse(value, out int val)) mProp.SetValue(temp, val);
                                }
                                else
                                {
                                    mProp.SetValue(temp, value);
                                }
                            }
                        }
                    }
                    updateList.Add(temp);
                }
            }
            try
            {
                db.BeginTran();
                if (updateList.Count > 0)
                {
                    foreach (var item in updateList)
                    {
                        result += db.Updateable(item).IgnoreColumns(true).ExecuteCommand();
                    }
                }
                if (insertList.Count > 0)
                {
                    foreach (var item in insertList)
                    {
                        result += db.Insertable(item).IgnoreColumns(true).ExecuteCommand();
                    }
                }
                db.CommitTran();
            }
            catch (Exception)
            {
                db.RollbackTran();
            }
            return result;
        }

        public List<TFS_Material> GetMaterial(string fMaterialFormulaIDs) 
        {
            return AppSettingsHelper.GetSqlSugar()
                .Queryable<TFS_Material, TFS_ViewMaterial>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FMaterialID))
                .Where((a, b) => fMaterialFormulaIDs.Contains(a.FID.ToString())).Select<TFS_Material>((a, b) => a).ToList();
        }
        /// <summary>
        /// 更具试验号获取物料
        /// </summary>
        /// <param name="fTestCode"></param>
        /// <returns></returns>
        public List<TFS_Material> GetMaterialListByFTestCode(string fTestCode) 
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<TFS_Material>().Where(m => m.FTestCode == fTestCode).ToList();
        }


        public TFS_Material GetMaterialById(int id) 
        {
            return BaseBll.GetTempModel<TFS_Material>("FID=" + id);
        }


        /// <summary>
        /// 物料子数据比对
        /// </summary>
        public int DockingRecipeData(List<TFS_ViewMaterial> childList, List<PropertyInfo> childProp, int userId)
        {
            int result = 0;
            if (childList.Count == 0) return result;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            //主数据
            List<string> codes = childList.GroupBy(g => g.FCode).Select(ss => ss.Key).ToList();
            List<TFS_Material> mainList = db.Queryable<TFS_Material>().Where(s => s.FDeleted != (int)Constant.DeleteCode.已删除 && codes.Contains(s.FCode)).ToList();
            if (mainList == null || mainList.Count == 0) return result;
            //已存在子数据
            codes = mainList.Select(ss => ss.FID.ToString()).ToList();
            List<TFS_ViewMaterial> childsList = db.Queryable<TFS_ViewMaterial>().Where(s => s.FDeleted != (int)Constant.DeleteCode.已删除
            && codes.Contains(s.FMaterialID.ToString())).ToList();
            List<TFS_Factory> factorys = db.Queryable<TFS_Factory>().OrderBy(s => s.FDeleted).ToList();
            List<TFS_ViewMaterial> updateList = new List<TFS_ViewMaterial>();
            List<TFS_ViewMaterial> insertList = new List<TFS_ViewMaterial>();
            foreach (TFS_Material main in mainList)
            {
                List<TFS_ViewMaterial> childs = childList.Where(s => s.FCode.Equals(main.FCode)).ToList();
                if (childs != null && childs.Count() > 0)
                {
                    foreach (TFS_ViewMaterial child in childs)
                    {
                        TFS_ViewMaterial temp = childsList.Find(s => s.FMaterialID == main.FID && s.FFactoryCode.Equals(child.FFactoryCode));
                        if (temp == null)
                        {
                            temp = child;
                            temp.FAddDate = temp.FEditDate = DateTime.Now;
                            temp.FEditUser = userId;
                            insertList.Add(temp);
                        }
                        else
                        {
                            temp.FEditDate = DateTime.Now;
                            temp.FEditUser = userId;
                            foreach (PropertyInfo mProp in childProp)
                            {
                                if (!NoSetField.Contains(mProp.Name))
                                {
                                    string value = mProp.GetValue(child).ToString();
                                    if (!string.IsNullOrEmpty(value) && value != "null" && value != "0")
                                    {
                                        if (mProp.PropertyType.Name == "Int32")
                                        {
                                            if (int.TryParse(value, out int val)) mProp.SetValue(temp, val);
                                        }
                                        else
                                        {
                                            mProp.SetValue(temp, value);
                                        }
                                    }
                                }
                            }
                            updateList.Add(temp);
                        }
                        temp.FMaterialID = main.FID;
                        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;
                        }
                    }
                }
            }

            try
            {
                db.BeginTran();
                if (updateList.Count > 0)
                {
                    foreach (var item in updateList)
                    {
                        result += db.Updateable(item).IgnoreColumns(true).ExecuteCommand();
                    }
                }
                if (insertList.Count > 0)
                {
                    foreach (var item in insertList)
                    {
                        result += db.Insertable(item).IgnoreColumns(true).ExecuteCommand();
                    }
                }
                db.CommitTran();
            }
            catch (Exception)
            {
                db.RollbackTran();
            }
            return result;
        }

        /// <summary>
        /// 物料查询接口--弃用
        /// </summary>
        public object SearchMaterialData(Dictionary<string, object> inParam)
        {
            List<object> resultList = new List<object>();
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_Material> materialList = db.Queryable<TFS_Material>()
                     .WhereIF(inParam.ContainsKey("FVersionCode"), a => a.FVersionCode.Equals(inParam["FVersionCode"].ToString()))
                     .WhereIF(inParam.ContainsKey("FCode"), a => a.FCode.Equals(inParam["FCode"].ToString()))
                     .WhereIF(inParam.ContainsKey("FPlmCode"), a => a.FCode.Equals(inParam["FPlmCode"].ToString()))
                     .WhereIF(inParam.ContainsKey("FName"), a => a.FName.Equals(inParam["FName"].ToString()))
                     .WhereIF(inParam.ContainsKey("FTestCode"), a => a.FTestCode.Equals(inParam["FTestCode"].ToString()))
                     .ToList();
            if (materialList != null && materialList.Count > 0)
            {
                List<TFS_ViewMaterial> viewList = new List<TFS_ViewMaterial>();
                if (inParam.ContainsKey("FFactoryCode"))
                {
                    List<int> mIds = materialList.Select(s => s.FID).ToList();
                    viewList = db.Queryable<TFS_ViewMaterial>().Where(s => mIds.Contains(s.FMaterialID) &&
                    s.FFactoryCode.Equals(inParam["FFactoryCode"].ToString())).ToList();
                }
                foreach (TFS_Material material in materialList)
                {
                    TFS_ViewMaterial view = viewList.Find(s => s.FMaterialID == material.FID);
                    if (view != null)
                    {
                        resultList.Add(new
                        {
                            FName = view.FBaseMaterialDesc,
                            FType = material.FType,
                            FCode = view.FBaseMaterialCode,
                            FTestCode = view.FBaseTestCode,
                            FVersionCode = material.FVersionCode,
                            FPlmCode = material.FPlmCode
                        });
                    }
                    else
                    {
                        resultList.Add(new
                        {
                            material.FName,
                            material.FType,
                            material.FCode,
                            material.FTestCode,
                            material.FVersionCode,
                            material.FPlmCode
                        });
                    }
                }
            }
            return resultList;
        }

        /// <summary>
        /// 物料查询接口
        /// </summary>
        public dynamic SearchMaterialData2(Dictionary<string, object> inParam)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string selectVal = "distinct isnull(b.FBaseMaterialDesc,a.FName)FName,isnull(b.FMRP1ProductType,a.FType)FType," +
                "isnull(a.FCode,'')FCode,isnull(a.FPlmCode,'')SP,isnull(b.FBaseTestCode,a.FTestCode)" +
                "SP_VALUE,isnull(a.FVersionCode,'')SP_VERSION";
            string code1 = "", code2 = "", code3 = "";
            dynamic result = new List<int>();
            switch (inParam["FType"].ToString())
            {
                case "1":
                    if (inParam.TryGetValue("FCode", out object obj1)) code1 = obj1.ToString();

                    if (string.IsNullOrWhiteSpace(code1))
                    {
                        return result;
                    }

                    result = db.Queryable<TFS_Material, TFS_ViewMaterial>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FMaterialID))
                        .Where((a, b) => b.FBaseMaterialCode.Equals(code1)).Select<dynamic>(selectVal).ToList();
                    break;
                case "2":
                    if (inParam.TryGetValue("SP", out object obj2)) code1 = obj2.ToString();
                    if (inParam.TryGetValue("SP_VERSION", out object obj3)) code2 = obj3.ToString();

                    if (string.IsNullOrWhiteSpace(code1) || string.IsNullOrWhiteSpace(code2))
                    {
                        return result;
                    }

                    result = db.Queryable<TFS_Material, TFS_ViewMaterial>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FMaterialID))
                        .Where((a, b) => a.FPlmCode.Equals(code1) && a.FVersionCode.Equals(code2)).Select<dynamic>(selectVal).ToList();
                    break;
                case "3":
                    if (inParam.TryGetValue("SP", out object obj4)) code1 = obj4.ToString();
                    if (inParam.TryGetValue("FFactoryCode", out object obj5)) code2 = obj5.ToString();

                    if (string.IsNullOrWhiteSpace(code1) || string.IsNullOrWhiteSpace(code2)) 
                    {
                        return result;
                    }

                    result = db.Queryable<TFS_Material, TFS_ViewMaterial>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FMaterialID))
                        .Where((a, b) => a.FPlmCode.Equals(code1) && b.FFactoryCode.Equals(code2)).Select<dynamic>(selectVal).ToList();
                    break;
                case "4":
                    if (inParam.TryGetValue("SP", out object obj6)) code1 = obj6.ToString();
                    if (inParam.TryGetValue("SP_VERSION", out object obj7)) code2 = obj7.ToString();
                    if (inParam.TryGetValue("SP_VERSION", out object obj8)) code3 = obj8.ToString();

                    if (string.IsNullOrWhiteSpace(code1) || string.IsNullOrWhiteSpace(code2)||string.IsNullOrWhiteSpace(code3))
                    {
                        return result;
                    }
                    result = db.Queryable<TFS_Material, TFS_ViewMaterial>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FMaterialID))
                        .Where((a, b) => a.FPlmCode.Equals(code1) && a.FVersionCode.Equals(code2) && b.FFactoryCode.Equals(code3)).Select<dynamic>(selectVal).ToList();
                    break;
                // 20230802 增加试验号 + 工厂查询
                case "5":
                    if (inParam.TryGetValue("SP_VALUE", out object objSpValue5)) code1 = objSpValue5.ToString();
                    if (inParam.TryGetValue("FFactoryCode", out object objFactoryCode5)) code2 = objFactoryCode5.ToString();

                    if (string.IsNullOrWhiteSpace(code1) || string.IsNullOrWhiteSpace(code2))
                    {
                        return result;
                    }
                    result = db.Queryable<TFS_Material, TFS_ViewMaterial>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FMaterialID))
                        .Where((a, b) => a.FTestCode.Equals(code1) && b.FFactoryCode.Equals(code2)).Select<dynamic>(selectVal).ToList();
                    break;
                // 20230802 增加试验号 + 版本号 + 工厂查询
                case "6":
                    if (inParam.TryGetValue("SP_VALUE", out object objSpValue6)) code1 = objSpValue6.ToString();
                    if (inParam.TryGetValue("FFactoryCode", out object objFactoryCode6)) code2 = objFactoryCode6.ToString();
                    if (inParam.TryGetValue("SP_VERSION", out object objVersion6)) code3 = objVersion6.ToString();

                    if (string.IsNullOrWhiteSpace(code1) || string.IsNullOrWhiteSpace(code2) || string.IsNullOrWhiteSpace(code3))
                    {
                        return result;
                    }
                    result = db.Queryable<TFS_Material, TFS_ViewMaterial>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FMaterialID))
                        .Where((a, b) => a.FTestCode.Equals(code1) && b.FFactoryCode.Equals(code2) && a.FVersionCode.Equals(code3)).Select<dynamic>(selectVal).ToList();
                    break;
            }
            return result;
        }

        /// <summary>
        /// 物料信息补全导入
        /// </summary>
        public int InsertBatchInfoMaterialData(List<TFS_Material> mainList, List<TFS_MaterialInfo> infoList, List<PropertyInfo> mainProp,
            List<PropertyInfo> childProp, List<TFS_FieldInfo> fieldList, int userId)
        {
            int result = 0;
            if (mainList.Count == 0) return result;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_MaterialType> typeList = db.Queryable<TFS_MaterialType>().Where(s => s.FDeleted != 1).ToList();
            List<Dictionary<string, object>> updateList = new List<Dictionary<string, object>>();
            object dataVal = null; TFS_Material temp1 = null; TFS_MaterialInfo temp2 = null;
            for (int i = 0; i < mainList.Count; i++)
            {
                temp1 = mainList[i];
                temp2 = infoList[i];
                TFS_Material mainMater = db.Queryable<TFS_Material>().Where(s => s.FCode == temp1.FCode).OrderBy(s => s.FID, OrderByType.Desc).First();
                if (mainMater == null) continue;

                List<TFS_MaterialType> tempType1 = typeList.Where(s => s.FName == temp1.FTypeName1.Trim() && s.FDepth == 1).ToList();
                List<TFS_MaterialType> tempType2 = typeList.Where(s => s.FName == temp1.FTypeName2.Trim() && s.FDepth == 2).ToList();
                if (tempType2.Count == 1 && tempType1.Count == 1)
                {
                    mainMater.FTypeID1 = tempType1.FirstOrDefault().FID;
                    mainMater.FTypeID2 = tempType2.FirstOrDefault().FID;
                }
                else
                {
                    foreach (TFS_MaterialType type1 in tempType1)
                    {
                        TFS_MaterialType type2 = tempType2.Find(s => s.FParentID == type1.FID);
                        if (type2 != null)
                        {
                            mainMater.FTypeID1 = type1.FID;
                            mainMater.FTypeID2 = type2.FID;
                            break;
                        }
                    }
                }

                TFS_MaterialInfo childMater = db.Queryable<TFS_MaterialInfo>().Where(s => s.FDataID == mainMater.FID && s.FType == 2)
                    .OrderBy(s => s.FID, OrderByType.Desc).First();
                if (childMater == null && mainMater.FTypeID2 > 0)
                {
                    childMater = db.Queryable<TFS_MaterialInfo>().Where(s => s.FDataID == mainMater.FTypeID2 && s.FType == 1)
                        .OrderBy(s => s.FID, OrderByType.Desc).First();
                    if (childMater != null)
                    {
                        childMater.FID = -1;
                        childMater.FType = 2;
                        childMater.FDataID = mainMater.FID;
                        childMater.FAddDate = null;
                        childMater.FAddUser = userId;
                    }
                }
                if (childMater == null)
                {
                    childMater = new TFS_MaterialInfo()
                    {
                        FType = 2,
                        FDataID = mainMater.FID,
                        FAddUser = userId
                    };
                }
                Dictionary<string, object> update = new Dictionary<string, object>();
                foreach (TFS_FieldInfo field in fieldList)
                {
                    PropertyInfo mProp = mainProp.Find(s => s.Name == field.FColumnFIeld);
                    if (mProp != null && (dataVal = mProp.GetValue(temp1)) != null)
                    {
                        update.Add(field.FColumnFIeld, dataVal);
                    }
                    mProp = childProp.Find(s => s.Name == field.FColumnFIeld);
                    if (mProp != null && (dataVal = mProp.GetValue(temp2)) != null)
                    {
                        mProp.SetValue(childMater, dataVal);
                    }
                }
                if (update.Count > 0)
                {
                    update.Add("FID", mainMater.FID);
                    update.Add("FTypeID1", mainMater.FTypeID1 < 1 ? -1 : mainMater.FTypeID1);
                    update.Add("FTypeID2", mainMater.FTypeID2 < 1 ? -1 : mainMater.FTypeID2);
                    update.Remove("FTypeName1");
                    update.Remove("FTypeName2");
                    update.Add("FEditUser", userId);
                    update.Add("FEditDate", DateTime.Now);
                    updateList.Add(update);
                    infoList[i] = childMater;
                }
                else
                {
                    infoList[i] = null;
                }
            }
            try
            {
                if (updateList.Count > 0)
                {
                    db.BeginTran();
                    result += db.Updateable(updateList).AS("TFS_Material").WhereColumns("FID").IgnoreColumns(true).ExecuteCommand();
                    List<TFS_MaterialInfo> temps = infoList.Where(s => s != null && s.FID > 0).ToList();
                    if (temps.Count > 0) db.Updateable(temps).WhereColumns("FID").IgnoreColumns(true).ExecuteCommand();
                    temps = infoList.Where(s => s != null && s.FID <= 0).ToList();
                    if (temps.Count > 0) db.Insertable(temps).IgnoreColumns(true).ExecuteCommand();
                    db.CommitTran();
                }
                ExceptionHelper.AddSystemJournal(null, mainList, new { updateList, infoList }, userId, "InsertBatchInfoMaterialData");
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                ExceptionHelper.AddSystemJournal(null, mainList, new { updateList, infoList, ex.Message }, userId, "InsertBatchInfoMaterialData");
            }
            return result;
        }

        /// <summary>
        /// 替代料导入处理
        /// </summary>
        public int InsertBatchTiMaterialData(List<TFS_Material> mainList, List<PropertyInfo> mainProp, List<TFS_FieldInfo> fieldList, int userId)
        {
            int result = 0;
            if (mainList.Count == 0) return result;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<Dictionary<string, object>> updateList = new List<Dictionary<string, object>>();
            object dataVal = null; TFS_Material temp = null;
            foreach (var item in mainList.GroupBy(s => new { s.FCode, s.FName }))
            {
                temp = item.ToList().Find(s => !string.IsNullOrEmpty(s.FSuccedaneumCode));
                if (temp == null || string.IsNullOrEmpty(item.Key.FCode)) continue;
                TFS_Material mainMater = db.Queryable<TFS_Material>().Where(s => s.FCode == item.Key.FCode).OrderBy(s => s.FID, OrderByType.Desc).First();
                if (mainMater == null) continue;
                TFS_Material lossMater = db.Queryable<TFS_Material>().Where(s => s.FCode == temp.FSuccedaneumCode).OrderBy(s => s.FID, OrderByType.Desc).First();
                if (lossMater == null) continue;
                Dictionary<string, object> update = new Dictionary<string, object>();
                foreach (TFS_FieldInfo field in fieldList)
                {
                    PropertyInfo mProp = mainProp.Find(s => s.Name == field.FColumnFIeld);
                    if (mProp != null && (dataVal = mProp.GetValue(temp)) != null)
                    {
                        update.Add(field.FColumnFIeld, dataVal);
                    }
                }
                if (update.Count > 0)
                {
                    update.Add("FID", mainMater.FID);
                    update.Add("FEditDate", DateTime.Now);
                    update.Add("FEditUser", userId);
                    update.Add("FSuccedaneumID", lossMater.FID);
                    update.Add("FSuccedaneumInfo", lossMater.FName);
                    update.Add("FSuccedaneumType", lossMater.FType);
                    updateList.Add(update);
                }
            }
            try
            {
                if (updateList.Count > 0)
                {
                    db.BeginTran();
                    result += db.Updateable(updateList).AS("TFS_Material").WhereColumns("FID").IgnoreColumns(true).ExecuteCommand();
                    db.CommitTran();
                }
                ExceptionHelper.AddSystemJournal(null, mainList, updateList, userId, "InsertBatchTiMaterialData");
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                ExceptionHelper.AddSystemJournal(null, mainList, new { updateList, ex.Message }, userId, "InsertBatchTiMaterialData");
            }
            return result;
        }

        /// <summary>
        /// 副产物导入处理
        /// </summary>
        public int InsertBatchFuMaterialData(List<TFS_Material> mainList, List<PropertyInfo> mainProp, List<TFS_FieldInfo> fieldList, int userId)
        {
            int result = 0;
            if (mainList.Count == 0) return result;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<Dictionary<string, object>> updateList = new List<Dictionary<string, object>>();
            object dataVal = null; TFS_Material temp = null;
            foreach (var item in mainList.GroupBy(s => new { s.FCode, s.FName }))
            {
                temp = item.ToList().Find(s => !string.IsNullOrEmpty(s.FFuProductsCode) && !string.IsNullOrEmpty(s.FFuProductsInfo));
                if (temp == null || string.IsNullOrEmpty(item.Key.FCode) || string.IsNullOrEmpty(item.Key.FName)) continue;
                TFS_Material mainMater = db.Queryable<TFS_Material>().Where(s => s.FCode == item.Key.FCode && s.FName == item.Key.FName)
                    .OrderBy(s => s.FID, OrderByType.Desc).First();
                if (mainMater == null) continue;
                TFS_Material lossMater = db.Queryable<TFS_Material>().Where(s => s.FCode == temp.FFuProductsCode && s.FName == temp.FFuProductsInfo)
                    .OrderBy(s => s.FID, OrderByType.Desc).First();
                if (lossMater == null) continue;
                Dictionary<string, object> update = new Dictionary<string, object>();
                foreach (TFS_FieldInfo field in fieldList)
                {
                    PropertyInfo mProp = mainProp.Find(s => s.Name == field.FColumnFIeld);
                    if (mProp != null && (dataVal = mProp.GetValue(temp)) != null)
                    {
                        update.Add(field.FColumnFIeld, dataVal);
                    }
                }
                if (update.Count > 0)
                {
                    update.Add("FID", mainMater.FID);
                    update.Add("FEditDate", DateTime.Now);
                    update.Add("FEditUser", userId);
                    update.Add("FFuProductsID", lossMater.FID);
                    update.Add("FFuProductsType", lossMater.FType);
                    updateList.Add(update);
                }
            }
            try
            {
                if (updateList.Count > 0)
                {
                    db.BeginTran();
                    foreach (var item in updateList)
                    {
                        result += db.Updateable(item).AS("TFS_Material").WhereColumns("FID").IgnoreColumns(true).ExecuteCommand();
                    }
                    db.CommitTran();
                }
                ExceptionHelper.AddSystemJournal(null, mainList, updateList, userId, "InsertBatchFuMaterialData");
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                ExceptionHelper.AddSystemJournal(null, mainList, new { updateList, ex.Message }, userId, "InsertBatchFuMaterialData");
            }
            return result;
        }

        /// <summary>
        /// （对接）SAP物料同步
        /// </summary>
        public int DockSapMaterial(List<TFS_Material> materialList, int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            int okCount = 0;
            db.BeginTran();
            List<TFS_ViewMaterial> views = new List<TFS_ViewMaterial>();
            try
            {
                foreach (TFS_Material item in materialList)
                {
                    TFS_Material temp = db.Queryable<TFS_Material>().Where(s => s.FCode == item.FCode).First();
                    if (temp == null)
                    {
                        temp = item;
                        temp.FID = db.Insertable(item).IgnoreColumns(true).ExecuteReturnIdentity();
                        okCount += 1;
                    }
                    if (db.Queryable<TFS_ViewMaterial>().Where(s => s.FMaterialID == temp.FID && s.FFactoryID == item.FFactoryID).First() == null)
                    {
                        TFS_ViewMaterial view = new TFS_ViewMaterial()
                        {
                            FMaterialID = temp.FID,
                            FFactoryID = item.FFactoryID,
                            FFactoryCode = item.FFactoryCode,
                            FBaseMaterialCode = string.IsNullOrEmpty(item.FCode) ? temp.FCode : item.FCode,
                            FBaseMaterialDesc = string.IsNullOrEmpty(item.FName) ? temp.FName : item.FName,
                            FBaseTestCode = string.IsNullOrEmpty(item.FTestCode) ? temp.FTestCode : item.FTestCode,
                            FBaseBasicMeter = string.IsNullOrEmpty(item.FBaseUnit) ? temp.FBaseUnit : item.FBaseUnit,
                            FBaseMaterialGroup = string.IsNullOrEmpty(item.FMaterialGroup) ? temp.FMaterialGroup : item.FMaterialGroup,
                            FBaseFameCode = string.IsNullOrEmpty(item.FFameCode) ? temp.FFameCode : item.FFameCode,
                            FOrganizeMaterialType = string.IsNullOrEmpty(item.FMaterialType) ? temp.FMaterialType : item.FMaterialType
                        };
                        okCount += db.Insertable(view).IgnoreColumns(true).ExecuteCommand();
                        views.Add(view);
                    }
                }
                db.CommitTran();
                ExceptionHelper.AddSystemJournal(null, materialList, new { views }, userId, "InsertBatchFuMaterialData");
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                ExceptionHelper.AddSystemJournal(null, materialList, new { views, ex.Message }, userId, "InsertBatchFuMaterialData");
            }
            return okCount;
        }

        /// <summary>
        /// 导出视图
        /// </summary>
        /// <param name="intType"></param>
        /// <param name="savePath"></param>
        /// <param name="selectSql"></param>
        /// <param name="whereSql"></param>
        /// <param name="joinSql"></param>
        /// <param name="teamId"></param>
        /// <param name="halfId"></param>
        public void CreateExeclFile(string fType, string savePath, string selectSql, string whereSql, string joinSql, string teamId, string halfId)
        {
            //selectSql = selectSql.Replace("@FMaterialID@", halfId);
            DataTable dataList = new DataTable();

            dataList = GetMaterialInfo(teamId);
            //dataList.Columns.Remove("FMaterialID");
            NPOIHelper.ExportDTtoExcel(dataList, "Sheet1", savePath.Replace(".xlsx", fType + ".xlsx"));
        }


        /// <summary>
        /// 导出SAP视图
        /// </summary>
        /// <param name="intType"></param>
        /// <param name="savePath"></param>
        /// <param name="selectSql"></param>
        /// <param name="whereSql"></param>
        /// <param name="joinSql"></param>
        /// <param name="teamId"></param>
        /// <param name="halfId"></param>
        public void CreateExeclFileSAP(string fType, string savePath, string selectSql, string whereSql, string joinSql, string teamId, string halfId)
        {
            DataTable dataList = new DataTable();

            dataList = GetMaterialInfoSAP(teamId);
            //dataList.Columns.Remove("FMaterialID");
            NPOIHelper.ExportDTtoExcel(dataList, "Sheet1", savePath.Replace(".xlsx", fType + ".xlsx"));
        }

        public DataTable GetMaterialInfo(string FID) 
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = string.Format(@"	
                                            SELECT
 	                                            isnull( replace(FTypeName1,'(空)',''), '' ) AS '一级分类',
	                                            isnull(  replace(FTypeName2,'(空)',''), '' ) AS '二级分类',
	                                            isnull(  replace(FK3Code,'(空)',''), '' ) AS 'K3系统代码',
	                                            isnull(  replace(FK3Name,'(空)',''), '' ) AS 'K3系统名称',
	                                            isnull(  replace(FK3ShortCode,'(空)',''), '' ) AS 'K3系统短代码',
	                                            isnull(  replace(FTestCode,'(空)',''), '' ) AS '产品试验号',
	                                            isnull(  replace(FCode,'(空)',''), '' ) AS 'SAP系统代码',
	                                            isnull(  replace(FName,'(空)',''), '' ) AS 'SAP系统描述',
	                                            isnull(  replace(FMaterialGroup,'(空)',''), '' ) AS '物料组',
	                                            isnull(  replace(FMaterialType,'(空)',''), '' ) AS '物料主分类',
	                                            isnull(  replace(FCustomerCode,'(空)',''), '' ) AS '客供料标识',
	                                            isnull(  replace(FStoreHouse,'(空)',''), '' ) AS '总仓地址',
	                                            isnull(  replace(FBomEntry,'(空)',''), '' ) AS 'BOM录入情况',
	                                            isnull(  replace(FLineHouse,'(空)',''), '' ) AS '线边仓地址',
	                                            isnull(  replace(FProductDesc,'(空)',''), '' ) AS '产品说明',
	                                            isnull(  replace(FWorkCenter,'(空)',''), '' ) AS '工作中心',
	                                            isnull(  replace(FCraftExplain,'(空)',''), '' ) AS '工艺说明',
	                                            isnull(  replace(FIidentifier,'(空)',''), '' ) AS '标识符',
	                                            isnull(  replace(FGuaranteePeriod,'(空)',''), '' ) AS '保质期',
	                                            isnull(  replace(FStorageConditions,'(空)',''), '' ) AS '存储条件',
	                                            isnull(  replace(FSafetyStock,'(空)',''), '' ) AS '安全库存',
	                                            isnull(  replace(FTriggerRatio,'(空)',''), '' ) AS '触发比例',
	                                            isnull(  replace(FMinAmount,'(空)',''), '' ) AS '最小量',
	                                            isnull(  replace(FMaxAmount,'(空)',''), '' ) AS '最大量',
	                                            isnull(  replace(FYield,'(空)',''), '' ) AS '得率',
	                                            isnull(  replace(FFixedLoss,'(空)',''), '' ) AS '固损',
	                                            isnull( replace(FTheoryYield,'(空)',''), '' ) AS '理论得率',
	                                            isnull( replace(FQualityTest1,'(空)',''), '' ) AS '品质检验1',
	                                            isnull( replace(FQualityTest2,'(空)',''), '' ) AS '品质检验2',
	                                            isnull( replace(FName,'(空)',''), '' ) AS '物料名称',
	                                            isnull( replace(FDesc,'(空)',''), '' ) AS '物料简介',
	                                            isnull( replace(FType,'(空)',''), '' ) AS '物料类型',
	                                            isnull( replace(FCode,'(空)',''), '' ) AS '物料编码',
	                                            isnull( replace(FTestCode,'(空)',''), '' ) AS '试验号',
	                                            isnull( replace(FVersionCode,'(空)',''), '' ) AS '配方内码',
	                                            isnull( replace(FFactoryCode,'(空)',''), '' ) AS '工厂代码',
	                                            isnull( replace(FSupplyCode,'(空)',''), '' ) AS '物料供应标识',
	                                            isnull( replace(FGroupCode,'(空)',''), '' ) AS '组编号',
	                                            isnull( replace(FBaseUnit,'(空)',''), '' ) AS '基本计量单位',
	                                            isnull( replace(FMaterialGroup,'(空)',''), '' ) AS '物料组',
	                                            isnull( replace(FStoreHouse,'(空)',''), '' ) AS '总仓地址',
	                                            isnull( replace(FWorkCenter,'(空)',''), '' ) AS '工作中心',
	                                            isnull( replace(FCraftDesc,'(空)',''), '' ) AS '工艺描述',
	                                            isnull( replace(FCraftExplain,'(空)',''), '' ) AS '工艺说明',
	                                            isnull( replace(FLineHouse,'(空)',''), '' ) AS '线边仓',
	                                            isnull( replace(FFixedLoss,'(空)',''), '' ) AS '固定损耗',
	                                            isnull( replace(FOrganizeIndustryField,'(空)',''), '' ) AS '组织级别.行业领域',
	                                            isnull( replace(FOrganizeMaterialType,'(空)',''), '' ) AS '组织级别.物料类型',
	                                            isnull( replace(FOrganizeFactory,'(空)',''), '' ) AS '组织级别.工厂',
	                                            isnull( replace(FOrganizeInventoryLocation,'(空)',''), '' ) AS '组织级别.库存地点',
	                                            isnull( replace(FOrganizeSalesOrganize,'(空)',''), '' ) AS '组织级别.销售组织',
	                                            isnull( replace(FOrganizeDistributionChannel,'(空)',''), '' ) AS '组织级别.分销渠道',
	                                            isnull( replace(FBaseMaterialCode,'(空)',''), '' ) AS '基本视图.物料编号',
	                                            isnull( replace(FBaseTestCode,'(空)',''), '' ) AS '基本视图.试验号',
	                                            isnull( replace(FBaseBasicMeter,'(空)',''), '' ) AS '基本视图.基本计量',
	                                            isnull( replace(FBaseMaterialDesc,'(空)',''), '' ) AS '基本视图.物料描述',
	                                            isnull( replace(FBaseMaterialGroup,'(空)',''), '' ) AS '基本视图.物料组',
	                                            isnull( replace(FBaseSpecification,'(空)',''), '' ) AS '基本视图.大小/量纲(规格)',
	                                            isnull( replace(FBaseMaterialText,'(空)',''), '' ) AS '基本视图.物料长文本',
	                                            isnull( replace(FBaseIdentifier,'(空)',''), '' ) AS '基本视图.标识符:固体/液体',
	                                            isnull( replace(FBaseVolumeUnit,'(空)',''), '' ) AS '基本视图.体积单位',
	                                            isnull( replace(FBaseGrossWeight,'(空)',''), '' ) AS '基本视图.毛重',
	                                            isnull( replace(FBaseNetWeight,'(空)',''), '' ) AS '基本视图.净重',
	                                            isnull( replace(FBaseWeightUnit,'(空)',''), '' ) AS '基本视图.重量单位',
	                                            isnull( replace(FBaseBusinessVolume,'(空)',''), '' ) AS '基本视图.业务量',
	                                            isnull( replace(FBaseFameCode,'(空)',''), '' ) AS '基本视图.fame号',
	                                            isnull( replace(FPurchaseGroup,'(空)',''), '' ) AS '采购视图.采购组',
	                                            isnull( replace(FPurchaseCompany,'(空)',''), '' ) AS '采购视图.采购单位',
	                                            isnull( replace(FPurchaseCompanyCount,'(空)',''), '' ) AS '采购视图.采购单位数量',
	                                            isnull( replace(FPurchaseBaseCompanyCount,'(空)',''), '' ) AS '采购视图.采购基本单位数量',
	                                            isnull( replace(FPurchaseValueCode,'(空)',''), '' ) AS '采购视图.采购价值码',
	                                            isnull( replace(FPurchaseFactorySpecificStatus,'(空)',''), '' ) AS '采购视图.工厂特定状态',
	                                            isnull( replace(FPurchaseAutoOrder,'(空)',''), '' ) AS '采购视图.自动采购单标识',
	                                            isnull( replace(FPurchaseGoodsSource,'(空)',''), '' ) AS '采购视图.货源清单',
	                                            isnull( replace(FTypeCategoryType,'(空)',''), '' ) AS '分类视图.类别种类',
	                                            isnull( replace(FTypeType,'(空)',''), '' ) AS '分类视图.类别',
	                                            isnull( replace(FSaleDeliveryFactory,'(空)',''), '' ) AS '销售视图.交货工厂',
	                                            isnull( replace(FSaleTaxType,'(空)',''), '' ) AS '销售视图.税金分类',
	                                            isnull( replace(FSaleMaterialStatisticsGroup,'(空)',''), '' ) AS '销售视图.物料统计组',
	                                            isnull( replace(FSaleSalesCompany,'(空)',''), '' ) AS '销售视图.销售单位',
	                                            isnull( replace(FSaleBaseCompanyCount,'(空)',''), '' ) AS '销售视图.基本单位数量',
	                                            isnull( replace(FSaleSalesCompanyCount,'(空)',''), '' ) AS '销售视图.销售单位数量',
	                                            isnull( replace(FSaleAccountSettingGroup,'(空)',''), '' ) AS '销售视图.科目设置组',
	                                            isnull( replace(FSaleGeneralProjectCategoryGroup,'(空)',''), '' ) AS '销售视图.普通项目类别组',
	                                            isnull( replace(FSaleProjectCategoryGroup,'(空)',''), '' ) AS '销售视图.项目类别组',
	                                            isnull( replace(FSaleAvailabilityCheck,'(空)',''), '' ) AS '销售视图.可用性检查',
	                                            isnull( replace(FSaleOutfitGroup,'(空)',''), '' ) AS '销售视图.装载组',
	                                            isnull( replace(FSaleOldMaterialCode,'(空)',''), '' ) AS '销售视图.旧物料号',
	                                            isnull( replace(FStorageConditions,'(空)',''), '' ) AS '仓储视图.存储条件',
	                                            isnull( replace(FStorageBatchManage,'(空)',''), '' ) AS '仓储视图.批次管理',
	                                            isnull( replace(FStorageMaxStoragePeriod,'(空)',''), '' ) AS '仓储视图.最大存储期间',
	                                            isnull( replace(FStorageTimeUnit,'(空)',''), '' ) AS '仓储视图.时间单位',
	                                            isnull( replace(FStorageMinSurplusShelfLife,'(空)',''), '' ) AS '仓储视图.最小剩余货架寿命',
	                                            isnull( replace(FStorageTotalShelfLife,'(空)',''), '' ) AS '仓储视图.总货架寿命',
	                                            isnull( replace(FStorageSLEDCode,'(空)',''), '' ) AS '仓储视图.SLED期间标识',
	                                            isnull( replace(FMRP1Type,'(空)',''), '' ) AS 'MRP1.MRP类型',
	                                            isnull( replace(FMRP1Controller,'(空)',''), '' ) AS 'MRP1.MRP控制者',
	                                            isnull( replace(FMRP1BatchSize,'(空)',''), '' ) AS 'MRP1.批量大小',
	                                            isnull( replace(FMRP1MinBatchSize,'(空)',''), '' ) AS 'MRP1.最小批量大小',
	                                            isnull( replace(FMRP1MaxBatchSize,'(空)',''), '' ) AS 'MRP1.最大批量大小',
	                                            isnull( replace(FMRP1Group,'(空)',''), '' ) AS 'MRP1.MRP组',
	                                            isnull( replace(FMRP1RoundValue,'(空)',''), '' ) AS 'MRP1.舍入值',
	                                            isnull( replace(FMRP1ProductType,'(空)',''), '' ) AS 'MRP1.产品分类',
	                                            isnull( replace(FMRP1CustomerCode,'(空)',''), '' ) AS 'MRP1.客户代码',
	                                            isnull( replace(FMRP1SizeMaterial,'(空)',''), '' ) AS 'MRP1.大小料',
	                                            isnull( replace(FMRP1SmallMaterialStandard,'(空)',''), '' ) AS 'MRP1.小料标准（小于）',
	                                            isnull( replace(FMRP2PurchaseType,'(空)',''), '' ) AS 'MRP2.采购类型',
	                                            isnull( replace(FMRP2PlanMarginalCode,'(空)',''), '' ) AS 'MRP2.计划边际码',
	                                            isnull( replace(FMRP2SpecialProcurement,'(空)',''), '' ) AS 'MRP2.特殊采购类',
	                                            isnull( replace(FMRP2Recoil,'(空)',''), '' ) AS 'MRP2.反冲',
	                                            isnull( replace(FMRP2SelfProductTime,'(空)',''), '' ) AS 'MRP2.自制生产时间',
	                                            isnull( replace(FMRP2PlannDeliveryTime,'(空)',''), '' ) AS 'MRP2.计划交货时间',
	                                            isnull( replace(FMRP2ReceiveProcessTime,'(空)',''), '' ) AS 'MRP2.收货处理时间',
	                                            isnull( replace(FMRP2SafeStock,'(空)',''), '' ) AS 'MRP2.安全库存',
	                                            isnull( replace(FMRP2DeliveryInventoryPlace,'(空)',''), '' ) AS 'MRP2.发货库存地点',
	                                            isnull( replace(FMRP2ExternalStoragePlace,'(空)',''), '' ) AS 'MRP2.外部采购仓储地点',
	                                            isnull( replace(FMRP3PolicyGroup,'(空)',''), '' ) AS 'MRP3.策略组',
	                                            isnull( replace(FMRP3ConsumePattern,'(空)',''), '' ) AS 'MRP3.消耗模式',
	                                            isnull( replace(FMRP3ForwardConsumePeriod,'(空)',''), '' ) AS 'MRP3.向前消耗期间',
	                                            isnull( replace(FMRP3ReverseConsumePeriod,'(空)',''), '' ) AS 'MRP3.逆向消耗期',
	                                            isnull( replace(FMRP3BlendMRP,'(空)',''), '' ) AS 'MRP3.混合MRP',
	                                            isnull( replace(FMRP3AvailabilityCheck,'(空)',''), '' ) AS 'MRP3.可用性检查',
	                                            isnull( replace(FMRP4AloneOrFocus,'(空)',''), '' ) AS 'MRP3.单独或集中',
	                                            isnull( replace(FPlanProductPlanParam,'(空)',''), '' ) AS '工作计划视图.生产计划参数文件',
	                                            isnull( replace(FPlanUnlimitedOverDelivery,'(空)',''), '' ) AS '工作计划视图.无限制过量交货',
	                                            isnull( replace(FPlanUnderDeliveryTolerance,'(空)',''), '' ) AS '工作计划视图.不足交货允差',
	                                            isnull( replace(FPlanOverDeliveryTolerance,'(空)',''), '' ) AS '工作计划视图.过度交货允差',
	                                            isnull( replace(FPlanDeliverCompany,'(空)',''), '' ) AS '工作计划视图.发货单位',
	                                            isnull( replace(FPlanDeliverCompanyCount,'(空)',''), '' ) AS '工作计划视图.发货单位数量',
	                                            isnull( replace(FPlanBaseCompanyCount,'(空)',''), '' ) AS '工作计划视图.发货基本单位数量',
	                                            isnull( replace(FQualityType1,'(空)',''), '' ) AS '质检视图.检验类型1',
	                                            isnull( replace(FQualityType2,'(空)',''), '' ) AS '质检视图.检验类型2',
	                                            isnull( replace(FQualityType3,'(空)',''), '' ) AS '质检视图.检验类型3',
	                                            isnull( replace(FQualityType4,'(空)',''), '' ) AS '质检视图.检验类型4',
	                                            isnull( replace(FQualityType5,'(空)',''), '' ) AS '质检视图.检验类型5',
	                                            isnull( replace(FQualityType6,'(空)',''), '' ) AS '质检视图.检验类型6',
	                                            isnull( replace(FAccountPriceControl,'(空)',''), '' ) AS '会计视图.价格控制',
	                                            isnull( replace(FAccountPriceDetermine,'(空)',''), '' ) AS '会计视图.价格确定',
	                                            isnull( replace(FAccountPriceUnit,'(空)',''), '' ) AS '会计视图.价格单位',
	                                            isnull( replace(FAccountAccessType,'(空)',''), '' ) AS '会计视图.评估分类',
	                                            isnull( replace(FAccountSaleOrderInventory,'(空)',''), '' ) AS '会计视图.VC: 销售订单库存',
	                                            isnull( replace(FAccountStandardPrice,'(空)',''), '' ) AS '会计视图.标准价格',
	                                            isnull( replace(FAccountProfitCenter,'(空)',''), '' ) AS '会计视图.利润中心',
	                                            isnull( replace(FAccountCostAccountBatch,'(空)',''), '' ) AS '会计视图.成本核算批量' 
                                            FROM(
                                            SELECT
	                                            isnull( b.FName, '' ) AS 'FTypeName1',
	                                            isnull( c.FName, '' ) AS 'FTypeName2',
	                                            isnull( FSAPCode, '' ) AS 'FCode',
	                                            isnull( FSAPDescription, '' ) AS 'FName',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FDesc',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FVersionCode',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FFactoryCode',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FSupplyCode',
	                                            isnull( FBaseMaterialGroup, '' ) AS 'FGroupCode',
	                                            isnull( FBaseWeightUnit, '' ) AS 'FBaseUnit',
	                                            isnull( FCraftExplain, '' ) AS 'FCraftDesc',
                                                d.FName AS 'FtypeName',
	                                            a.*
                                            FROM
	                                            TFS_MaterialInfo AS a
                                                LEFT JOIN TFS_MaterialType AS d ON a.FType=d.FID
	                                            LEFT JOIN TFS_MaterialType AS b ON a.FTypeID1= b.FID
	                                            LEFT JOIN TFS_MaterialType AS C ON a.FTypeID2= b.FID 
                                            WHERE
	                                            FDataId = {0})a;", FID);
            DataTable data = db.Ado.GetDataTable(strSql);
            return data;
        }

        public DataTable GetMaterialInfoSAP(string FID)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = string.Format(@"	
                                            SELECT
                                                isnull( FName, '' ) AS '物料名称',
	                                            isnull( FDesc, '' ) AS '物料简介',
	                                            isnull(  REPLACE ( FType , FType , FtypeName ), '' ) AS '物料类型',
	                                            isnull( FCode, '' ) AS '物料编码',
	                                            isnull( FTestCode, '' ) AS '试验号',
	                                            isnull( FVersionCode, '' ) AS '配方内码',
	                                            isnull( FFactoryCode, '' ) AS '工厂代码',
	                                            isnull( FSupplyCode, '' ) AS '物料供应标识',
	                                            isnull( FGroupCode, '' ) AS '组编号',
	                                            isnull( FBaseUnit, '' ) AS '基本计量单位',
	                                            isnull( FMaterialGroup, '' ) AS '物料组',
	                                            isnull( FStoreHouse, '' ) AS '总仓地址',
	                                            isnull( FWorkCenter, '' ) AS '工作中心',
	                                            isnull( FCraftDesc, '' ) AS '工艺描述',
	                                            isnull( FCraftExplain, '' ) AS '工艺说明',
	                                            isnull( FLineHouse, '' ) AS '线边仓',
	                                            isnull( FFixedLoss, '' ) AS '固定损耗',
	                                            isnull( FOrganizeIndustryField, '' ) AS '组织级别.行业领域',
	                                            isnull( FOrganizeMaterialType, '' ) AS '组织级别.物料类型',
	                                            isnull( FOrganizeFactory, '' ) AS '组织级别.工厂',
	                                            isnull( FOrganizeInventoryLocation, '' ) AS '组织级别.库存地点',
	                                            isnull( FOrganizeSalesOrganize, '' ) AS '组织级别.销售组织',
	                                            isnull( FOrganizeDistributionChannel, '' ) AS '组织级别.分销渠道',
	                                            isnull( FBaseMaterialCode, '' ) AS '基本视图.物料编号',
	                                            isnull( FBaseTestCode, '' ) AS '基本视图.试验号',
	                                            isnull( FBaseBasicMeter, '' ) AS '基本视图.基本计量',
	                                            isnull( FBaseMaterialDesc, '' ) AS '基本视图.物料描述',
	                                            isnull( FBaseMaterialGroup, '' ) AS '基本视图.物料组',
	                                            isnull( FBaseSpecification, '' ) AS '基本视图.大小/量纲(规格)',
	                                            isnull( FBaseMaterialText, '' ) AS '基本视图.物料长文本',
	                                            isnull( FBaseIdentifier, '' ) AS '基本视图.标识符:固体/液体',
	                                            isnull( FBaseVolumeUnit, '' ) AS '基本视图.体积单位',
	                                            isnull( FBaseGrossWeight, '' ) AS '基本视图.毛重',
	                                            isnull( FBaseNetWeight, '' ) AS '基本视图.净重',
	                                            isnull( FBaseWeightUnit, '' ) AS '基本视图.重量单位',
	                                            isnull( FBaseBusinessVolume, '' ) AS '基本视图.业务量',
	                                            isnull( FBaseFameCode, '' ) AS '基本视图.fame号',
	                                            isnull( FPurchaseGroup, '' ) AS '采购视图.采购组',
	                                            isnull( FPurchaseCompany, '' ) AS '采购视图.采购单位',
	                                            isnull( FPurchaseCompanyCount, '' ) AS '采购视图.采购单位数量',
	                                            isnull( FPurchaseBaseCompanyCount, '' ) AS '采购视图.采购基本单位数量',
	                                            isnull( FPurchaseValueCode, '' ) AS '采购视图.采购价值码',
	                                            isnull( FPurchaseFactorySpecificStatus, '' ) AS '采购视图.工厂特定状态',
	                                            isnull( FPurchaseAutoOrder, '' ) AS '采购视图.自动采购单标识',
	                                            isnull( FPurchaseGoodsSource, '' ) AS '采购视图.货源清单',
	                                            isnull( FTypeCategoryType, '' ) AS '分类视图.类别种类',
	                                            isnull( FTypeType, '' ) AS '分类视图.类别',
	                                            isnull( FSaleDeliveryFactory, '' ) AS '销售视图.交货工厂',
	                                            isnull( FSaleTaxType, '' ) AS '销售视图.税金分类',
	                                            isnull( FSaleMaterialStatisticsGroup, '' ) AS '销售视图.物料统计组',
	                                            isnull( FSaleSalesCompany, '' ) AS '销售视图.销售单位',
	                                            isnull( FSaleBaseCompanyCount, '' ) AS '销售视图.基本单位数量',
	                                            isnull( FSaleSalesCompanyCount, '' ) AS '销售视图.销售单位数量',
	                                            isnull( FSaleAccountSettingGroup, '' ) AS '销售视图.科目设置组',
	                                            isnull( FSaleGeneralProjectCategoryGroup, '' ) AS '销售视图.普通项目类别组',
	                                            isnull( FSaleProjectCategoryGroup, '' ) AS '销售视图.项目类别组',
	                                            isnull( FSaleAvailabilityCheck, '' ) AS '销售视图.可用性检查',
	                                            isnull( FSaleOutfitGroup, '' ) AS '销售视图.装载组',
	                                            isnull( FSaleOldMaterialCode, '' ) AS '销售视图.旧物料号',
	                                            isnull( FStorageConditions, '' ) AS '仓储视图.存储条件',
	                                            isnull( FStorageBatchManage, '' ) AS '仓储视图.批次管理',
	                                            isnull( FStorageMaxStoragePeriod, '' ) AS '仓储视图.最大存储期间',
	                                            isnull( FStorageTimeUnit, '' ) AS '仓储视图.时间单位',
	                                            isnull( FStorageMinSurplusShelfLife, '' ) AS '仓储视图.最小剩余货架寿命',
	                                            isnull( FStorageTotalShelfLife, '' ) AS '仓储视图.总货架寿命',
	                                            isnull( FStorageSLEDCode, '' ) AS '仓储视图.SLED期间标识',
	                                            isnull( FMRP1Type, '' ) AS 'MRP1.MRP类型',
	                                            isnull( FMRP1Controller, '' ) AS 'MRP1.MRP控制者',
	                                            isnull( FMRP1BatchSize, '' ) AS 'MRP1.批量大小',
	                                            isnull( FMRP1MinBatchSize, '' ) AS 'MRP1.最小批量大小',
	                                            isnull( FMRP1MaxBatchSize, '' ) AS 'MRP1.最大批量大小',
	                                            isnull( FMRP1Group, '' ) AS 'MRP1.MRP组',
	                                            isnull( FMRP1RoundValue, '' ) AS 'MRP1.舍入值',
	                                            isnull( FMRP1ProductType, '' ) AS 'MRP1.产品分类',
	                                            isnull( FMRP1CustomerCode, '' ) AS 'MRP1.客户代码',
	                                            isnull( FMRP1SizeMaterial, '' ) AS 'MRP1.大小料',
	                                            isnull( FMRP1SmallMaterialStandard, '' ) AS 'MRP1.小料标准（小于）',
	                                            isnull( FMRP2PurchaseType, '' ) AS 'MRP2.采购类型',
	                                            isnull( FMRP2PlanMarginalCode, '' ) AS 'MRP2.计划边际码',
	                                            isnull( FMRP2SpecialProcurement, '' ) AS 'MRP2.特殊采购类',
	                                            isnull( FMRP2Recoil, '' ) AS 'MRP2.反冲',
	                                            isnull( FMRP2SelfProductTime, '' ) AS 'MRP2.自制生产时间',
	                                            isnull( FMRP2PlannDeliveryTime, '' ) AS 'MRP2.计划交货时间',
	                                            isnull( FMRP2ReceiveProcessTime, '' ) AS 'MRP2.收货处理时间',
	                                            isnull( FMRP2SafeStock, '' ) AS 'MRP2.安全库存',
	                                            isnull( FMRP2DeliveryInventoryPlace, '' ) AS 'MRP2.发货库存地点',
	                                            isnull( FMRP2ExternalStoragePlace, '' ) AS 'MRP2.外部采购仓储地点',
	                                            isnull( FMRP3PolicyGroup, '' ) AS 'MRP3.策略组',
	                                            isnull( FMRP3ConsumePattern, '' ) AS 'MRP3.消耗模式',
	                                            isnull( FMRP3ForwardConsumePeriod, '' ) AS 'MRP3.向前消耗期间',
	                                            isnull( FMRP3ReverseConsumePeriod, '' ) AS 'MRP3.逆向消耗期',
	                                            isnull( FMRP3BlendMRP, '' ) AS 'MRP3.混合MRP',
	                                            isnull( FMRP3AvailabilityCheck, '' ) AS 'MRP3.可用性检查',
	                                            isnull( FMRP4AloneOrFocus, '' ) AS 'MRP3.单独或集中',
	                                            isnull( FPlanProductPlanParam, '' ) AS '工作计划视图.生产计划参数文件',
	                                            isnull( FPlanUnlimitedOverDelivery, '' ) AS '工作计划视图.无限制过量交货',
	                                            isnull( FPlanUnderDeliveryTolerance, '' ) AS '工作计划视图.不足交货允差',
	                                            isnull( FPlanOverDeliveryTolerance, '' ) AS '工作计划视图.过度交货允差',
	                                            isnull( FPlanDeliverCompany, '' ) AS '工作计划视图.发货单位',
	                                            isnull( FPlanDeliverCompanyCount, '' ) AS '工作计划视图.发货单位数量',
	                                            isnull( FPlanBaseCompanyCount, '' ) AS '工作计划视图.发货基本单位数量',
	                                            isnull( FQualityType1, '' ) AS '质检视图.检验类型1',
	                                            isnull( FQualityType2, '' ) AS '质检视图.检验类型2',
	                                            isnull( FQualityType3, '' ) AS '质检视图.检验类型3',
	                                            isnull( FQualityType4, '' ) AS '质检视图.检验类型4',
	                                            isnull( FQualityType5, '' ) AS '质检视图.检验类型5',
	                                            isnull( FQualityType6, '' ) AS '质检视图.检验类型6',
	                                            isnull( FAccountPriceControl, '' ) AS '会计视图.价格控制',
	                                            isnull( FAccountPriceDetermine, '' ) AS '会计视图.价格确定',
	                                            isnull( FAccountPriceUnit, '' ) AS '会计视图.价格单位',
	                                            isnull( FAccountAccessType, '' ) AS '会计视图.评估分类',
	                                            isnull( FAccountSaleOrderInventory, '' ) AS '会计视图.VC: 销售订单库存',
	                                            isnull( FAccountStandardPrice, '' ) AS '会计视图.标准价格',
	                                            isnull( FAccountProfitCenter, '' ) AS '会计视图.利润中心',
	                                            isnull( FAccountCostAccountBatch, '' ) AS '会计视图.成本核算批量' 
	                                            
                                            FROM(
                                            SELECT
	                                            isnull( b.FName, '' ) AS 'FTypeName1',
	                                            isnull( c.FName, '' ) AS 'FTypeName2',
	                                            isnull( FSAPCode, '' ) AS 'FCode',
	                                            isnull( FSAPDescription, '' ) AS 'FName',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FDesc',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FVersionCode',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FFactoryCode',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FSupplyCode',
	                                            isnull( FBaseMaterialGroup, '' ) AS 'FGroupCode',
	                                            isnull( FBaseWeightUnit, '' ) AS 'FBaseUnit',
	                                            isnull( FCraftExplain, '' ) AS 'FCraftDesc',
                                                d.FName AS 'FtypeName',
	                                            a.*
                                            FROM
	                                            TFS_MaterialInfo AS a
                                                LEFT JOIN TFS_MaterialType AS d ON a.FType=d.FID
	                                            LEFT JOIN TFS_MaterialType AS b ON a.FTypeID1= b.FID
	                                            LEFT JOIN TFS_MaterialType AS C ON a.FTypeID2= b.FID 
                                            WHERE
	                                            FDataId = {0})a;", FID);
            DataTable data = db.Ado.GetDataTable(strSql);
            return data;
        }


        public void CreateExeclFileALL(string FType,string savePath)
        {
            DataTable dataList = new DataTable();
            string str = "";
            if (FType == "1")
            {
                str = "全部视图";
                dataList = GetMaterialInfoALL();
            }
            else {
                str = "SAP视图";
                dataList = GetMaterialInfoSAPALL();
            }
            
            //dataList.Columns.Remove("FMaterialID");
            NPOIHelper.ExportDTtoExcel(dataList, "Sheet1", savePath.Replace(".xlsx",str+".xlsx"));
        }

        public DataTable GetMaterialInfoALL()
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = string.Format(@"	
                                            SELECT
 	                                            isnull( FTypeName1, '' ) AS '一级分类',
	                                            isnull( FTypeName2, '' ) AS '二级分类',
	                                            isnull( FK3Code, '' ) AS 'K3系统代码',
	                                            isnull( FK3Name, '' ) AS 'K3系统名称',
	                                            isnull( FK3ShortCode, '' ) AS 'K3系统短代码',
	                                            isnull( FTestCode, '' ) AS '产品试验号',
	                                            isnull( FCode, '' ) AS 'SAP系统代码',
	                                            isnull( FName, '' ) AS 'SAP系统描述',
	                                            isnull( FMaterialGroup, '' ) AS '物料组',
	                                            isnull( FMaterialType, '' ) AS '物料主分类',
	                                            isnull( FCustomerCode, '' ) AS '客供料标识',
	                                            isnull( FStoreHouse, '' ) AS '总仓地址',
	                                            isnull( FBomEntry, '' ) AS 'BOM录入情况',
	                                            isnull( FLineHouse, '' ) AS '线边仓地址',
	                                            isnull( FProductDesc, '' ) AS '产品说明',
	                                            isnull( FWorkCenter, '' ) AS '工作中心',
	                                            isnull( FCraftExplain, '' ) AS '工艺说明',
	                                            isnull( FIidentifier, '' ) AS '标识符',
	                                            isnull( FGuaranteePeriod, '' ) AS '保质期',
	                                            isnull( FStorageConditions, '' ) AS '存储条件',
	                                            isnull( FSafetyStock, '' ) AS '安全库存',
	                                            isnull( FTriggerRatio, '' ) AS '触发比例',
	                                            isnull( FMinAmount, '' ) AS '最小量',
	                                            isnull( FMaxAmount, '' ) AS '最大量',
	                                            isnull( FYield, '' ) AS '得率',
	                                            isnull( FFixedLoss, '' ) AS '固损',
	                                            isnull( FTheoryYield, '' ) AS '理论得率',
	                                            isnull( FQualityTest1, '' ) AS '品质检验1',
	                                            isnull( FQualityTest2, '' ) AS '品质检验2',
	                                            isnull( FName, '' ) AS '物料名称',
	                                            isnull( FDesc, '' ) AS '物料简介',
	                                            isnull( FType, '' ) AS '物料类型',
	                                            isnull( FCode, '' ) AS '物料编码',
	                                            isnull( FTestCode, '' ) AS '试验号',
	                                            isnull( FVersionCode, '' ) AS '配方内码',
	                                            isnull( FFactoryCode, '' ) AS '工厂代码',
	                                            isnull( FSupplyCode, '' ) AS '物料供应标识',
	                                            isnull( FGroupCode, '' ) AS '组编号',
	                                            isnull( FBaseUnit, '' ) AS '基本计量单位',
	                                            isnull( FMaterialGroup, '' ) AS '物料组',
	                                            isnull( FStoreHouse, '' ) AS '总仓地址',
	                                            isnull( FWorkCenter, '' ) AS '工作中心',
	                                            isnull( FCraftDesc, '' ) AS '工艺描述',
	                                            isnull( FCraftExplain, '' ) AS '工艺说明',
	                                            isnull( FLineHouse, '' ) AS '线边仓',
	                                            isnull( FFixedLoss, '' ) AS '固定损耗',
	                                            isnull( FOrganizeIndustryField, '' ) AS '组织级别.行业领域',
	                                            isnull( FOrganizeMaterialType, '' ) AS '组织级别.物料类型',
	                                            isnull( FOrganizeFactory, '' ) AS '组织级别.工厂',
	                                            isnull( FOrganizeInventoryLocation, '' ) AS '组织级别.库存地点',
	                                            isnull( FOrganizeSalesOrganize, '' ) AS '组织级别.销售组织',
	                                            isnull( FOrganizeDistributionChannel, '' ) AS '组织级别.分销渠道',
	                                            isnull( FBaseMaterialCode, '' ) AS '基本视图.物料编号',
	                                            isnull( FBaseTestCode, '' ) AS '基本视图.试验号',
	                                            isnull( FBaseBasicMeter, '' ) AS '基本视图.基本计量',
	                                            isnull( FBaseMaterialDesc, '' ) AS '基本视图.物料描述',
	                                            isnull( FBaseMaterialGroup, '' ) AS '基本视图.物料组',
	                                            isnull( FBaseSpecification, '' ) AS '基本视图.大小/量纲(规格)',
	                                            isnull( FBaseMaterialText, '' ) AS '基本视图.物料长文本',
	                                            isnull( FBaseIdentifier, '' ) AS '基本视图.标识符:固体/液体',
	                                            isnull( FBaseVolumeUnit, '' ) AS '基本视图.体积单位',
	                                            isnull( FBaseGrossWeight, '' ) AS '基本视图.毛重',
	                                            isnull( FBaseNetWeight, '' ) AS '基本视图.净重',
	                                            isnull( FBaseWeightUnit, '' ) AS '基本视图.重量单位',
	                                            isnull( FBaseBusinessVolume, '' ) AS '基本视图.业务量',
	                                            isnull( FBaseFameCode, '' ) AS '基本视图.fame号',
	                                            isnull( FPurchaseGroup, '' ) AS '采购视图.采购组',
	                                            isnull( FPurchaseCompany, '' ) AS '采购视图.采购单位',
	                                            isnull( FPurchaseCompanyCount, '' ) AS '采购视图.采购单位数量',
	                                            isnull( FPurchaseBaseCompanyCount, '' ) AS '采购视图.采购基本单位数量',
	                                            isnull( FPurchaseValueCode, '' ) AS '采购视图.采购价值码',
	                                            isnull( FPurchaseFactorySpecificStatus, '' ) AS '采购视图.工厂特定状态',
	                                            isnull( FPurchaseAutoOrder, '' ) AS '采购视图.自动采购单标识',
	                                            isnull( FPurchaseGoodsSource, '' ) AS '采购视图.货源清单',
	                                            isnull( FTypeCategoryType, '' ) AS '分类视图.类别种类',
	                                            isnull( FTypeType, '' ) AS '分类视图.类别',
	                                            isnull( FSaleDeliveryFactory, '' ) AS '销售视图.交货工厂',
	                                            isnull( FSaleTaxType, '' ) AS '销售视图.税金分类',
	                                            isnull( FSaleMaterialStatisticsGroup, '' ) AS '销售视图.物料统计组',
	                                            isnull( FSaleSalesCompany, '' ) AS '销售视图.销售单位',
	                                            isnull( FSaleBaseCompanyCount, '' ) AS '销售视图.基本单位数量',
	                                            isnull( FSaleSalesCompanyCount, '' ) AS '销售视图.销售单位数量',
	                                            isnull( FSaleAccountSettingGroup, '' ) AS '销售视图.科目设置组',
	                                            isnull( FSaleGeneralProjectCategoryGroup, '' ) AS '销售视图.普通项目类别组',
	                                            isnull( FSaleProjectCategoryGroup, '' ) AS '销售视图.项目类别组',
	                                            isnull( FSaleAvailabilityCheck, '' ) AS '销售视图.可用性检查',
	                                            isnull( FSaleOutfitGroup, '' ) AS '销售视图.装载组',
	                                            isnull( FSaleOldMaterialCode, '' ) AS '销售视图.旧物料号',
	                                            isnull( FStorageConditions, '' ) AS '仓储视图.存储条件',
	                                            isnull( FStorageBatchManage, '' ) AS '仓储视图.批次管理',
	                                            isnull( FStorageMaxStoragePeriod, '' ) AS '仓储视图.最大存储期间',
	                                            isnull( FStorageTimeUnit, '' ) AS '仓储视图.时间单位',
	                                            isnull( FStorageMinSurplusShelfLife, '' ) AS '仓储视图.最小剩余货架寿命',
	                                            isnull( FStorageTotalShelfLife, '' ) AS '仓储视图.总货架寿命',
	                                            isnull( FStorageSLEDCode, '' ) AS '仓储视图.SLED期间标识',
	                                            isnull( FMRP1Type, '' ) AS 'MRP1.MRP类型',
	                                            isnull( FMRP1Controller, '' ) AS 'MRP1.MRP控制者',
	                                            isnull( FMRP1BatchSize, '' ) AS 'MRP1.批量大小',
	                                            isnull( FMRP1MinBatchSize, '' ) AS 'MRP1.最小批量大小',
	                                            isnull( FMRP1MaxBatchSize, '' ) AS 'MRP1.最大批量大小',
	                                            isnull( FMRP1Group, '' ) AS 'MRP1.MRP组',
	                                            isnull( FMRP1RoundValue, '' ) AS 'MRP1.舍入值',
	                                            isnull( FMRP1ProductType, '' ) AS 'MRP1.产品分类',
	                                            isnull( FMRP1CustomerCode, '' ) AS 'MRP1.客户代码',
	                                            isnull( FMRP1SizeMaterial, '' ) AS 'MRP1.大小料',
	                                            isnull( FMRP1SmallMaterialStandard, '' ) AS 'MRP1.小料标准（小于）',
	                                            isnull( FMRP2PurchaseType, '' ) AS 'MRP2.采购类型',
	                                            isnull( FMRP2PlanMarginalCode, '' ) AS 'MRP2.计划边际码',
	                                            isnull( FMRP2SpecialProcurement, '' ) AS 'MRP2.特殊采购类',
	                                            isnull( FMRP2Recoil, '' ) AS 'MRP2.反冲',
	                                            isnull( FMRP2SelfProductTime, '' ) AS 'MRP2.自制生产时间',
	                                            isnull( FMRP2PlannDeliveryTime, '' ) AS 'MRP2.计划交货时间',
	                                            isnull( FMRP2ReceiveProcessTime, '' ) AS 'MRP2.收货处理时间',
	                                            isnull( FMRP2SafeStock, '' ) AS 'MRP2.安全库存',
	                                            isnull( FMRP2DeliveryInventoryPlace, '' ) AS 'MRP2.发货库存地点',
	                                            isnull( FMRP2ExternalStoragePlace, '' ) AS 'MRP2.外部采购仓储地点',
	                                            isnull( FMRP3PolicyGroup, '' ) AS 'MRP3.策略组',
	                                            isnull( FMRP3ConsumePattern, '' ) AS 'MRP3.消耗模式',
	                                            isnull( FMRP3ForwardConsumePeriod, '' ) AS 'MRP3.向前消耗期间',
	                                            isnull( FMRP3ReverseConsumePeriod, '' ) AS 'MRP3.逆向消耗期',
	                                            isnull( FMRP3BlendMRP, '' ) AS 'MRP3.混合MRP',
	                                            isnull( FMRP3AvailabilityCheck, '' ) AS 'MRP3.可用性检查',
	                                            isnull( FMRP4AloneOrFocus, '' ) AS 'MRP3.单独或集中',
	                                            isnull( FPlanProductPlanParam, '' ) AS '工作计划视图.生产计划参数文件',
	                                            isnull( FPlanUnlimitedOverDelivery, '' ) AS '工作计划视图.无限制过量交货',
	                                            isnull( FPlanUnderDeliveryTolerance, '' ) AS '工作计划视图.不足交货允差',
	                                            isnull( FPlanOverDeliveryTolerance, '' ) AS '工作计划视图.过度交货允差',
	                                            isnull( FPlanDeliverCompany, '' ) AS '工作计划视图.发货单位',
	                                            isnull( FPlanDeliverCompanyCount, '' ) AS '工作计划视图.发货单位数量',
	                                            isnull( FPlanBaseCompanyCount, '' ) AS '工作计划视图.发货基本单位数量',
	                                            isnull( FQualityType1, '' ) AS '质检视图.检验类型1',
	                                            isnull( FQualityType2, '' ) AS '质检视图.检验类型2',
	                                            isnull( FQualityType3, '' ) AS '质检视图.检验类型3',
	                                            isnull( FQualityType4, '' ) AS '质检视图.检验类型4',
	                                            isnull( FQualityType5, '' ) AS '质检视图.检验类型5',
	                                            isnull( FQualityType6, '' ) AS '质检视图.检验类型6',
	                                            isnull( FAccountPriceControl, '' ) AS '会计视图.价格控制',
	                                            isnull( FAccountPriceDetermine, '' ) AS '会计视图.价格确定',
	                                            isnull( FAccountPriceUnit, '' ) AS '会计视图.价格单位',
	                                            isnull( FAccountAccessType, '' ) AS '会计视图.评估分类',
	                                            isnull( FAccountSaleOrderInventory, '' ) AS '会计视图.VC: 销售订单库存',
	                                            isnull( FAccountStandardPrice, '' ) AS '会计视图.标准价格',
	                                            isnull( FAccountProfitCenter, '' ) AS '会计视图.利润中心',
	                                            isnull( FAccountCostAccountBatch, '' ) AS '会计视图.成本核算批量' 
                                            FROM(
                                            SELECT
	                                            isnull( b.FName, '' ) AS 'FTypeName1',
	                                            isnull( c.FName, '' ) AS 'FTypeName2',
	                                            isnull( FSAPCode, '' ) AS 'FCode',
	                                            isnull( FSAPDescription, '' ) AS 'FName',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FDesc',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FVersionCode',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FFactoryCode',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FSupplyCode',
	                                            isnull( FBaseMaterialGroup, '' ) AS 'FGroupCode',
	                                            isnull( FBaseWeightUnit, '' ) AS 'FBaseUnit',
	                                            isnull( FCraftExplain, '' ) AS 'FCraftDesc',
                                                d.FName AS 'FtypeName',
	                                            a.*
                                            FROM
	                                            TFS_MaterialInfo AS a
                                                LEFT JOIN TFS_MaterialType AS d ON a.FType=d.FID
	                                            LEFT JOIN TFS_MaterialType AS b ON a.FTypeID1= b.FID
	                                            LEFT JOIN TFS_MaterialType AS C ON a.FTypeID2= b.FID 
                                         )a;");
            DataTable data = db.Ado.GetDataTable(strSql);
            return data;
        }

        public DataTable GetMaterialInfoSAPALL()
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = string.Format(@"	
                                            SELECT
 	                                             isnull( FName, '' ) AS '物料名称',
	                                            isnull( FDesc, '' ) AS '物料简介',
	                                            isnull(  REPLACE ( FType , FType , FtypeName ), '' ) AS '物料类型',
	                                            isnull( FCode, '' ) AS '物料编码',
	                                            isnull( FTestCode, '' ) AS '试验号',
	                                            isnull( FVersionCode, '' ) AS '配方内码',
	                                            isnull( FFactoryCode, '' ) AS '工厂代码',
	                                            isnull( FSupplyCode, '' ) AS '物料供应标识',
	                                            isnull( FGroupCode, '' ) AS '组编号',
	                                            isnull( FBaseUnit, '' ) AS '基本计量单位',
	                                            isnull( FMaterialGroup, '' ) AS '物料组',
	                                            isnull( FStoreHouse, '' ) AS '总仓地址',
	                                            isnull( FWorkCenter, '' ) AS '工作中心',
	                                            isnull( FCraftDesc, '' ) AS '工艺描述',
	                                            isnull( FCraftExplain, '' ) AS '工艺说明',
	                                            isnull( FLineHouse, '' ) AS '线边仓',
	                                            isnull( FFixedLoss, '' ) AS '固定损耗',
	                                            isnull( FOrganizeIndustryField, '' ) AS '组织级别.行业领域',
	                                            isnull( FOrganizeMaterialType, '' ) AS '组织级别.物料类型',
	                                            isnull( FOrganizeFactory, '' ) AS '组织级别.工厂',
	                                            isnull( FOrganizeInventoryLocation, '' ) AS '组织级别.库存地点',
	                                            isnull( FOrganizeSalesOrganize, '' ) AS '组织级别.销售组织',
	                                            isnull( FOrganizeDistributionChannel, '' ) AS '组织级别.分销渠道',
	                                            isnull( FBaseMaterialCode, '' ) AS '基本视图.物料编号',
	                                            isnull( FBaseTestCode, '' ) AS '基本视图.试验号',
	                                            isnull( FBaseBasicMeter, '' ) AS '基本视图.基本计量',
	                                            isnull( FBaseMaterialDesc, '' ) AS '基本视图.物料描述',
	                                            isnull( FBaseMaterialGroup, '' ) AS '基本视图.物料组',
	                                            isnull( FBaseSpecification, '' ) AS '基本视图.大小/量纲(规格)',
	                                            isnull( FBaseMaterialText, '' ) AS '基本视图.物料长文本',
	                                            isnull( FBaseIdentifier, '' ) AS '基本视图.标识符:固体/液体',
	                                            isnull( FBaseVolumeUnit, '' ) AS '基本视图.体积单位',
	                                            isnull( FBaseGrossWeight, '' ) AS '基本视图.毛重',
	                                            isnull( FBaseNetWeight, '' ) AS '基本视图.净重',
	                                            isnull( FBaseWeightUnit, '' ) AS '基本视图.重量单位',
	                                            isnull( FBaseBusinessVolume, '' ) AS '基本视图.业务量',
	                                            isnull( FBaseFameCode, '' ) AS '基本视图.fame号',
	                                            isnull( FPurchaseGroup, '' ) AS '采购视图.采购组',
	                                            isnull( FPurchaseCompany, '' ) AS '采购视图.采购单位',
	                                            isnull( FPurchaseCompanyCount, '' ) AS '采购视图.采购单位数量',
	                                            isnull( FPurchaseBaseCompanyCount, '' ) AS '采购视图.采购基本单位数量',
	                                            isnull( FPurchaseValueCode, '' ) AS '采购视图.采购价值码',
	                                            isnull( FPurchaseFactorySpecificStatus, '' ) AS '采购视图.工厂特定状态',
	                                            isnull( FPurchaseAutoOrder, '' ) AS '采购视图.自动采购单标识',
	                                            isnull( FPurchaseGoodsSource, '' ) AS '采购视图.货源清单',
	                                            isnull( FTypeCategoryType, '' ) AS '分类视图.类别种类',
	                                            isnull( FTypeType, '' ) AS '分类视图.类别',
	                                            isnull( FSaleDeliveryFactory, '' ) AS '销售视图.交货工厂',
	                                            isnull( FSaleTaxType, '' ) AS '销售视图.税金分类',
	                                            isnull( FSaleMaterialStatisticsGroup, '' ) AS '销售视图.物料统计组',
	                                            isnull( FSaleSalesCompany, '' ) AS '销售视图.销售单位',
	                                            isnull( FSaleBaseCompanyCount, '' ) AS '销售视图.基本单位数量',
	                                            isnull( FSaleSalesCompanyCount, '' ) AS '销售视图.销售单位数量',
	                                            isnull( FSaleAccountSettingGroup, '' ) AS '销售视图.科目设置组',
	                                            isnull( FSaleGeneralProjectCategoryGroup, '' ) AS '销售视图.普通项目类别组',
	                                            isnull( FSaleProjectCategoryGroup, '' ) AS '销售视图.项目类别组',
	                                            isnull( FSaleAvailabilityCheck, '' ) AS '销售视图.可用性检查',
	                                            isnull( FSaleOutfitGroup, '' ) AS '销售视图.装载组',
	                                            isnull( FSaleOldMaterialCode, '' ) AS '销售视图.旧物料号',
	                                            isnull( FStorageConditions, '' ) AS '仓储视图.存储条件',
	                                            isnull( FStorageBatchManage, '' ) AS '仓储视图.批次管理',
	                                            isnull( FStorageMaxStoragePeriod, '' ) AS '仓储视图.最大存储期间',
	                                            isnull( FStorageTimeUnit, '' ) AS '仓储视图.时间单位',
	                                            isnull( FStorageMinSurplusShelfLife, '' ) AS '仓储视图.最小剩余货架寿命',
	                                            isnull( FStorageTotalShelfLife, '' ) AS '仓储视图.总货架寿命',
	                                            isnull( FStorageSLEDCode, '' ) AS '仓储视图.SLED期间标识',
	                                            isnull( FMRP1Type, '' ) AS 'MRP1.MRP类型',
	                                            isnull( FMRP1Controller, '' ) AS 'MRP1.MRP控制者',
	                                            isnull( FMRP1BatchSize, '' ) AS 'MRP1.批量大小',
	                                            isnull( FMRP1MinBatchSize, '' ) AS 'MRP1.最小批量大小',
	                                            isnull( FMRP1MaxBatchSize, '' ) AS 'MRP1.最大批量大小',
	                                            isnull( FMRP1Group, '' ) AS 'MRP1.MRP组',
	                                            isnull( FMRP1RoundValue, '' ) AS 'MRP1.舍入值',
	                                            isnull( FMRP1ProductType, '' ) AS 'MRP1.产品分类',
	                                            isnull( FMRP1CustomerCode, '' ) AS 'MRP1.客户代码',
	                                            isnull( FMRP1SizeMaterial, '' ) AS 'MRP1.大小料',
	                                            isnull( FMRP1SmallMaterialStandard, '' ) AS 'MRP1.小料标准（小于）',
	                                            isnull( FMRP2PurchaseType, '' ) AS 'MRP2.采购类型',
	                                            isnull( FMRP2PlanMarginalCode, '' ) AS 'MRP2.计划边际码',
	                                            isnull( FMRP2SpecialProcurement, '' ) AS 'MRP2.特殊采购类',
	                                            isnull( FMRP2Recoil, '' ) AS 'MRP2.反冲',
	                                            isnull( FMRP2SelfProductTime, '' ) AS 'MRP2.自制生产时间',
	                                            isnull( FMRP2PlannDeliveryTime, '' ) AS 'MRP2.计划交货时间',
	                                            isnull( FMRP2ReceiveProcessTime, '' ) AS 'MRP2.收货处理时间',
	                                            isnull( FMRP2SafeStock, '' ) AS 'MRP2.安全库存',
	                                            isnull( FMRP2DeliveryInventoryPlace, '' ) AS 'MRP2.发货库存地点',
	                                            isnull( FMRP2ExternalStoragePlace, '' ) AS 'MRP2.外部采购仓储地点',
	                                            isnull( FMRP3PolicyGroup, '' ) AS 'MRP3.策略组',
	                                            isnull( FMRP3ConsumePattern, '' ) AS 'MRP3.消耗模式',
	                                            isnull( FMRP3ForwardConsumePeriod, '' ) AS 'MRP3.向前消耗期间',
	                                            isnull( FMRP3ReverseConsumePeriod, '' ) AS 'MRP3.逆向消耗期',
	                                            isnull( FMRP3BlendMRP, '' ) AS 'MRP3.混合MRP',
	                                            isnull( FMRP3AvailabilityCheck, '' ) AS 'MRP3.可用性检查',
	                                            isnull( FMRP4AloneOrFocus, '' ) AS 'MRP3.单独或集中',
	                                            isnull( FPlanProductPlanParam, '' ) AS '工作计划视图.生产计划参数文件',
	                                            isnull( FPlanUnlimitedOverDelivery, '' ) AS '工作计划视图.无限制过量交货',
	                                            isnull( FPlanUnderDeliveryTolerance, '' ) AS '工作计划视图.不足交货允差',
	                                            isnull( FPlanOverDeliveryTolerance, '' ) AS '工作计划视图.过度交货允差',
	                                            isnull( FPlanDeliverCompany, '' ) AS '工作计划视图.发货单位',
	                                            isnull( FPlanDeliverCompanyCount, '' ) AS '工作计划视图.发货单位数量',
	                                            isnull( FPlanBaseCompanyCount, '' ) AS '工作计划视图.发货基本单位数量',
	                                            isnull( FQualityType1, '' ) AS '质检视图.检验类型1',
	                                            isnull( FQualityType2, '' ) AS '质检视图.检验类型2',
	                                            isnull( FQualityType3, '' ) AS '质检视图.检验类型3',
	                                            isnull( FQualityType4, '' ) AS '质检视图.检验类型4',
	                                            isnull( FQualityType5, '' ) AS '质检视图.检验类型5',
	                                            isnull( FQualityType6, '' ) AS '质检视图.检验类型6',
	                                            isnull( FAccountPriceControl, '' ) AS '会计视图.价格控制',
	                                            isnull( FAccountPriceDetermine, '' ) AS '会计视图.价格确定',
	                                            isnull( FAccountPriceUnit, '' ) AS '会计视图.价格单位',
	                                            isnull( FAccountAccessType, '' ) AS '会计视图.评估分类',
	                                            isnull( FAccountSaleOrderInventory, '' ) AS '会计视图.VC: 销售订单库存',
	                                            isnull( FAccountStandardPrice, '' ) AS '会计视图.标准价格',
	                                            isnull( FAccountProfitCenter, '' ) AS '会计视图.利润中心',
	                                            isnull( FAccountCostAccountBatch, '' ) AS '会计视图.成本核算批量' 
	                                            
                                            FROM(
                                            SELECT
	                                            isnull( b.FName, '' ) AS 'FTypeName1',
	                                            isnull( c.FName, '' ) AS 'FTypeName2',
	                                            isnull( FSAPCode, '' ) AS 'FCode',
	                                            isnull( FSAPDescription, '' ) AS 'FName',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FDesc',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FVersionCode',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FFactoryCode',
	                                            isnull( FBaseMaterialDesc, '' ) AS 'FSupplyCode',
	                                            isnull( FBaseMaterialGroup, '' ) AS 'FGroupCode',
	                                            isnull( FBaseWeightUnit, '' ) AS 'FBaseUnit',
	                                            isnull( FCraftExplain, '' ) AS 'FCraftDesc',
                                                d.FName AS 'FtypeName',
	                                            a.*
                                            FROM
	                                            TFS_MaterialInfo AS a
                                                LEFT JOIN TFS_MaterialType AS d ON a.FType=d.FID
	                                            LEFT JOIN TFS_MaterialType AS b ON a.FTypeID1= b.FID
	                                            LEFT JOIN TFS_MaterialType AS C ON a.FTypeID2= b.FID 
                                            )a;");
            DataTable data = db.Ado.GetDataTable(strSql);
            return data;
        }

        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>

        public static List<T> TableToListModel<T>(DataTable dt) where T : new()
        {
            // 定义集合    
            List<T> ts = new List<T>();

            // 获得此模型的类型   
            Type type = typeof(T);
            string tempName = "";

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性      
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;  // 检查DataTable是否包含此列    

                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter      
                        if (!pi.CanWrite) continue;

                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }

        public int ExecSql(string sql) 
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            return db.Ado.ExecuteCommand(sql);
        }

        public List<TFS_Material> GetMaterialByFName(string fname)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_Material> mainsList = db.Queryable<TFS_Material>().Where(s => s.FDeleted != (int)Constant.DeleteCode.已删除 && s.FName.Equals(fname)).ToList();

            return mainsList;
        }

        public int InsertMaterial(TFS_Material material)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            return db.Insertable(material).IgnoreColumns(true).ExecuteReturnIdentity();
        }


        public List<TFS_MaterialInfo> GetMaterialInfoList() 
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            return db.Queryable<TFS_MaterialInfo>().Where(s => s.FType == 1).ToList();
        }
    }
}