using FactorySystemCommon;
using FactorySystemModel.EnumModel;
using FactorySystemModel.RequestModel;
using FactorySystemModel.ResponseModel;
using FactorySystemModel.SqlSugarModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using static FactorySystemModel.EnumModel.Constant;

namespace FactorySystemBll
{
    public class MaterialTeamworkBll
    {
        /// <summary>
        /// 获取路线列表
        /// </summary>
        public List<MaterialTeamworkRow> GetList(MaterialTeamworkQuery mtq, out int totalNumber)
        {
            totalNumber = 0;
            var db = AppSettingsHelper.GetSqlSugar();
            return db.Queryable<TFS_FMaterialTeamwork, TUser, TFS_Factory>((a, b, c) => new JoinQueryInfos(JoinType.Left, a.FAddUser == b.FID, JoinType.Left, a.FCreateFactoryID == c.FID))
                // 事项状态
                .WhereIF(mtq.FState > 0 && mtq.FState != 99, a => a.FState == mtq.FState)
                // 物料号
                .WhereIF(!string.IsNullOrEmpty(mtq.FMaterialCode), a => a.FMaterialCode.Equals(mtq.FMaterialCode))
                // 类型
                .WhereIF(mtq.FTeamworkType > 0, a => a.FTeamworkType == mtq.FTeamworkType)
                // 发起时间
                .WhereIF(mtq.FDateRange != null && mtq.FDateRange[0] != "",a => a.FAddDate >= DateTime.Parse(mtq.FDateRange[0]))
                .WhereIF(mtq.FDateRange != null && mtq.FDateRange[1] != "", a => a.FAddDate <= DateTime.Parse(mtq.FDateRange[1]))
                // 责任人
                //.WhereIF(mtq.FUserID != null, (a, b) => (',' + a.FUserID + ',').Contains(',' + mtq.FUserID + ',') || a.FAddUser.Equals(mtq.FUserID))
                //// 协同
                //.WhereIF(mtq.FMaterialTeamID > 0, (a, b) => a.FMaterialTeamID == mtq.FMaterialTeamID).OrderBy((a, b) => a.FID, OrderByType.Desc)
                .Select<MaterialTeamworkRow>("a.* ,c.FName as FCreateFactoryName, b.FName as FAddUserName").OrderBy((a) => a.FID, OrderByType.Desc)
                .ToPageList(mtq.FPageIndex, mtq.FPageSize, ref totalNumber);
        }

        /// <summary>
        /// 获取视图编辑列
        /// </summary>
        public List<Dictionary<string, object>> GetColumns()
        {
            List<TFS_ViewFieldInfo> fieldList = AppSettingsHelper.GetSqlSugar().Queryable<TFS_ViewFieldInfo>()
                .Where(it => it.FType == (int)Constant.ViewType.成品视图 || it.FType == (int)Constant.ViewType.物料主表)
                .OrderBy(it => it.FType, OrderByType.Desc)
                .OrderBy(it => it.FOrder)
                .ToList();
            List<Dictionary<string, object>> dicList = new List<Dictionary<string, object>>();
            foreach (var field in fieldList)
            {
                Dictionary<string, object> dic = new Dictionary<string, object> { { "id", field.FID } };
                string[] fArr = field.FField.Split('.');
                dic.Add("key", fArr.Last());
                dic.Add("table", fArr.First());
                string[] nArr = field.FName.Split('.');
                dic.Add("title", nArr.Last());
                dic.Add("category", nArr.First());
                dic.Add("width", field.FWidth);
                dic.Add("align", field.FAlign);
                dic.Add("dataType", field.FDataType);
                if (field.FName.Equals("基本视图.大小/量纲(规格)") || field.FName.Equals("基本视图.毛重") || field.FName.Equals("基本视图.净重"))
                {
                    dic.Add("fieldType", 7);
                }
                else
                {
                    dic.Add("fieldType", field.FType);
                }
                dicList.Add(dic);
            }
            return dicList;
        }

        public string GetViewColumns()
        {
            string cols = "";
            string sql = "SELECT COLUMN_NAME FROM information_schema.columns where table_name = 'TFS_ViewMaterial'";
            var db = AppSettingsHelper.GetSqlSugar();

            DataTable table = db.Ado.GetDataTable(sql);

            foreach (DataRow row in table.Rows)
            {
                cols = cols + row[0].ToString() + ",";
            }

            return cols;
        }

        /// <summary>
        /// 获取视图
        /// </summary>
        public List<Dictionary<string, object>> GetMaterialViewsByTeamId(int teamId, int teamworkType, int teamType, int currUserId, bool byFactory, out List<int> materialId)
        {
            TUser currUser = null;
            if (byFactory == true) currUser = BaseBll.GetTempModel<TUser>(currUserId, "FFactoryID");
            var db = AppSettingsHelper.GetSqlSugar();

            List<Dictionary<string, object>> viewList = new List<Dictionary<string, object>>();

            if (teamworkType == 2)
            {
                viewList = db.Queryable<TFS_ViewMaterial, TFS_Material>((a, b) =>
                new JoinQueryInfos(JoinType.Inner, a.FMaterialID == b.FID))
                .Where((a, b) => a.FMdfMaterialTeamID == teamId)
                .Where((a, b) => a.FTeamType == teamType)
                //.WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                .Select<object>("distinct a.*,b.FTypeID1,b.FTypeID2,b.FK3Code,b.FK3Name,b.FK3ShortCode,b.FTestCode,b.FRelationCode,b.FRelationName,b.FSAPCode,b.FSAPDescription,b.FMaterialGroup,b.FMaterialType,b.FCustomerCode,b.FStoreHouse," +
                "b.FBomEntry,b.FLineHouse,b.FProductDesc,b.FWorkCenter,b.FCraftExplain,b.FIidentifier,b.FGuaranteePeriod,b.FBStorageConditions,b.FSafetyStock,b.FTriggerRatio,b.FMinAmount,b.FMaxAmount,b.FYield,b.FFixedLoss,b.FTheoryYield," +
                "b.FQualityTest1,b.FQualityTest2").ToDictionaryList();
            }
            else
            {
                viewList = db.Queryable<TFS_ViewMaterial, TFS_Material>((a, b) =>
                new JoinQueryInfos(JoinType.Inner, a.FMaterialID == b.FID))
                .Where((a, b) => a.FTeamID == teamId)
                .Where((a, b) => a.FTeamType == teamType)
                //.WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                .Select<object>("distinct a.*,b.FTypeID1,b.FTypeID2,b.FK3Code,b.FK3Name,b.FK3ShortCode,b.FTestCode,b.FRelationCode,b.FRelationName,b.FSAPCode,b.FSAPDescription,b.FMaterialGroup,b.FMaterialType,b.FCustomerCode,b.FStoreHouse," +
                "b.FBomEntry,b.FLineHouse,b.FProductDesc,b.FWorkCenter,b.FCraftExplain,b.FIidentifier,b.FGuaranteePeriod,b.FBStorageConditions,b.FSafetyStock,b.FTriggerRatio,b.FMinAmount,b.FMaxAmount,b.FYield,b.FFixedLoss,b.FTheoryYield," +
                "b.FQualityTest1,b.FQualityTest2").ToDictionaryList();
            }            

