using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Reflection;
using System.Web.UI.WebControls;
using FactorySystemCommon;
using FactorySystemModel.EnumModel;
using FactorySystemModel.SqlSugarModel;
using SqlSugar;

namespace FactorySystemBll
{
    public class ViewBll
    {
        /// <summary>
        /// 根据协同ID获取物料视图
        /// </summary>
        public List<Dictionary<string, object>> GetListByTeamId(int teamId, int viewType, int currUserId, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, bool byFactory = true)
        {
            TUser currUser = null;
            FGuaranteePeriod = "";
            FStorageConditions = "";
            if (byFactory == true) currUser = BaseBll.GetTempModel<TUser>(currUserId, "FFactoryID, FFactoryList");
            var db = AppSettingsHelper.GetSqlSugar();

            /**
            * 20230414 需求变更
            * 新增物料分类视图获取逻辑
            * 物料分类的viewType=10，此时，取所有下载的bomList中的视图，a.FViewType in (2,3,4,5)
            * 分别对应半成品视图、中间品视图、香基视图、原料视图
            * 此处的viewType来自TBasicCode中FType=33时，的FRemark字段
            * **/
            List<Dictionary<string, object>> viewList = new List<Dictionary<string, object>>();
            List<int> viewTypes = new List<int> { 2, 3, 4, 5 };
            if (viewTypes.Contains(viewType))
            {
                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 == 0)
                    //.WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                    .WhereIF(currUser != null, (a, b) => currUser.FFactoryList.Contains(a.FFactoryID.ToString()))
                    .WhereIF(viewType > 0, (a, b) => a.FViewType == viewType)
                    .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 if (viewType == 10)
            {
                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 == 0)
                    //.WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                    .WhereIF(currUser != null, (a, b) => currUser.FFactoryList.Contains(a.FFactoryID.ToString()))
                    .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();

                TFS_FTeamwork teamWork = db.Queryable<TFS_FTeamwork>().Where(s => s.FID == teamId).First();
                TFS_PackageMain packAge = db.Queryable<TFS_PackageMain>().Where(s => s.FCode == teamWork.FPackCode).First();

                if (packAge != null)
                {
                    viewList[0].Remove("FBaseGrossWeight");
                    viewList[0].Add("FBaseGrossWeight", packAge.FGrossWeight);
                    viewList[0].Remove("FBaseNetWeight");
                    viewList[0].Add("FBaseNetWeight", packAge.FNetWeight);
                    viewList[0].Remove("FBaseSpecification");
                    viewList[0].Add("FBaseSpecification", packAge.FSpecs);
                    viewList[0].Add("HalfCode", teamWork.FMaterialHalfIDs);
                }
                var FBaseMaterialDesc = viewList.GroupBy(s => s["FBaseMaterialDesc"]).Select(s => s.Key).ToList();

                if (FBaseMaterialDesc.Count > 0)
                {
                    viewList[0].Add("HalfDesc", FBaseMaterialDesc[0]);
                }
            }

            if (viewType == 1)
            {
                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 == 0)
                //.WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                .WhereIF(currUser != null, (a, b) => currUser.FFactoryList.Contains(a.FFactoryID.ToString()))
                .WhereIF(viewType > 0, (a, b) => a.FViewType == 1)
                .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();
                List<TFS_MaterialInfo> Minfo = GetMaterialInfoList(viewList.GroupBy(s => s["FMaterialID"]).Select(s => int.Parse(s.Key.ToString())).ToList(), "", "", currUserId);
                if (Minfo.Count > 0)
                {
                    FGuaranteePeriod = Minfo[0].FGuaranteePeriod;
                    FStorageConditions = Minfo[0].FStorageConditions;
                }

                TFS_FTeamwork teamWork = db.Queryable<TFS_FTeamwork>().Where(s => s.FID == teamId).First();
                TFS_PackageMain packAge = db.Queryable<TFS_PackageMain>().Where(s => s.FCode == teamWork.FPackCode).First();

                if (packAge != null)
                {
                    viewList[0].Remove("FBaseGrossWeight");
                    viewList[0].Add("FBaseGrossWeight", packAge.FGrossWeight);
                    viewList[0].Remove("FBaseNetWeight");
                    viewList[0].Add("FBaseNetWeight", packAge.FNetWeight);
                    viewList[0].Remove("FBaseSpecification");
                    viewList[0].Add("FBaseSpecification", packAge.FSpecs);
                    viewList[0].Add("HalfCode", teamWork.FMaterialHalfIDs);
                }
                var FBaseMaterialDesc = viewList.GroupBy(s => s["FBaseMaterialDesc"]).Select(s => s.Key).ToList();

