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;
        }

        /// <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("FViewType={0} and FMdfMaterialTeamId={1} and FTeamType={2}", 0, teamId, 1);
                }
                else
                {
                    sqlWhere = string.Format("FViewType={0} and FTeamID={1} and FTeamType={2}", 0, teamId, 1);
                }

                for (int i = 0; i < viewList.Count; i++)
                {
                    // 设置成成品视图
                    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");

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

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

            return result;
        }

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

            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());
                        }
                    }
                    result += db.Updateable(materialList[i]).AS("TFS_Material").WhereColumns("FID").ExecuteCommand();
                }
                
                result += 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]).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 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))
                     .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
            {
                viewList = db.Queryable<TFS_ViewMaterial>().Where(s => s.FMdfMaterialTeamID == teamworkId && s.FTeamType == 1).ToList();
            }

            return viewList;
        }

        public DataTable GetViewMaterialSAP(string teamworkId, string teamworkType)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = @"
                SELECT
                    isnull(FMaterialId, '') AS '物料ID',
                    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 'MRP4.单独或集中',
                    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 '会计视图.成本核算批量',
                    isnull(FExtraQuantity, '') AS '额外增加字段：配方视图、组装bom视图的基本数量对应PLM配方下载BOM中用量',
                    isnull(FMRP1ReorderLocation, '') AS 'MRP1.再订货点',
                    isnull(FMRP1RegularBatchSize, '') AS 'MRP1.固定批量大小',
                    isnull(FMRP1MaxInventorySize, '') AS 'MRP1.最大库存水平',
                    isnull(FMRP1IgnoreLack, '') AS 'MRP1.不计算缺料',
                    isnull(FMRP1laminated, '') AS 'MRP1.压膜',
                    isnull(FMRP1SafeStock, '') AS 'MRP1.安全库存带小样',
                    isnull(FMRP1RequireCount, '') AS 'MRP1.需求计算不考虑前置物料库存',
                    isnull(FMRP4DiscontinuousIidentifier, '') AS 'MRP4.非连续标识',
                    isnull(FMRP4EffectivePeriod, '') AS 'MRP4.生效期',
                    isnull(FMRP4FollowMaterial, '') AS 'MRP4.后续的物料'
                FROM TFS_ViewMaterial";
                
            if ("2".Equals(teamworkType))
            {
                string whereSql = string.Format(" Where FTeamType=1 And FMdfMaterialTeamID={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
 	                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 
                WHERE
	                FDataId = {0})a;", FID);

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