            materialId = viewList.GroupBy(s => s["FMaterialID"]).Select(s => int.Parse(s.Key.ToString())).ToList();

            return viewList;
        }

        /// <summary>
        /// 根据模式和物料获取视图
        /// </summary>
        public TFS_ViewMaterial GetMaterialViewsByFactoryAndMaterial(int factoryId, int materialId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            TFS_ViewMaterial view = db.Queryable<TFS_ViewMaterial>().Where(s => s.FMaterialID == materialId && s.FFactoryID == factoryId).First();

            return view;
        }

        /// <summary>
        /// 根据物料获取基本信息
        /// </summary>
        public List<TFS_MaterialInfo> GetMaterialInfoList(List<int> materialIds, int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_MaterialInfo> infoList = db.Queryable<TFS_MaterialInfo>().Where(s => materialIds.Contains(s.FDataID) && s.FType == 2).ToList();
            if (infoList.Count != materialIds.Count)
            {
                materialIds = materialIds.Where(s => infoList.Find(f => f.FDataID == s) == null).ToList();
                foreach (int materialId in materialIds)
                {
                    TFS_Material temp = db.Queryable<TFS_Material>().Where(s => s.FID == materialId).First();
                    TFS_MaterialInfo info = new TFS_MaterialInfo()
                    {
                        FType = 2,
                        FDataID = materialId,
                        FAddUser = userId,
                        FMaterialGroup = temp.FMaterialGroup,
                        FMaterialType = temp.FMaterialType
                    };
                    db.Insertable(info).IgnoreColumns(true).ExecuteCommand();
                    infoList.Add(info);
                }
            }

            return infoList;
        }

        /// <summary>
        /// 根据物料分类集合信息
        /// </summary>
        public object GetMaterialTypeList()
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<TFS_MaterialType>().Where(s => s.FDeleted != 1 && s.FState == 1)
                .OrderBy("FDepth,FID").Select<dynamic>("FID,FName,FID FValue,FDepth,FParentID").ToList();
        }

        public int InsertMaterialView(TFS_ViewMaterial view)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            return db.Insertable(view).IgnoreColumns(true).ExecuteReturnIdentity();
        }

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

        public int UpdateMaterial(TFS_Material material)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            return db.Updateable(material).IgnoreColumns(true).Where("FID").ExecuteCommand();
        }

        public int UpdateMaterialViewById(List<Dictionary<string, object>> viewList, int userId, int teamId, int teamworkType)
        {
            int result = 0;

            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            MaterialTypeBll materialTypeBll = new MaterialTypeBll();
            if (viewList != null && viewList.Count > 0)
            {
                for(int i = 0; i < viewList.Count; i++)
                {
                    viewList[i]["FEditUser"] = userId;
                    viewList[i]["FEditDate"] = DateTime.Now;
                }

                string sqlWhere = "";

                if (teamworkType == 2)
                {
                    sqlWhere = string.Format("FMdfMaterialTeamId={0} and FTeamType={1}", teamId, 1);
                }
                else
                {
                    sqlWhere = string.Format("FTeamID={0} and FTeamType={1}", teamId, 1);
                }

                for (int i = 0; i < viewList.Count; i++)
                {

                    if (!viewList[i].ContainsKey("FK3Code") && viewList[i].ContainsKey("FSAPCode"))
                    {
                        viewList[i].Add("FK3Code", viewList[i]["FSAPCode"]);
                    }
                    else if(viewList[i].ContainsKey("FK3Code") && !viewList[i].ContainsKey("FSAPCode"))
                    {
                        viewList[i].Add("FSAPCode", viewList[i]["FK3Code"]);
                    }

                    if (!viewList[i].ContainsKey("FK3Name") && viewList[i].ContainsKey("FSAPDescription"))
                    {
                        viewList[i].Add("FK3Name", viewList[i]["FSAPDescription"]);
                    }
                    else if (viewList[i].ContainsKey("FK3Name") && !viewList[i].ContainsKey("FSAPDescription"))
                    {
                        viewList[i].Add("FSAPDescription", viewList[i]["FK3Name"]);
                    }

                    // 设置成成品视图
                    if (viewList[i]["FMRP1ProductType"].ToString() == "10")
                    {
                        if (viewList[i].ContainsKey("FViewType"))
                        {
                            viewList[i]["FViewType"] = (int)Constant.ViewType.成品视图;
                        }
                        else
                        {
                            viewList[i].Add("FViewType", (int)Constant.ViewType.成品视图);
                        }
                    }

                    // 设置成半成品视图
                    if (viewList[i]["FMRP1ProductType"].ToString() == "20")
                    {
                        if (viewList[i].ContainsKey("FViewType"))
                        {
                            viewList[i]["FViewType"] = (int)Constant.ViewType.半成品视图;
                        }
                        else
                        {
                            viewList[i].Add("FViewType", (int)Constant.ViewType.半成品视图);
                        }
                    }

                    //设置成中间品视图或香基视图，判断是否等于中间品
                    if (viewList[i]["FMRP1ProductType"].ToString() == "30")
                    {
                        TFS_MaterialType materialType = materialTypeBll.GetMaterialTypeByID(int.Parse(viewList[i]["FTypeID2"].ToString())).LastOrDefault();
                        if (materialType.FName.Contains("香基"))
                        {
                            if (viewList[i].ContainsKey("FViewType"))
                            {
                                viewList[i]["FViewType"] = (int)Constant.ViewType.香基视图;
                            }
                            else
                            {
                                viewList[i].Add("FViewType", (int)Constant.ViewType.香基视图);
                            }
                        }
                        else
                        {
                            if (viewList[i].ContainsKey("FViewType"))
                            {
                                viewList[i]["FViewType"] = (int)Constant.ViewType.中间品视图;
                            }
                            else
                            {
                                viewList[i].Add("FViewType", (int)Constant.ViewType.中间品视图);
                            }
                        }
                    }

                    // 设置成原料视图
                    if (viewList[i]["FMRP1ProductType"].ToString() == "40")
                    {
                        if (viewList[i].ContainsKey("FViewType"))
                        {
                            viewList[i]["FViewType"] = (int)Constant.ViewType.原料视图;
                        }
                        else
                        {
                            viewList[i].Add("FViewType", (int)Constant.ViewType.原料视图);
                        }
                    }

                    viewList[i].Remove("FTypeID2");

                    // 更新视图
                    db.Updateable(viewList[i]).AS("TFS_ViewMaterial").WhereColumns("FMaterialID").Where(sqlWhere).ExecuteCommand();

                    int.TryParse(viewList[i]["FMRP1ProductType"].ToString(), out result);
                }

                UnionModifyData(viewList, "TFS_ViewMaterial", teamId, teamworkType, db, "FMaterialID");
            }

            return result;
        }

        public string UpdateMaterialById(List<Dictionary<string, object>> materialList, int userId, int teamId, int teamworkType)
        {
            string result = "";

            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();

            if (materialList != null && materialList.Count > 0)
            {
                for (int i = 0; i < materialList.Count; i++)
                {
                    materialList[i]["FID"] = materialList[i]["FMaterialID"];
                    materialList[i]["FEditUser"] = userId;
                    materialList[i]["FEditDate"] = DateTime.Now;
                    materialList[i].Remove("FMaterialID");
                    if (materialList[i].TryGetValue("FK3Code", out object k3Code))
                    {
                        if (materialList[i].ContainsKey("FK3ShortCode"))
                        {
                            materialList[i]["FK3ShortCode"] = k3Code.ToString().Split('.').Last();
                        }
                        else
                        {
                            materialList[i].Add("FK3ShortCode", k3Code.ToString().Split('.').Last());
                        }
                    }
                    db.Updateable(materialList[i]).AS("TFS_Material").WhereColumns("FID").ExecuteCommand();

                    if (materialList[i].ContainsKey("FCode"))
                    {
                        result = materialList[i]["FCode"].ToString();
                    }
                }
                
                UnionModifyData(materialList, "TFS_Material", teamId, teamworkType, db);
            }

            return result;
        }

        public int UpdateMaterialInfoById(List<Dictionary<string, object>> infoList, int userId, int teamId, int teamworkType)
        {
            int result = 0;

            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();

            if (infoList != null && infoList.Count > 0)
            {
                for (int i = 0; i < infoList.Count; i++)
                {
                    infoList[i]["FDataID"] = infoList[i]["FMaterialID"];
                    infoList[i]["FEditUser"] = userId;
                    infoList[i]["FEditDate"] = DateTime.Now;
                    infoList[i].Remove("FMaterialID");
                    infoList[i].Add("FType", 2);

                    result += db.Updateable(infoList[i]).IgnoreColumns(true).AS("TFS_MaterialInfo").WhereColumns("FDataID", "FType").ExecuteCommand();
                }

                result += UnionModifyData(infoList, "TFS_MaterialInfo", teamId, teamworkType, db, "FDataID");
            }

            return result;
        }

        public int UpdateMaterialView(TFS_ViewMaterial view)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            return db.Updateable(view).IgnoreColumns(true).WhereColumns("FID").ExecuteCommand();
        }

        private int UnionModifyData(List<Dictionary<string, object>> dataList, string srcTable, int teamId, int teamworkType, SqlSugarClient db = null, string colName = "FID")
        {
            int result = 0;
            if (dataList != null && dataList.Count > 0)
            {
                if (db == null) db = AppSettingsHelper.GetSqlSugar();
                List<TFS_UnionModify> unionList = db.Queryable<TFS_UnionModify>().Where(s => s.FDeleted != 1 && s.FTableOriginal == srcTable).ToList();
                if (unionList.Count > 0)
                {
                    List<string> sqlList = new List<string>() { "update {0} set {0}.{1}={2}.{3} from {0} left join {2} on {4} where {2}.{5}='{6}' {7}" };
                    foreach (Dictionary<string, object> data in dataList)
                    {
                        foreach (TFS_UnionModify union in unionList)
                        {
                            if (data.TryGetValue(union.FColumnOriginal, out object srcVal))
                            {
                                string sqlWhere = "";
                                if (union.FTableTarget == "TFS_ViewMaterial" || union.FTableOriginal == "TFS_ViewMaterial")
                                {
                                    if (teamworkType == 2)
                                    {
                                        sqlWhere = " and TFS_ViewMaterial.FMdfMaterialTeamID=" + teamId;
                                    }
                                    else
                                    {
                                        sqlWhere = " and TFS_ViewMaterial.FTeamID=" + teamId;
                                    }                                    
                                }
                                sqlList.Add(string.Format(sqlList[0], union.FTableTarget, union.FColumnTarget,
                                    union.FTableOriginal, union.FColumnOriginal, union.FUnionCondition, colName,
                                    data[colName], sqlWhere));
                            }
                        }
                    }
                    sqlList.RemoveAt(0);
                    if (sqlList.Count > 0)
                    {
                        string updateSql = string.Join(";", sqlList);
                        try { 
                            result = db.Ado.ExecuteCommand(updateSql);
                        }
                        catch (Exception ex) {
                        }
                    }
                }
            }
            return result;
        }

        public int CloseMaterialTeamwork(int teamId, int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_FMaterialTeamwork> teamworkList = db.Queryable<TFS_FMaterialTeamwork>().Where(s => s.FID == teamId && s.FState == 1).ToList();
            int result = 0;

            if (teamworkList != null && teamworkList.Count > 0)
            {
                TFS_FMaterialTeamwork fmt = teamworkList[0];

                fmt.FState = 2;
                fmt.FEditUser = userId;
                fmt.FEditDate = DateTime.Now;

                result = db.Updateable(fmt).IgnoreColumns(true).WhereColumns("FID").ExecuteCommand();
            }

            return result;
        }

        public TFS_FMaterialTeamwork GetMaterialTeamworkById(int teamId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            TFS_FMaterialTeamwork teamwork = null;
            List<TFS_FMaterialTeamwork> teamworkList = db.Queryable<TFS_FMaterialTeamwork>().Where(s => s.FID == teamId && s.FState == 1).ToList();

            if (teamworkList != null && teamworkList.Count > 0)
            {
                teamwork = teamworkList[0];
            }

            return teamwork;
        }

        public int UpdateMaterialTeamwork(TFS_FMaterialTeamwork teamwork)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            int result = 0;
            result = db.Updateable(teamwork).IgnoreColumns(true).WhereColumns("FID").ExecuteCommand();

            return result;
        }

        public List<TFS_Material> SearchMaterialsByFactory(string materialName, int pageNumber, int pageSize, out int totalNumber)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            totalNumber = 0;

            List<TFS_Material> materialList = db.Queryable<TFS_Material>()
                     .WhereIF(!string.IsNullOrEmpty(materialName.Trim()), a => a.FName.Contains(materialName) || a.FCode.Contains(materialName))
                     .OrderBy((a) => a.FID, OrderByType.Desc)
                     .ToPageList(pageNumber, pageSize, ref totalNumber);

            return materialList;
        }

        public List<TFS_ViewMaterial> GetViewMaterialByTeamId(int teamworkId, int teamworkType)
        {
            List<TFS_ViewMaterial> viewList = null;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();

            if (teamworkType == 1)
            {
                viewList = db.Queryable<TFS_ViewMaterial>().Where(s => s.FTeamID == teamworkId && s.FTeamType == 1).ToList();
            }
            else if (teamworkType == 3) 
            {
                viewList = db.Queryable<TFS_ViewMaterial>().Where(s => s.FHalfMaterialTeamID == teamworkId).ToList();
            }
            else
            {
                viewList = db.Queryable<TFS_ViewMaterial>().Where(s => s.FMdfMaterialTeamID == teamworkId && s.FTeamType == 1).ToList();
            }

            return viewList;
        }

        public List<object> GetViewPower(int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();

            List<object> powers = db.Queryable<TRole_Right, FPower>((a, b) => new JoinQueryInfos(
                JoinType.Full, b.FRole.Equals(a.FRoleID.ToString())
                ))
                .Where((a, b) => b.FUserID.Equals(userId.ToString()))
                .Where((a, b) => a.FType == 3)
                .Select<object>("a.FRoleID, a.FType, a.FFunctionID, b.FFactoryID").Distinct()
                .ToList();

            return powers;
        }

        public DataTable GetViewMaterialSAP(string teamworkId, string teamworkType)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = @"
                SELECT
                    isnull(replace(FOrganizeIndustryField,'(空)',''), '') AS '行业领域