                if (FBaseMaterialDesc.Count > 0)
                {
                    viewList[0].Add("HalfDesc", FBaseMaterialDesc[0]);
                }
            }
            materialId = viewList.GroupBy(s => s["FMaterialID"]).Select(s => int.Parse(s.Key.ToString())).ToList();
            return viewList;
        }



        /// <summary>
        /// 根据协同ID获取物料视图
        /// </summary>
        public List<Dictionary<string, object>> GetHalfMaterialListByTeamId(int teamId, int viewType, int currUserId, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, bool byFactory = true)
        {
            TUser currUser = null;
            FGuaranteePeriod = "";
            FStorageConditions = "";
            if (byFactory == true) currUser = BaseBll.GetTempModel<TUser>(currUserId, "FFactoryID");
            var db = AppSettingsHelper.GetSqlSugar();

            /**
            * 20230414 需求变更
            * 新增物料分类视图获取逻辑
            * 物料分类的viewType=10，此时，取所有下载的bomList中的视图，a.FViewType in (2,3,4,5)
            * 分别对应半成品视图、中间品视图、香基视图、原料视图
            * 此处的viewType来自TBasicCode中FType=33时，的FRemark字段
            * **/
            List<Dictionary<string, object>> viewList = new List<Dictionary<string, object>>();
            List<int> viewTypes = new List<int> { 2, 3, 4, 5 };
            if (viewTypes.Contains(viewType))
            {
                viewList = db.Queryable<TFS_ViewMaterial, TFS_Material>((a, b) =>
                    new JoinQueryInfos(JoinType.Inner, a.FMaterialID == b.FID))
                   .Where((a, b) => a.FHalfMaterialTeamID == teamId)
                   .WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                   .WhereIF(viewType > 0, (a, b) => a.FViewType == viewType)
                   .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 if (viewType == 10)
            {
                viewList = db.Queryable<TFS_ViewMaterial, TFS_Material>((a, b) =>
                    new JoinQueryInfos(JoinType.Inner, a.FMaterialID == b.FID))
                   .Where((a, b) => a.FTeamID == teamId)
                   .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();

                TFS_HalfMaterialFTeamwork teamWork = db.Queryable<TFS_HalfMaterialFTeamwork>().Where(s => s.FID == teamId).First();
                TFS_PackageMain packAge = db.Queryable<TFS_PackageMain>().Where(s => s.FCode == teamWork.FPackCode).First();

                if (packAge != null)
                {
                    viewList[0].Remove("FBaseGrossWeight");
                    viewList[0].Add("FBaseGrossWeight", packAge.FGrossWeight);
                    viewList[0].Remove("FBaseNetWeight");
                    viewList[0].Add("FBaseNetWeight", packAge.FNetWeight);
                    viewList[0].Remove("FBaseSpecification");
                    viewList[0].Add("FBaseSpecification", packAge.FSpecs);
                    viewList[0].Add("HalfCode", teamWork.FMaterialHalfIDs);
                }
                var FBaseMaterialDesc = viewList.GroupBy(s => s["FBaseMaterialDesc"]).Select(s => s.Key).ToList();

                if (FBaseMaterialDesc.Count > 0)
                {
                    viewList[0].Add("HalfDesc", FBaseMaterialDesc[0]);
                }
            }

            if (viewType == 1)
            {
                viewList = db.Queryable<TFS_ViewMaterial, TFS_Material>((a, b) =>
                 new JoinQueryInfos(JoinType.Inner, a.FMaterialID == b.FID))
               .Where((a, b) => a.FHalfMaterialTeamID == teamId)
               .WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
               .WhereIF(viewType > 0, (a, b) => a.FViewType == 2)
               .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();
                List<TFS_MaterialInfo> Minfo = GetMaterialInfoList(viewList.GroupBy(s => s["FMaterialID"]).Select(s => int.Parse(s.Key.ToString())).ToList(), "", "", currUserId);
                if (Minfo.Count > 0)
                {
                    FGuaranteePeriod = Minfo[0].FGuaranteePeriod;
                    FStorageConditions = Minfo[0].FStorageConditions;
                }

                TFS_HalfMaterialFTeamwork teamWork = db.Queryable<TFS_HalfMaterialFTeamwork>().Where(s => s.FID == teamId).First();
                TFS_PackageMain packAge = db.Queryable<TFS_PackageMain>().Where(s => s.FCode == teamWork.FPackCode).First();

                if (packAge != null)
                {
                    viewList[0].Remove("FBaseGrossWeight");
                    viewList[0].Add("FBaseGrossWeight", packAge.FGrossWeight);
                    viewList[0].Remove("FBaseNetWeight");
                    viewList[0].Add("FBaseNetWeight", packAge.FNetWeight);
                    viewList[0].Remove("FBaseSpecification");
                    viewList[0].Add("FBaseSpecification", packAge.FSpecs);
                    viewList[0].Add("HalfCode", teamWork.FMaterialHalfIDs);
                }
                var FBaseMaterialDesc = viewList.GroupBy(s => s["FBaseMaterialDesc"]).Select(s => s.Key).ToList();

                if (FBaseMaterialDesc.Count > 0)
                {
                    viewList[0].Add("HalfDesc", FBaseMaterialDesc[0]);
                }
            }
            materialId = viewList.GroupBy(s => s["FMaterialID"]).Select(s => int.Parse(s.Key.ToString())).ToList();
            return viewList;
        }



        /// <summary>
        /// 根据协同ID获取物料视图
        /// </summary>
        public List<Dictionary<string, object>> GetMaterialViewsByTeamId(int teamId, int viewType, int teamType, int currUserId, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, bool byFactory = true)
        {
            TUser currUser = null;
            FGuaranteePeriod = "";
            FStorageConditions = "";
            if (byFactory == true) currUser = BaseBll.GetTempModel<TUser>(currUserId, "FFactoryID, FFactoryList");
            var db = AppSettingsHelper.GetSqlSugar();

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

            if (viewType == 10)
            {
                viewList = db.Queryable<TFS_ViewMaterial, TFS_Material>((a, b) =>
                    new JoinQueryInfos(JoinType.Left, 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)
                   .WhereIF(currUser != null, (a, b) => currUser.FFactoryList.Contains(a.FFactoryID.ToString()))
                   .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.Left, 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)
                   .WhereIF(currUser != null, (a, b) => currUser.FFactoryList.Contains(a.FFactoryID.ToString()))
                   .WhereIF(viewType > 0, (a, b) => a.FViewType == viewType)
                   .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>
        /// 根据协同ID获取物料视图
        /// </summary>
        public List<Dictionary<string, object>> GetListByTeamId2(int teamId, int currUserId, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, bool byFactory = true)
        {
            TUser currUser = null;
            FGuaranteePeriod = "";
            FStorageConditions = "";
            //if (byFactory == true) currUser = BaseBll.GetTempModel<TUser>(currUserId, "FFactoryID");
            var db = AppSettingsHelper.GetSqlSugar();
            List<Dictionary<string, object>> 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 == 0)
                //.WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                .Select<object>("distinct a.*,b.FTypeID1,b.FTypeID2,b.FK3Code,b.FK3Name,b.FK3ShortCode").ToDictionaryList();


            foreach (var item in viewList)
            {
                if (item["FViewType"].ToString() == "1")
                {
                    int viewType = int.Parse(item["FViewType"].ToString());
                    if (viewType == 1)
                    {
                        List<Dictionary<string, object>> viewList1 = 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 == 0)
                        .WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                        .WhereIF(viewType > 0, (a, b) => a.FViewType == 2)
                        .Select<object>("distinct a.*,b.FTypeID1,b.FTypeID2,b.FK3Code,b.FK3Name,b.FK3ShortCode").ToDictionaryList();
                        List<TFS_MaterialInfo> Minfo = GetMaterialInfoList(viewList1.GroupBy(s => s["FMaterialID"]).Select(s => int.Parse(s.Key.ToString())).ToList(), "", "", currUserId);
                        if (Minfo.Count > 0)
                        {
                            FGuaranteePeriod = Minfo[0].FGuaranteePeriod;
                            FStorageConditions = Minfo[0].FStorageConditions;
                        }

                        TFS_FTeamwork teamWork = db.Queryable<TFS_FTeamwork>().Where(s => s.FID == teamId).First();
                        TFS_PackageMain packAge = db.Queryable<TFS_PackageMain>().Where(s => s.FCode == teamWork.FPackCode).First();

                        if (packAge != null)
                        {
                            item.Remove("FBaseGrossWeight");
                            item.Add("FBaseGrossWeight", packAge.FGrossWeight);
                            item.Remove("FBaseNetWeight");
                            item.Add("FBaseNetWeight", packAge.FNetWeight);
                            item.Remove("FBaseSpecification");
                            item.Add("FBaseSpecification", packAge.FSpecs);
                            item.Add("HalfCode", teamWork.FMaterialHalfIDs);
                        }
                        var FBaseMaterialDesc = viewList1.GroupBy(s => s["FBaseMaterialDesc"]).Select(s => s.Key).ToList();

                        if (FBaseMaterialDesc.Count > 0)
                        {
                            viewList[0].Add("HalfDesc", FBaseMaterialDesc[0]);
                        }
                    }
                }
            }
            materialId = viewList.GroupBy(s => s["FMaterialID"]).Select(s => int.Parse(s.Key.ToString())).ToList();
            return viewList;
        }



        /// <summary>
        /// 根据替换物料TeamID获取物料视图
        /// </summary>
        public List<Dictionary<string, object>> GetListByHalfMaterialTeamId(int teamId, int currUserId, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, bool byFactory = true)
        {
            TUser currUser = null;
            FGuaranteePeriod = "";
            FStorageConditions = "";
            //if (byFactory == true) currUser = BaseBll.GetTempModel<TUser>(currUserId, "FFactoryID");
            var db = AppSettingsHelper.GetSqlSugar();
            List<Dictionary<string, object>> viewList = db.Queryable<TFS_ViewMaterial, TFS_Material>((a, b) =>
                 new JoinQueryInfos(JoinType.Inner, a.FMaterialID == b.FID))
                .Where((a, b) => a.FHalfMaterialTeamID == teamId)
                //.WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                .Select<object>("distinct a.*,b.FTypeID1,b.FTypeID2,b.FK3Code,b.FK3Name,b.FK3ShortCode").ToDictionaryList();


            foreach (var item in viewList)
            {
                if (item["FViewType"].ToString() == "1")
                {
                    int viewType = int.Parse(item["FViewType"].ToString());
                    if (viewType == 1)
                    {
                        List<Dictionary<string, object>> viewList1 = db.Queryable<TFS_ViewMaterial, TFS_Material>((a, b) =>
                         new JoinQueryInfos(JoinType.Inner, a.FMaterialID == b.FID))
                       .Where((a, b) => a.FTeamID == teamId)
                       .WhereIF(currUser != null, (a, b) => a.FFactoryID == currUser.FFactoryID)
                        .WhereIF(viewType > 0, (a, b) => a.FViewType == 2)
                       .Select<object>("distinct a.*,b.FTypeID1,b.FTypeID2,b.FK3Code,b.FK3Name,b.FK3ShortCode").ToDictionaryList();
                        List<TFS_MaterialInfo> Minfo = GetMaterialInfoList(viewList1.GroupBy(s => s["FMaterialID"]).Select(s => int.Parse(s.Key.ToString())).ToList(), "", "", currUserId);
                        if (Minfo.Count > 0)
                        {
                            FGuaranteePeriod = Minfo[0].FGuaranteePeriod;
                            FStorageConditions = Minfo[0].FStorageConditions;
                        }

                        TFS_HalfMaterialFTeamwork teamWork = db.Queryable<TFS_HalfMaterialFTeamwork>().Where(s => s.FID == teamId).First();
                        TFS_PackageMain packAge = db.Queryable<TFS_PackageMain>().Where(s => s.FCode == teamWork.FPackCode).First();

                        if (packAge != null)
                        {
                            item.Remove("FBaseGrossWeight");
                            item.Add("FBaseGrossWeight", packAge.FGrossWeight);
                            item.Remove("FBaseNetWeight");
                            item.Add("FBaseNetWeight", packAge.FNetWeight);
                            item.Remove("FBaseSpecification");
                            item.Add("FBaseSpecification", packAge.FSpecs);
                            item.Add("HalfCode", teamWork.FMaterialHalfIDs);
                        }
                        var FBaseMaterialDesc = viewList1.GroupBy(s => s["FBaseMaterialDesc"]).Select(s => s.Key).ToList();

                        if (FBaseMaterialDesc.Count > 0)
                        {
                            viewList[0].Add("HalfDesc", FBaseMaterialDesc[0]);
                        }
                    }
                }
            }
            materialId = viewList.GroupBy(s => s["FMaterialID"]).Select(s => int.Parse(s.Key.ToString())).ToList();
            return viewList;
        }

        /// <summary>
        /// 根据物料获取基本信息
        /// </summary>
        public List<TFS_MaterialInfo> GetMaterialInfoList(List<int> materialIds, string FGuaranteePeriod, string FStorageConditions, 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,
                        FType2 = temp.FTypeID2,
                        FMaterialGroup = temp.FMaterialGroup,
                        FMaterialType = temp.FMaterialType,
                        FTestCode= temp.FTestCode,
                        FBaseTestCode=temp.FTestCode
                    };
                    db.Insertable(info).IgnoreColumns(true).ExecuteCommand();
                }
            }
            if (!FGuaranteePeriod.Equals(""))
            {
                infoList[0].FGuaranteePeriod = FGuaranteePeriod;
            }
            if (!FStorageConditions.Equals(""))
            {
                infoList[0].FStorageConditions = FStorageConditions;
            }
            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();
        }

        /// <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>
        /// <param name="rows"></param>
        public int UpdateBatchById(List<Dictionary<string, object>> rows, int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            foreach (var row in rows)
            {
                db.Updateable(row).AS("TFS_ViewMaterial").WhereColumns("FMaterialID", "FTeamID", "FViewType").AddQueue();
            }
            int result = db.SaveQueues();
            if (!rows[0].ContainsKey("FTeamID") || !int.TryParse(rows[0]["FTeamID"].ToString(), out int teamId)) teamId = -1;
            if (!rows[0].ContainsKey("FViewType") || !int.TryParse(rows[0]["FViewType"].ToString(), out int taskType)) taskType = -1;
            if (teamId > 0 && taskType > 0) result += CheckTaskComplete(db, teamId, taskType, userId);
            return result;
        }

        /// <summary>
        /// 保存视图编辑内容2
        /// </summary>
        public int UpdateBatchById2(List<Dictionary<string, object>> viewList, List<Dictionary<string, object>> materialList,
            List<Dictionary<string, object>> infoList, int teamId, int viewType, int userId)
        {
            int result = 0;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            MaterialTypeBll materialTypeBll = new MaterialTypeBll();
            if (viewList != null && viewList.Count > 0)
            {
                string sqlWhere = string.Format("FViewType={0} and FTeamID={1}", viewType, teamId);
                if (viewType == 10)
                {
                    sqlWhere = string.Format("FViewType in (2, 3, 4, 5) and FTeamID={1}", viewType, teamId);
                }


                for (int i = 0; i < viewList.Count; i++)
                {
                    //判断是否等于中间品
                    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.中间品视图);
                            }
                        }
                    }
                    else 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.成品视图);
                        }
                    }
                    else 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.半成品视图);
                        }
                    }
                    else 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.原料视图);
                        }
                    }

                    if (viewList[i].ContainsKey("FTypeID2")) viewList[i].Remove("FTypeID2");
                    result += db.Updateable(viewList[i]).AS("TFS_ViewMaterial").WhereColumns("FMaterialID").ExecuteCommand();
                }

                result += UnionModifyData(viewList, "TFS_ViewMaterial", teamId, db, "FMaterialID");
            }
            if (materialList != null && materialList.Count > 0)
            {
                for (int i = 0; i < materialList.Count; i++)
                {
                    materialList[i]["FID"] = materialList[i]["FMaterialID"];
                    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, db);
            }
            if (infoList != null && infoList.Count > 0)
            {
                for (int i = 0; i < infoList.Count; i++)
                {
                    infoList[i]["FDataID"] = infoList[i]["FMaterialID"];
                    infoList[i].Remove("FMaterialID");
                    infoList[i].Add("FType", 2);
                    result += db.Updateable(infoList[i]).AS("TFS_MaterialInfo").WhereColumns("FType", "FDataID").ExecuteCommand();
                }
                
                result += UnionModifyData(infoList, "TFS_MaterialInfo", teamId, db, "FDataID");
            }
            result += CheckTaskComplete(db, teamId, viewType, userId);
            return result;
        }

        public int UpdateMaterialViewById(List<Dictionary<string, object>> viewList, List<Dictionary<string, object>> materialList,
            List<Dictionary<string, object>> infoList, int teamId, int viewType, int userId)
        {
            int result = 0;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            if (viewList != null && viewList.Count > 0)
            {
                string sqlWhere = string.Format("FViewType={0} and FTeamID={1}", viewType, teamId);
                result += db.Updateable(viewList).AS("TFS_ViewMaterial").WhereColumns("FMaterialID").Where(sqlWhere).ExecuteCommand();
                result += UnionModifyData(viewList, "TFS_ViewMaterial", teamId, db, "FMaterialID");
            }
            if (materialList != null && materialList.Count > 0)
            {
                for (int i = 0; i < materialList.Count; i++)
                {
                    materialList[i]["FID"] = materialList[i]["FMaterialID"];
                    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).AS("TFS_Material").WhereColumns("FID").ExecuteCommand();
                result += UnionModifyData(materialList, "TFS_Material", teamId, db);
            }
            if (infoList != null && infoList.Count > 0)
            {
                for (int i = 0; i < infoList.Count; i++)
                {
                    infoList[i]["FDataID"] = infoList[i]["FMaterialID"];
                    infoList[i].Remove("FMaterialID");
                    infoList[i].Add("FType", 2);
                }
                result += db.Updateable(infoList).AS("TFS_MaterialInfo").WhereColumns("FType", "FDataID").ExecuteCommand();
                result += UnionModifyData(infoList, "TFS_MaterialInfo", teamId, db, "FDataID");
            }
            return result;
        }

        private int CheckTaskComplete(SqlSugarClient db, int teamId, int taskType, int userId)
        {
            int result = 0;
            //List<string> fields = db.Queryable<TBasicCode, TFS_ViewFieldInfo>((a, b) => new JoinQueryInfos(JoinType.Left, a.F2 == b.FID.ToString()))
            //       .Where((a, b) => a.FType == 40 && b.FType == 1 && a.F1 == taskType.ToString()).Select((a, b) => b.FField).ToList();
            //string okSql = string.Format("select count(1) from TFS_ViewMaterial where FTeamID={0} and FViewType={1} and(", teamId, taskType);
            //okSql += string.Join("='' or ", fields).Replace("TFS_ViewMaterial.", "") + "='')";
            //string okResult = db.Ado.GetString(okSql);
            string okResult = "";
            if (string.IsNullOrEmpty(okResult) || okResult == "0")
            {
                if (taskType != 10)
                {
                    //视图类型+2是事项，除了包材
                    taskType += 2;
                    if (taskType >= (int)Constant.TaskType.组编号申请) taskType = (int)Constant.TaskType.新包材视图;
                }
                else
                {
                    taskType = 15;
                }
                string taskSql = "";

                int proType = -2; string appSql = " and(select count(1) from TFS_Task t where t.FTeamID=a.FTeamID and t.FType in({0}) and t.FState!=2)=0";
                switch (taskType)
                {
                    case 3://成品视图事项:3→成品视图：2
                        proType = 2;
                        break;
                    case 4://新半成品视图:4
                    case 5://新中间品视图:5
                    case 6://新香基视图:6→新半成品/中间品/香基：3
                        proType = 3;
                        appSql = string.Format(appSql, "4,5,6");
                        break;
                    case 7://新原料视图:7→新原料视图:4
                        proType = 4;
                        break;
                    case 15://物料分类视图:15→物料分类视图:0
                        proType = 0;
                        break;
                    case 11://新包材视图:7→新原料视图:8
                        proType = 8;
                        break;
                }
                if (taskType == 15 || proType > 0) taskSql = BaseBll.GetProcessSql(teamId, proType, "F3", 2, string.Format(appSql, taskType));
                taskSql = BaseBll.GetTaskSql(-1, 2, teamId, taskType, -1, string.Format("','+a.FUserID+',' like ',%{0}%,'", userId)) + taskSql;
                result += db.Ado.ExecuteCommand(taskSql);
                TeamworkBll.ChangeTeamProcess(teamId);
            }
            return result;
        }
        /// <summary>
        /// 试验号变更-保存视图编辑内容3
        /// </summary>
        public int UpdateBatchById3(List<Dictionary<string, object>> viewList, List<Dictionary<string, object>> materialList,
            List<Dictionary<string, object>> infoList, int teamId, int viewType, int userId)
        {
            int result = 0;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            MaterialBll materialBll = new MaterialBll();
            MaterialTypeBll materialTypeBll = new MaterialTypeBll();

            if (viewList != null && viewList.Count > 0)
            {

                string sqlWhere = string.Format(" FHalfMaterialTeamID={1}", viewType, teamId);

                //if (viewType == 10)
                //{
                //    sqlWhere = string.Format("FViewType in (2, 3, 4, 5) and FHalfMaterialTeamID={1}", viewType, teamId);
                //}
                for (int i = 0; i < viewList.Count; i++)
                {
                    //判断是否等于中间品
                    if (viewList[i].ContainsKey("FMRP1ProductType") &&viewList[i]["FMRP1ProductType"].ToString() == "30")
                    {
                        TFS_MaterialType materialType = materialTypeBll.GetMaterialTypeByID(int.Parse(materialList[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.中间品视图);
                            }
                        }
                    }
                    else
                    {
                        switch (viewList[i]["FMRP1ProductType"].ToString())
                        {
                            case "10":
                                if (viewList[i].ContainsKey("FViewType"))
                                {
                                    viewList[i]["FViewType"] = (int)Constant.ViewType.成品视图;
                                }
                                else
                                {
                                    viewList[i].Add("FViewType", (int)Constant.ViewType.成品视图);
                                }
                                break;
                            case "20":
                                if (viewList[i].ContainsKey("FViewType"))
                                {
                                    viewList[i]["FViewType"] = (int)Constant.ViewType.半成品视图;
                                }
                                else
                                {
                                    viewList[i].Add("FViewType", (int)Constant.ViewType.半成品视图);
                                }
                                break;
                            case "40":
                                if (viewList[i].ContainsKey("FViewType"))
                                {
                                    viewList[i]["FViewType"] = (int)Constant.ViewType.原料视图;
                                }
                                else
                                {
                                    viewList[i].Add("FViewType", (int)Constant.ViewType.原料视图);
                                }
                                break;
                            default:
                                if (viewList[i].ContainsKey("FViewType"))
                                {
                                    viewList[i]["FViewType"] = -1;
                                }
                                else
                                {
                                    viewList[i].Add("FViewType", -1);
                                }
                                break;
                        }
                    }
                   
                }

                

                result += db.Updateable(viewList).AS("TFS_ViewMaterial").WhereColumns("FMaterialID").Where(sqlWhere).ExecuteCommand();

                result += HalfMaterialUnionModifyData(viewList, "TFS_ViewMaterial", teamId, db, "FMaterialID");
            }
            if (materialList != null && materialList.Count > 0)
            {
                for (int i = 0; i < materialList.Count; i++)
                {
                    materialList[i]["FID"] = materialList[i]["FMaterialID"];
                    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());
                        }
                    }

                    if (materialList[i].ContainsKey("FName"))
                    {
                        materialList[i]["FName"] = viewList[i]["FBaseMaterialDesc"];
                    }
                    else 
                    {
                        materialList[i].Add("FName", viewList[i]["FBaseMaterialDesc"]);
                    }

                    if (materialList[i].ContainsKey("FDesc"))
                    {
                        materialList[i]["FDesc"] = viewList[i]["FBaseMaterialDesc"];
                    }
                    else
                    {
                        materialList[i].Add("FDesc", viewList[i]["FBaseMaterialDesc"]);
                    }


                    if (materialList[i].ContainsKey("FType"))
                    {
                        materialList[i]["FType"] = viewList[i]["FMRP1ProductType"];
                    }
                    else
                    {
                        materialList[i].Add("FType", viewList[i]["FMRP1ProductType"]);
                    }

                    if (materialList[i].ContainsKey("FCode"))
                    {
                        materialList[i]["FCode"] = viewList[i]["FBaseMaterialCode"];
                    }
                    else
                    {
                        materialList[i].Add("FCode", viewList[i]["FBaseMaterialCode"]);
                    }



                    result += db.Updateable(materialList[i]).AS("TFS_Material").WhereColumns("FID").ExecuteCommand();
                }



               
                result += HalfMaterialUnionModifyData(materialList, "TFS_Material", teamId, db);
            }
            if (infoList != null && infoList.Count > 0)
            {
                for (int i = 0; i < infoList.Count; i++)
                {
                    if (infoList[i].ContainsKey("FTestCode")) 
                    {
                        if (materialList[i].ContainsKey("FTestCode")) 
                        {
                            infoList[i]["FTestCode"] = materialList[i]["FTestCode"].ToString();
                        }
                    }
                    else 
                    {
                        if (materialList[i].ContainsKey("FTestCode")) 
                        {
                            infoList[i].Add("FTestCode", materialList[i]["FTestCode"].ToString());
                        }
                    }

                    if (infoList[i].ContainsKey("FBaseTestCode")) 
                    {
                        if (viewList[i].ContainsKey("FBaseTestCode")) 
                        {
                            infoList[i]["FBaseTestCode"] = viewList[i]["FBaseTestCode"].ToString();
                        }
                    }
                    else 
                    {
                        if (viewList[i].ContainsKey("FBaseTestCode")) 
                        {
                            infoList[i].Add("FBaseTestCode", viewList[i]["FBaseTestCode"].ToString());
                        }
                    }

                    infoList[i]["FDataID"] = infoList[i]["FMaterialID"];
                    infoList[i].Remove("FMaterialID");
                    infoList[i].Add("FType", 2);
                    infoList[i].Add("FType2", int.Parse(materialList[i]["FTypeID2"].ToString()));
                    result += db.Updateable(infoList[i]).AS("TFS_MaterialInfo").WhereColumns("FType", "FDataID").ExecuteCommand();
                }
                
                result += UnionModifyData(infoList, "TFS_MaterialInfo", teamId, db, "FDataID");
            }
            //result += CheckTaskComplete2(db, teamId, viewType, userId);
            return result;
        }

        /// <summary>
        /// 试验号变更-
        /// </summary>
        /// <param name="db"></param>
        /// <param name="teamId"></param>
        /// <param name="taskType"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        private int CheckTaskComplete2(SqlSugarClient db, int teamId, int taskType, int userId)
        {
            int result = 0;
            //List<string> fields = db.Queryable<TBasicCode, TFS_ViewFieldInfo>((a, b) => new JoinQueryInfos(JoinType.Left, a.F2 == b.FID.ToString()))
            //       .Where((a, b) => a.FType == 40 && b.FType == 1 && a.F1 == taskType.ToString()).Select((a, b) => b.FField).ToList();
            //string okSql = string.Format("select count(1) from TFS_ViewMaterial where FTeamID={0} and FViewType={1} and(", teamId, taskType);
            //okSql += string.Join("='' or ", fields).Replace("TFS_ViewMaterial.", "") + "='')";
            //string okResult = db.Ado.GetString(okSql);
            string okResult = "";
            if (string.IsNullOrEmpty(okResult) || okResult == "0")
            {
                if (taskType != 10)
                {
                    //视图类型+2是事项，除了包材
                    taskType += 2;
                    if (taskType >= (int)Constant.TaskType.组编号申请) taskType = (int)Constant.TaskType.新包材视图;
                }
                else
                {
                    taskType = 15;
                }
                string taskSql = "";

                int proType = -2; string appSql = " and(select count(1) from TFS_HalfMaterialTask t where t.FTeamID=a.FTeamID and t.FType in({0}) and t.FState!=2)=0";
                switch (taskType)
                {
                    case 3://成品视图事项:3→成品视图：2
                        proType = 2;
                        break;
                    case 4://新半成品视图:4
                    case 5://新中间品视图:5
                    case 6://新香基视图:6→新半成品/中间品/香基：3
                        proType = 3;
                        appSql = string.Format(appSql, "4,5,6");
                        break;
                    case 7://新原料视图:7→新原料视图:4
                        proType = 4;
                        break;
                    case 15://物料分类视图:15→物料分类视图:0
                        proType = 0;
                        break;
                    case 11://新包材视图:7→新原料视图:8
                        proType = 8;
                        break;
                }
                if (taskType == 15 || proType > 0) taskSql = BaseBll.GetProcessSql2(teamId, proType, "F3", 2, string.Format(appSql, taskType));
                taskSql = BaseBll.GetTaskSql2(-1, 2, teamId, taskType, -1, string.Format("','+a.FUserID+',' like ',%{0}%,'", userId)) + taskSql;
                result += db.Ado.ExecuteCommand(taskSql);
                HalfMaterialTeamworkBll.ChangeTeamProcess(teamId);
            }
            return result;
        }

        /// <summary>
        /// 联合修改
        /// </summary>
        private int UnionModifyData(List<Dictionary<string, object>> dataList, string srcTable, int teamId, 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")
                                {
                                    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) { }
                    }
                }
            }
            return result;
        }




        private int HalfMaterialUnionModifyData(List<Dictionary<string, object>> dataList, string srcTable, int teamId, 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")
                                {
                                    sqlWhere = " and TFS_ViewMaterial.FHalfMaterialTeamID=" + 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) { }
                    }
                }
            }
            return result;
        }


        public object EexcSql(int tempId = 0)
        {
            string sql = "";
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();

            if (tempId > 0)
            {
                sql = string.Format("SELECT FMaterialFormulaIDs FROM TFS_FTeamwork WHERE FID='{0}'", tempId);
                var result= db.Ado.SqlQuery<string>(sql);

                if (string.IsNullOrWhiteSpace(result[0])) 
                {
                    return null;
                }
                sql = string.Format(@"SELECT
	                                        DISTINCT
	                                        a.*,
	                                        c.FName AS 'FUserName' 
                                        FROM
	                                        TFS_Material AS a
	                                        LEFT JOIN TUser AS c ON a.FEditUser= c.FID 
                                        WHERE
	                                        a.FID IN({0});", result[0]);

            }
            else
            {
                sql = string.Format(@"SELECT DISTINCT b.*,c.FName AS 'FUserName' FROM TFS_ViewMaterial AS a LEFT JOIN TFS_Material AS b ON a.FMaterialID=b.FID LEFT JOIN TUser AS c ON b.FEditUser=c.FID ");
            }

            return db.Ado.SqlQuery<object>(sql);

        }

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