（Industry Sector）',
                    isnull(replace(FOrganizeMaterialType,'(空)',''), '') AS '物料类型
(Material Type)',
                    isnull(replace(FOrganizeFactory,'(空)',''), '') AS '工厂
(Plant)',
                    isnull(replace(FOrganizeInventoryLocation,'(空)',''), '') AS '库存地点
(Stock Location)',
                    isnull(replace(FOrganizeSalesOrganize,'(空)',''), '') AS '销售组织
(Sales Organization)',
                    isnull(replace(FOrganizeDistributionChannel,'(空)',''), '') AS '分销渠道
(distribution Channel',
                    isnull(replace(FBaseMaterialCode,'(空)',''), '') AS '物料编号
(Material NO.)',
                    isnull(replace(FBaseTestCode,'(空)',''), '') AS '试验号
(Test NO.)',
                    isnull(replace(FBaseBasicMeter,'(空)',''), '') AS '基本计量
(Base Unit of Measure)',
                    isnull(replace(FBaseMaterialDesc,'(空)',''), '') AS '物料描述
（Material Description）',
                    isnull(replace(FBaseMaterialGroup,'(空)',''), '') AS '物料组
(Material Group)',
                    isnull(replace(FBaseSpecification,'(空)',''), '') AS '大小/量纲（规格）
(Specifications)',
                    isnull(replace(FBaseMaterialText,'(空)',''), '') AS '物料长文本
(Basic Data Text)',
                    isnull(replace(FBaseIdentifier,'(空)',''), '') AS '实验室\办公室（标识符:固体/液体/乳化）
(In bulk/liquid)',
                    isnull(replace(FBaseVolumeUnit,'(空)',''), '') AS '体积单位
(Volume Unit)',
                    isnull(replace(FBaseGrossWeight,'(空)',''), '') AS '毛重
(Gross weight)',
                    isnull(replace(FBaseNetWeight,'(空)',''), '') AS '净重
(Net weight)',
                    isnull(replace(FBaseWeightUnit,'(空)',''), '') AS '重量单位
(Weight unit)',
                    isnull(replace(FBaseFameCode,'(空)',''), '') AS '生产备忘录（fame号）',
                    isnull(replace(FBaseBusinessVolume,'(空)',''), '') AS '业务量
(Volume)',
                    isnull(replace(FPurchaseGroup,'(空)',''), '') AS '采购组
(Purchasing Group)',
                    isnull(replace(FPurchaseCompany,'(空)',''), '') AS '采购单位
(Order Unit)',
                    isnull(replace(FPurchaseCompanyCount,'(空)',''), '') AS '采购单位数量
(Quantity Conversion of procument)',
                    isnull(replace(FPurchaseBaseCompanyCount,'(空)',''), '') AS '基本单位数量
(Quantity Conversion of basic unit of measure)',
                    isnull(replace(FPurchaseValueCode,'(空)',''), '') AS '采购价值码
(Purchasing value key)',
                    isnull(replace(FPurchaseFactorySpecificStatus,'(空)',''), '') AS '工厂特定状态
(Plant-Specific Material Status)',
                    isnull(replace(FPurchaseAutoOrder,'(空)',''), '') AS '自动采购订单
（automatic purchase order allowed）',
                    isnull(replace(FPurchaseGoodsSource,'(空)',''), '') AS '货源清单
（Source list requirement）',
                    isnull(replace(FTypeCategoryType,'(空)',''), '') AS '类别种类
（Class Type）',
                    isnull(replace(FTypeType,'(空)',''), '') AS '类别
（Class）',
                    isnull(replace(FSaleDeliveryFactory,'(空)',''), '') AS '交货工厂
(Delivering Plant)',
                    isnull(replace(FSaleTaxType,'(空)',''), '') AS '税金分类
(Tax classification material)',
                    isnull(replace(FSaleMaterialStatisticsGroup,'(空)',''), '') AS '物料统计组
(Material statistics group)',
                    isnull(replace(FSaleSalesCompany,'(空)',''), '') AS '销售单位
(Sales unit)',
                    isnull(replace(FSaleBaseCompanyCount,'(空)',''), '') AS '基本单位数量
(Quantity Conversion of basic unit of measure)',
                    isnull(replace(FSaleSalesCompanyCount,'(空)',''), '') AS '销售单位数量
(Quantity Conversion of Sales)',
                    isnull(replace(FSaleAccountSettingGroup,'(空)',''), '') AS '科目设置组
(Account Assignment Group for Material)',
                    isnull(replace(FSaleGeneralProjectCategoryGroup,'(空)',''), '') AS '普通项目类别组
(General item category group)',
                    isnull(replace(FSaleProjectCategoryGroup,'(空)',''), '') AS '项目类别组
(Item Category Group)',
                    isnull(replace(FSaleAvailabilityCheck,'(空)',''), '') AS '可用性检查
(Availability check)',
                    isnull(replace(FSaleOutfitGroup,'(空)',''), '') AS '装载组
(Loading Group)',
                    isnull(replace(FSaleOldMaterialCode,'(空)',''), '') AS '旧物料号
（old material number）',
                    isnull(replace(FStorageConditions,'(空)',''), '') AS '存储条件
（Storage conditions）',
                    isnull(replace(FStorageBatchManage,'(空)',''), '') AS '批次管理
（Batch Management Requirement Indicator）',
                    isnull(replace(FStorageMaxStoragePeriod,'(空)',''), '') AS '最大存储期间
（Maximum Storage Period）',
                    isnull(replace(FStorageTimeUnit,'(空)',''), '') AS '时间单位
（Time unit）',
                    isnull(replace(FStorageMinSurplusShelfLife,'(空)',''), '') AS '最小剩余货架寿命(Minimum Remaining Shelf Life)',
                    isnull(replace(FStorageTotalShelfLife,'(空)',''), '') AS '总货架寿命
(Total shelf life)',
                    isnull(replace(FStorageSLEDCode,'(空)',''), '') AS 'SLED期间标识
(Period Indicator for Shelf Life Expiration Date)',
                    isnull(replace(FMRP1Type,'(空)',''), '') AS 'MRP类型
(MRP Type)',
                    isnull(replace(FMRP1ReorderLocation,'(空)',''), '') AS '再订货点',
                    isnull(replace(FMRP1RegularBatchSize,'(空)',''), '') AS '固定批量大小',
                    isnull(replace(FMRP1MaxInventorySize,'(空)',''), '') AS '最大库存水平',
                    isnull(replace(FMRP1Controller,'(空)',''), '') AS 'MRP
控制者
MRP Controller',
                    isnull(replace(FMRP1BatchSize,'(空)',''), '') AS '批量大小
Lot Sizing Procedure within Materials Planning',
                    isnull(replace(FMRP1MinBatchSize,'(空)',''), '') AS '最小批
量大小
Maximum Lot Size',
                    isnull(replace(FMRP1MaxBatchSize,'(空)',''), '') AS '最大批
量大小
Minimum Lot Size',
                    isnull(replace(FMRP1Group,'(空)',''), '') AS 'MRP组
MRP Group',
                    isnull(replace(FMRP1RoundValue,'(空)',''), '') AS '舍入值
Rounding value for purchase order quantity',
                    isnull(replace(FMRP1ProductType,'(空)',''), '') AS '产品分类
Product classification',
                    isnull(replace(FMRP1CustomerCode,'(空)',''), '') AS '客户代码',
                    isnull(replace(FMRP1SizeMaterial,'(空)',''), '') AS '大小料',
                    isnull(replace(FMRP1IgnoreLack,'(空)',''), '') AS '不计算缺料',
                    isnull(replace(FMRP1laminated,'(空)',''), '') AS '压膜',
                    isnull(replace(FMRP1SafeStock,'(空)',''), '') AS '安全库存带小样',
                    isnull(replace(FMRP1RequireCount,'(空)',''), '') AS '需求计算不考虑前置物料库存',
                    isnull(replace(FMRP1SmallMaterialStandard,'(空)',''), '') AS ' 小料标准（小于）',
                    isnull(replace(FMRP2PurchaseType,'(空)',''), '') AS '采购类型
Procurement Type',
                    isnull(replace(FMRP2PlanMarginalCode,'(空)',''), '') AS '计划
边际码
SchedMargin key',
                    isnull(replace(FMRP2SpecialProcurement,'(空)',''), '') AS '特殊
采购类
Special procurement',
                    isnull(replace(FMRP2Recoil,'(空)',''), '') AS '反冲
Backflush',
                    isnull(replace(FMRP2SelfProductTime,'(空)',''), '') AS '自制
生产时间
In-house production time',
                    isnull(replace(FMRP2PlannDeliveryTime,'(空)',''), '') AS '计划交
货时间
Planned Delivery Time in Days',
                    isnull(replace(FMRP2ReceiveProcessTime,'(空)',''), '') AS '收货处
理时间
Goods receipt processing time in days',
                    isnull(replace(FMRP2SafeStock,'(空)',''), '') AS '安全库存
Safety Stock',
                    isnull(replace(FMRP2DeliveryInventoryPlace,'(空)',''), '') AS '发货库
存地点
Issue Storage Location',
                    isnull(replace(FMRP2ExternalStoragePlace,'(空)',''), '') AS '外部采购
仓储地点
Default storage location for external procurement',
                    isnull(replace(FMRP3PolicyGroup,'(空)',''), '') AS '策略组
Strategy Group',
                    isnull(replace(FMRP3ConsumePattern,'(空)',''), '') AS '消耗模式
Consumption Mode',
                    isnull(replace(FMRP3ForwardConsumePeriod,'(空)',''), '') AS '向前消
耗期间
（Consumption period: forward）',
                    isnull(replace(FMRP3ReverseConsumePeriod,'(空)',''), '') AS '逆向
消耗期
（Consumption period: backward）',
                    isnull(replace(FMRP3BlendMRP,'(空)',''), '') AS '混合MRP
Mixed MRP indicator',
                    isnull(replace(FMRP3AvailabilityCheck,'(空)',''), '') AS '可用性检查

Availability check',
                    isnull(replace(FMRP4AloneOrFocus,'(空)',''), '') AS '单独或集中
Individual requirements/Collective requirements',
                    isnull(replace(FMRP4DiscontinuousIidentifier,'(空)',''), '') AS '非连续标识',
                    isnull(replace(FMRP4EffectivePeriod,'(空)',''), '') AS '生效期',
                    isnull(replace(FMRP4FollowMaterial,'(空)',''), '') AS '后续的物料',
                    isnull(replace(FPlanProductPlanParam,'(空)',''), '') AS '生产计划参数文件
Production Scheduling Profile',
                    isnull(replace(FPlanUnlimitedOverDelivery,'(空)',''), '') AS '无限制过
量交货
（Indicator: Unlimited Overdelivery Allowed）',
                    isnull(replace(FPlanUnderDeliveryTolerance,'(空)',''), '') AS '不足交
货允差
Underdelivery tolerance limit',
                    isnull(replace(FPlanOverDeliveryTolerance,'(空)',''), '') AS '过度交
货允差
Overdelivery tolerance limit',
                    isnull(replace(FPlanDeliverCompany,'(空)',''), '') AS '发货单位
Unit of issue',
                    isnull(replace(FPlanDeliverCompanyCount,'(空)',''), '') AS '发货单位数量
(Quantity Conversion of Delivery)',
                    isnull(replace(FPlanBaseCompanyCount,'(空)',''), '') AS '基本单位数量
(Quantity Conversion of basic unit of measure)',
                    isnull(replace(FQualityType1,'(空)',''), '') AS '检验类型1
Inspection Type 1',
                    isnull(replace(FQualityType2,'(空)',''), '') AS '检验类型2
Inspection Type 2',
                    isnull(replace(FQualityType3,'(空)',''), '') AS '检验类型3
Inspection Type 3',
                    isnull(replace(FQualityType4,'(空)',''), '') AS '检验类型4
Inspection Type 4',
                    isnull(replace(FQualityType5,'(空)',''), '') AS '检验类型5
Inspection Type 5',
                    isnull(replace(FQualityType6,'(空)',''), '') AS '检验类型6
Inspection Type 6',
                    isnull(replace(FAccountPriceControl,'(空)',''), '') AS '价格控制
(Price control indicator)',
                    isnull(replace(FAccountPriceDetermine,'(空)',''), '') AS '价格确定
(Material Price Determination: Control)',
                    isnull(replace(FAccountPriceUnit,'(空)',''), '') AS '价格单位
(Price Unit)',
                    isnull(replace(FAccountAccessType,'(空)',''), '') AS '评估分类
Valuation Class',
                    isnull(replace(FAccountSaleOrderInventory,'(空)',''), '') AS 'VC: 销售订单库存
Valuation Class for Sales Order Stock',
                    isnull(replace(FAccountStandardPrice,'(空)',''), '') AS '标准价格
Standard Price',
                    isnull(replace(FAccountProfitCenter,'(空)',''), '') AS '利润中心
Profit Center',
                    isnull(replace(FAccountCostAccountBatch,'(空)',''), '') AS '成本核算批量
Lot Size for Product Costing'
                FROM TFS_ViewMaterial";
                
            if ("2".Equals(teamworkType))
            {
                string whereSql = string.Format(" Where FTeamType=1 And FMdfMaterialTeamID={0}", teamworkId);
                strSql = strSql + whereSql;
            }
            else if ("3".Equals(teamworkType)) 
            {
                string whereSql = string.Format(" Where FHalfMaterialTeamID={0}", teamworkId);
                strSql = strSql + whereSql;
            }
            else
            {
                string whereSql = string.Format(" Where FTeamType=1 And FTeamID={0}", teamworkId);
                strSql = strSql + whereSql;
            }

            DataTable data = db.Ado.GetDataTable(strSql);
            return data;
        }

        public DataTable GetViewMaterial(string FID)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = string.Format(@"select 
				iif(m.FTypeID1 is null, '', (select FName from TFS_MaterialType where fid = m.FTypeID1)) as '一级分类',
                iif(m.FTypeID2 is null, '', (select FName from TFS_MaterialType where fid = m.FTypeID2)) as '二级分类',
                isnull(m.FK3Code, '') as 'K3系统代码',
                isnull(m.FK3Name, '') as 'K3系统名称',
                isnull(m.FK3ShortCode, '') as 'K3系统短代码',
                isnull(m.FTestCode, '') as '产品试验号',
                isnull(m.FRelationCode, '') as '关联物料代码',
                isnull(m.FRelationName, '') as '关联物料名称',
                isnull(m.FSAPCode, '') as 'SAP系统代码',
                isnull(m.FSAPDescription, '') as 'SAP系统描述',
                isnull(i.FMaterialGroup, '') as '物料组',
                isnull(i.FMaterialType, '') as '物料主分类',
                isnull(i.FCustomerCode, '') as '客供料标识',
                isnull(i.FStoreHouse, '') as '总仓地址',
                isnull(i.FBomEntry, '') as 'BOM录入情况',
                isnull(i.FLineHouse, '') as '线边仓地址',
                isnull(i.FProductDesc, '') as '产品说明',
                isnull(i.FWorkCenter, '') as '工作中心',
                isnull(i.FCraftExplain, '') as '工艺说明',
                isnull(i.FIidentifier, '') as '标识符',
                isnull(i.FGuaranteePeriod, '') as '保质期',
                isnull(i.FBStorageConditions, '') as '存储条件',
                isnull(i.FSafetyStock, '') as '安全库存',
                isnull(i.FTriggerRatio, '') as '触发比例',
                isnull(i.FMinAmount, '') as '最小量',
                isnull(i.FMaxAmount, '') as '最大量',
                isnull(i.FYield, '') as '得率',
                isnull(i.FFixedLoss, '') as '固损',
                isnull(i.FTheoryYield, '') as '理论得率',
                isnull(i.FQualityTest1, '') as '品质检验',
                isnull(i.FQualityTest2, '') as '品质检验',
                isnull(v.FOrganizeIndustryField, '') as '行业领域
                （Industry Sector）',
                isnull(v.FOrganizeMaterialType, '') as '物料类型
                (Material Type)',
                isnull(v.FOrganizeFactory, '') as '工厂
                (Plant)',
                isnull(v.FOrganizeInventoryLocation, '') as '库存地点
                (Stock Location)',
                isnull(v.FOrganizeSalesOrganize, '') as '销售组织
                (Sales Organization)',
                isnull(v.FOrganizeDistributionChannel, '') as '分销渠道
                (distribution Channel)',
                isnull(v.FBaseMaterialCode, '') as '物料编号
                (Material NO.)',
                isnull(v.FBaseTestCode, '') as '试验号
                (Test NO.)',
                isnull(v.FBaseBasicMeter, '') as '基本计量
                (Base Unit of Measure)',
                isnull(v.FBaseMaterialDesc, '') as '物料描述
                （Material Description）',
                isnull(v.FBaseMaterialGroup, '') as '物料组
                (Material Group)',
                isnull(v.FBaseSpecification, '') as '大小/量纲（规格）
                (Specifications)',
                isnull(v.FBaseMaterialText, '') as '物料长文本
                (Basic Data Text)',
                isnull(v.FBaseIdentifier, '') as '实验室\办公室（标识符:固体/液体/乳化）
                (In bulk/liquid)',
                isnull(v.FBaseVolumeUnit, '') as '体积单位
                (Volume Unit)',
                isnull(v.FBaseGrossWeight, '') as '毛重
                (Gross weight)',
                isnull(v.FBaseNetWeight, '') as '净重
                (Net weight)',
                isnull(v.FBaseWeightUnit, '') as '重量单位
                (Weight unit)',
                isnull(v.FBaseFameCode, '') as '生产备忘录（fame号）',
                isnull(v.FBaseBusinessVolume, '') as '业务量
                (Volume)',
                isnull(v.FPurchaseGroup, '') as '采购组
                (Purchasing Group)',
                isnull(v.FPurchaseCompany, '') as '采购单位
                (Order Unit)',
                isnull(v.FPurchaseCompanyCount, '') as '采购单位数量
                (Quantity Conversion of procument)',
                isnull(v.FPurchaseBaseCompanyCount, '') as '基本单位数量
                (Quantity Conversion of basic unit of measure)',
                isnull(v.FPurchaseValueCode, '') as '采购价值码
                (Purchasing value key)',
                isnull(v.FPurchaseFactorySpecificStatus, '') as '工厂特定状态
                (Plant-Specific Material Status)',
                isnull(v.FPurchaseAutoOrder, '') as '自动采购订单
                （automatic purchase order allowed）',
                isnull(v.FPurchaseGoodsSource, '') as '货源清单
                （Source list requirement）',
                isnull(v.FTypeCategoryType, '') as '类别种类
                （Class Type）',
                isnull(v.FTypeType, '') as '类别
                （Class）',
                isnull(v.FSaleDeliveryFactory, '') as '交货工厂
                (Delivering Plant)',
                isnull(v.FSaleTaxType, '') as '税金分类
                (Tax classification material)',
                isnull(v.FSaleMaterialStatisticsGroup, '') as '物料统计组
                (Material statistics group)',
                isnull(v.FSaleSalesCompany, '') as '销售单位
                (Sales unit)',
                isnull(v.FSaleBaseCompanyCount, '') as '基本单位数量
                (Quantity Conversion of basic unit of measure)',
                isnull(v.FSaleSalesCompanyCount, '') as '销售单位数量
                (Quantity Conversion of Sales)',
                isnull(v.FSaleAccountSettingGroup, '') as '科目设置组
                (Account Assignment Group for Material)',
                isnull(v.FSaleGeneralProjectCategoryGroup, '') as '普通项目类别组
                (General item category group)',
                isnull(v.FSaleProjectCategoryGroup, '') as '项目类别组
                (Item Category Group)',
                isnull(v.FSaleAvailabilityCheck, '') as '可用性检查
                (Availability check)',
                isnull(v.FSaleOutfitGroup, '') as '装载组
                (Loading Group)',
                isnull(v.FSaleOldMaterialCode, '') as '旧物料号
                （old material number）
                ',
                isnull(v.FStorageConditions, '') as '存储条件
                （Storage conditions）',
                isnull(v.FStorageBatchManage, '') as '批次管理
                （Batch Management Requirement Indicator）',
                isnull(v.FStorageMaxStoragePeriod, '') as '最大存储期间
                （Maximum Storage Period）',
                isnull(v.FStorageTimeUnit, '') as '时间单位
                （Time unit）',
                isnull(v.FStorageMinSurplusShelfLife, '') as '最小剩余货架寿命(Minimum Remaining Shelf Life)',
                isnull(v.FStorageTotalShelfLife, '') as '总货架寿命
                (Total shelf life)',
                isnull(v.FStorageSLEDCode, '') as 'SLED期间标识
                (Period Indicator for Shelf Life Expiration Date)',
                isnull(v.FMRP1Type, '') as 'MRP类型
                (MRP Type)',
                isnull(v.FMRP1ReorderLocation, '') as '再订货点',
                isnull(v.FMRP1RegularBatchSize, '') as '固定批量大小',
                isnull(v.FMRP1MaxInventorySize, '') as '最大库存水平',
                isnull(v.FMRP1Controller, '') as 'MRP
                控制者
                MRP Controller',
                isnull(v.FMRP1BatchSize, '') as '批量大小
                Lot Sizing Procedure within Materials Planning',
                isnull(v.FMRP1MinBatchSize, '') as '最小批
                量大小
                Maximum Lot Size',
                isnull(v.FMRP1MaxBatchSize, '') as '最大批
                量大小
                Minimum Lot Size',
                isnull(v.FMRP1Group, '') as 'MRP组
                MRP Group',
                isnull(v.FMRP1RoundValue, '') as '舍入值
                Rounding value for purchase order quantity',
                isnull(v.FMRP1ProductType, '') as '产品分类
                Product classification',
                isnull(v.FMRP1CustomerCode, '') as '客户代码',
                isnull(v.FMRP1SizeMaterial, '') as '大小料',
                isnull(v.FMRP1IgnoreLack, '') as '不计算缺料     ',
                isnull(v.FMRP1laminated, '') as '压膜',
                isnull(v.FMRP1SafeStock, '') as '安全库存带小样',
                isnull(v.FMRP1RequireCount, '') as '需求计算不考虑前置物料库存',
                isnull(v.FMRP1SmallMaterialStandard, '') as ' 小料标准（小于）',
                isnull(v.FMRP2PurchaseType, '') as '采购类型
                Procurement Type',
                isnull(v.FMRP2PlanMarginalCode, '') as '计划
                边际码
                SchedMargin key',
                isnull(v.FMRP2SpecialProcurement, '') as '特殊
                采购类
                Special procurement',
                isnull(v.FMRP2Recoil, '') as '反冲
                Backflush',
                isnull(v.FMRP2SelfProductTime, '') as '自制
                生产时间
                In-house production time',
                isnull(v.FMRP2PlannDeliveryTime, '') as '计划交
                货时间
                Planned Delivery Time in Days',
                isnull(v.FMRP2ReceiveProcessTime, '') as '收货处
                理时间
                Goods receipt processing time in days',
                isnull(v.FMRP2SafeStock, '') as '安全库存
                Safety Stock',
                isnull(v.FMRP2DeliveryInventoryPlace, '') as '发货库
                存地点
                Issue Storage Location',
                isnull(v.FMRP2ExternalStoragePlace, '') as '外部采购
                仓储地点
                Default storage location for external procurement',
                isnull(v.FMRP3PolicyGroup, '') as '策略组
                Strategy Group',
                isnull(v.FMRP3ConsumePattern, '') as '消耗模式
                Consumption Mode',
                isnull(v.FMRP3ForwardConsumePeriod, '') as '向前消
                耗期间
                （Consumption period: forward）',
                isnull(v.FMRP3ReverseConsumePeriod, '') as '逆向
                消耗期
                （Consumption period: backward）',
                isnull(v.FMRP3BlendMRP, '') as '混合MRP
                Mixed MRP indicator',
                isnull(v.FMRP3AvailabilityCheck, '') as '可用性检查

                Availability check',
                isnull(v.FMRP4AloneOrFocus, '') as '单独或集中
                Individual requirements/Collective requirements',
                isnull(v.FMRP4DiscontinuousIidentifier, '') as '非连续标识',
                isnull(v.FMRP4EffectivePeriod, '') as '生效期',
                isnull(v.FMRP4FollowMaterial, '') as '后续的物料',
                isnull(v.FPlanProductPlanParam, '') as '生产计划参数文件
                Production Scheduling Profile',
                isnull(v.FPlanUnlimitedOverDelivery, '') as '无限制过
                量交货
                （Indicator: Unlimited Overdelivery Allowed）',
                isnull(v.FPlanUnderDeliveryTolerance, '') as '不足交
                货允差
                Underdelivery tolerance limit',
                isnull(v.FPlanOverDeliveryTolerance, '') as '过度交
                货允差
                Overdelivery tolerance limit',
                isnull(v.FPlanDeliverCompany, '') as '发货单位
                Unit of issue',
                isnull(v.FPlanDeliverCompanyCount, '') as '发货单位数量
                (Quantity Conversion of Delivery)',
                isnull(v.FPlanBaseCompanyCount, '') as '基本单位数量
                (Quantity Conversion of basic unit of measure)',
                isnull(v.FQualityType1, '') as '检验类型1
                Inspection Type 1',
                isnull(v.FQualityType2, '') as '检验类型2
                Inspection Type 2',
                isnull(v.FQualityType3, '') as '检验类型3
                Inspection Type 3',
                isnull(v.FQualityType4, '') as '检验类型4
                Inspection Type 4',
                isnull(v.FQualityType5, '') as '检验类型5
                Inspection Type 5',
                isnull(v.FQualityType6, '') as '检验类型6
                Inspection Type 6',
                isnull(v.FAccountPriceControl, '') as '价格控制
                (Price control indicator)',
                isnull(v.FAccountPriceDetermine, '') as '价格确定
                (Material Price Determination: Control)',
                isnull(v.FAccountPriceUnit, '') as '价格单位
                (Price Unit)',
                isnull(v.FAccountAccessType, '') as '评估分类
                Valuation Class',
                isnull(v.FAccountSaleOrderInventory, '') as 'VC: 销售订单库存
                Valuation Class for Sales Order Stock',
                isnull(v.FAccountStandardPrice, '') as '标准价格
                Standard Price',
                isnull(v.FAccountProfitCenter, '') as '利润中心
                Profit Center',
                isnull(v.FAccountCostAccountBatch, '') as '成本核算批量
                Lot Size for Product Costing'
            from
	            TFS_ViewMaterial v
            left join TFS_Material m on
	            v.FMaterialID = m.FID
            left join TFS_MaterialInfo i on
	            v.FMaterialID = i.FDataID
            where
	            i.FType = 2
	            and v.FMaterialID in ({0})", FID);

            DataTable data = db.Ado.GetDataTable(strSql);
            return data;
        }
    }
}
