using FactorySystemCommon;
using FactorySystemModel.BusinessModel;
using FactorySystemModel.EnumModel;
using FactorySystemModel.SqlSugarModel;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace FactorySystemBll
{
    public class HalfMaterialTeamworkBll    {
        /// <summary>
        /// 公共列表接口
        /// </summary>
        //public object GetTeamworkPageList(Dictionary<string, object> inParam, int userId, out int totalCount)
        //{
        //    totalCount = 0;
        //    int pageIndex = 1, pageSize = 15;
        //    List<string> paramName = new List<string>() { "FDeleted!=1" };
        //    List<SugarParameter> paramVal = new List<SugarParameter>();
        //    if (inParam != null && inParam.Count > 0)
        //    {
        //        foreach (var item in inParam)
        //        {
        //            if (item.Key == "FPageIndex" || item.Key == "PageIndex")
        //            {
        //                int.TryParse(item.Value.ToString(), out pageIndex);
        //            }
        //            else if (item.Key == "FPageSize" || item.Key == "PageSize")
        //            {
        //                int.TryParse(item.Value.ToString(), out pageSize);
        //            }
        //            else if (item.Key == "FAddDate" || item.Key == "AddDate")
        //            {
        //                paramName.Add("convert(varchar(10),FAddDate,120)=@FAddDate");
        //                paramVal.Add(new SugarParameter("@FAddDate", item.Value.ToString()));
        //            }
        //            else if (item.Key == "FDataType" || item.Key == "DataType")
        //            {
        //                if (item.Value.ToString() == "1")//我发起的
        //                {
        //                    paramName.Add("FAddUser=@FAddUser");
        //                    paramVal.Add(new SugarParameter("@FAddUser", userId));
        //                }
        //                else if (item.Value.ToString() == "2")//我参与的
        //                {
        //                    paramName.Add(string.Format(@"FID in(select distinct FTeamID from TFS_FTeamProcess where ','+FChargeID+',' like '%,{0},%'
        //                    union select distinct FTeamID from TFS_Task where ',' + FUserID + ',' like '%,{0},%')", userId));
        //                }
        //            }
        //            else if (item.Key == "FProgress" || item.Key == "FProgress")
        //            {
        //                string pVal = item.Value.ToString();
        //                if (!string.IsNullOrEmpty(pVal))
        //                {
        //                    if (pVal == "100" || pVal == "100%")
        //                    {
        //                        paramName.Add("FProgress='100'");
        //                    }
        //                    else
        //                    {
        //                        paramName.Add("FProgress!='100'");
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                //检索，全转成字符串
        //                paramName.Add("','+cast(" + item.Key + " as varchar)+',' like '%'+@" + item.Key + "+'%'");
        //                paramVal.Add(new SugarParameter("@" + item.Key, item.Value.ToString()));
        //            }
        //        }
        //    }
        //    string searchKey = "a.FID,a.FSaleCode,a.FTestCode,a.FViewType,a.FMdmCode,a.FFormulaID,a.FWeightUnit,a.FBomState,a.FProgress," +
        //        "a.FDeleted,a.FAddUser,a.FAddDate,a.FEditDate,b.FName FAddUserName,a.FFormulaName,a.FFormulaTestCode,a.FMaterialHalfIDs";
        //    SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
        //    var temp = db.Queryable<TFS_FTeamwork, TUser>((a, b) => new JoinQueryInfos(JoinType.Left, a.FAddUser == b.FID)).Select(searchKey);
        //    List<TFS_FTeamwork> resultList = db.Queryable(temp).Where(string.Join(" and ", paramName), paramVal)
        //        .OrderBy("FID desc").ToPageList(pageIndex, pageSize, ref totalCount);
        //    if (resultList.Count() > 0)
        //    {
        //        List<int> teamIds = resultList.Select(s => s.FID).ToList();
        //        List<TFS_Task> taskList = db.Queryable<TFS_Task>().Where(s => teamIds.Contains(s.FTeamID) && s.FState == 1)
        //            .Select("FTeamID,FType,FName").GroupBy("FTeamID,FType,FName").OrderBy("FType").ToList();
        //        if (taskList.Count() > 0)
        //        {
        //            foreach (TFS_FTeamwork item in resultList)
        //            {
        //                item.FTaskList = taskList.Where(s => s.FTeamID == item.FID).ToList();
        //            }
        //        }
        //    }
        //    return resultList;
        //}


        public object GetTeamworkPageList(Dictionary<string, object> inParam, int userId, out int totalCount) 
        {
            totalCount = 0;
            int pageIndex = 1, pageSize = 15;

            List<string> paramName = new List<string>() { "FDeleted!=1" };
            List<SugarParameter> paramVal = new List<SugarParameter>();

            List<string> FAddDate = null;
            if (inParam.ContainsKey("FAddDate"))
            {
                FAddDate = JsonConvert.DeserializeObject<List<string>>(inParam["FAddDate"].ToString());
            }


            if (inParam != null && inParam.Count > 0)
            {
                foreach (var item in inParam)
                {
                    if (item.Key == "FPageIndex" || item.Key == "PageIndex")
                    {
                        int.TryParse(item.Value.ToString(), out pageIndex);
                    }
                    else if (item.Key == "FPageSize" || item.Key == "PageSize")
                    {
                        int.TryParse(item.Value.ToString(), out pageSize);
                    }
                    else if (item.Key == "FAddDate" || item.Key == "AddDate")
                    {
                        if (!string.IsNullOrWhiteSpace(FAddDate[0].ToString())) 
                        {
                            paramName.Add("convert(varchar(10),FAddDate,120)>='" + FAddDate[0].ToString() + "'");
                            paramName.Add("convert(varchar(10),FAddDate,120)<='" + FAddDate[1].ToString() + "'");
                        }

                    }
                    else if (item.Key == "FDataType" || item.Key == "DataType")
                    {
                        if (item.Value.ToString() == "1")//我发起的
                        {
                            paramName.Add("FAddUser=@FAddUser");
                            paramVal.Add(new SugarParameter("@FAddUser", userId));
                        }
                        else if (item.Value.ToString() == "2")//我参与的
                        {
                            paramName.Add(string.Format(@"FID in(select distinct FTeamID from TFS_FTeamProcess where ','+FChargeID+',' like '%,{0},%'
                            union select distinct FTeamID from TFS_Task where ',' + FUserID + ',' like '%,{0},%')", userId));
                        }
                    }
                    else if (item.Key == "FProgress" || item.Key == "FProgress")
                    {
                        string pVal = item.Value.ToString();
                        if (!string.IsNullOrEmpty(pVal))
                        {
                            if (pVal == "100" || pVal == "100%")
                            {
                                paramName.Add("FProgress='100'");
                            }
                            else
                            {
                                paramName.Add("FProgress!='100'");
                            }
                        }
                    }
                    else
                    {
                        //检索，全转成字符串
                        paramName.Add("','+cast(" + item.Key + " as varchar)+',' like '%'+@" + item.Key + "+'%'");
                        paramVal.Add(new SugarParameter("@" + item.Key, item.Value.ToString()));
                    }
                }
            }

            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string searchKey = string.Format(@"a.*,d.FName");
            var temp =db.Queryable<TFS_HalfMaterialFTeamwork, TUser>((a,d) => new JoinQueryInfos(JoinType.Left, a.FAddUser == d.FID)).Select<object>(searchKey);

            List<object> result = db.Queryable(temp).Where(string.Join(" and ", paramName), paramVal)
               .OrderBy("FID desc").ToPageList(pageIndex, pageSize, ref totalCount).ToList<object>();
            return result;
        }

        /// <summary>
        /// 创建流程（仅仅创建，进度各个事项判断）
        /// </summary>
        public int CreateProcessData(int teamId, int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            try
            {
                List<TBasicCode> typeList = db.Queryable<TBasicCode>().Where(s => s.FType == (int)Constant.BasicCode.变更试验号流程 && s.FState == 1).ToList();
                List<TFS_HalfMaterialFTeamProcess> taskList = new List<TFS_HalfMaterialFTeamProcess>();
                TFS_HalfMaterialFTeamwork teamwork = BaseBll.GetTempModel<TFS_HalfMaterialFTeamwork>(teamId);
                foreach (var item in typeList)
                {
                    TFS_HalfMaterialFTeamProcess process = new TFS_HalfMaterialFTeamProcess()
                    {
                        FState = 0,//默认未开始
                        FProgress = 1,//默认F1文字
                        FDesc = item.F1,
                        FTeamID = teamId,
                        FName = item.FName,
                        FEditUser = userId,
                        FAddDate = DateTime.Now,
                        FEditDate = DateTime.Now,
                        FType = int.Parse(item.FValue),
                        FGroup = int.Parse(item.FCode),
                        FChargeID = "",
                        FChargeName = ""
                    };
                    List<TUser> users = null;
                    int proType = int.Parse(item.FValue);
                    switch (proType)
                    {
                        case (int)Constant.ProcessType.物料分类:
                        case (int)Constant.ProcessType.替代品确认:
                        case (int)Constant.ProcessType.协同发起:
                            string funcIds1 = "1,2,3";//36
                            users = db.Queryable<TUser>().Where(string.Format(@"FState=1 and FRoleID
                                                                    in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID 
                                                                    where b.FType={1} and b.FFunctionID in({0}) AND a.FFactoryID={2})",
                            funcIds1, (int)Constant.RoleType.事项权限, teamwork.FCreateFactoryID)).ToList();
                            break;
                        case (int)Constant.ProcessType.成品视图:
                            string funcIds2 = "1";//30
                            users = db.Queryable<TUser>().Where(string.Format(@"FState=1 and FRoleID 
                                                                                in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID 
	                                                                            where b.FType={1} and b.FFunctionID 
                                                                                in(select FValue from TBasicCode where FType={0} and F1={2}) AND a.FFactoryID={3})",
                            (int)Constant.BasicCode.物料视图编辑, (int)Constant.RoleType.物料视图编辑, funcIds2, teamwork.FCreateFactoryID)).ToList();
                            break;
                        case (int)Constant.ProcessType.新半成品中间品香基:
                            string funcIds3 = "2,3,4";//30
                            users = db.Queryable<TUser>().Where(string.Format(@"FState=1 and FRoleID 
                                                                                in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID 
	                                                                            where b.FType={1} and b.FFunctionID 
                                                                                in(select FValue from TBasicCode where FType={0} and F1 in ({2})) AND a.FFactoryID={3})",
                            (int)Constant.BasicCode.物料视图编辑, (int)Constant.RoleType.物料视图编辑, funcIds3, teamwork.FCreateFactoryID)).ToList();
                            break;
                        case (int)Constant.ProcessType.新原料视图:
                            string funcIds4 = "5";//30
                            users = db.Queryable<TUser>().Where(string.Format(@"FState=1 and FRoleID  
                                                                                in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID 
	                                                                            where b.FType={1} and b.FFunctionID 
                                                                                in(select FValue from TBasicCode where FType={0} and F1 in({2})) AND a.FFactoryID={3})",
                            (int)Constant.BasicCode.物料视图编辑, (int)Constant.RoleType.物料视图编辑, funcIds4, teamwork.FCreateFactoryID)).ToList();
                            break;
                        case (int)Constant.ProcessType.配方视图:
                            string funcIds5 = "2,7";//39
                            users = db.Queryable<TUser>().Where(string.Format(@"FState=1 and FRoleID 
                                                                                in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID 
                                                                                 where b.FType={1} and b.FFunctionID in({0}) AND a.FFactoryID={2})",
                                                                                 funcIds5, (int)Constant.RoleType.视图权限, teamwork.FCreateFactoryID)).ToList();
                            break;
                        case (int)Constant.ProcessType.生产工艺路线:
                            string funcIds6 = "3,8";//39
                            users = db.Queryable<TUser>().Where(string.Format(@"FState=1 and FRoleID 
                                                                                in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID 
                                                                                 where b.FType={1} and b.FFunctionID in({0}) AND a.FFactoryID={2})",
                                                                                 funcIds6, (int)Constant.RoleType.视图权限, teamwork.FCreateFactoryID)).ToList();
                            break;
                        case (int)Constant.ProcessType.生成版本:
                            string funcIds7 = "4,9";//39
                            users = db.Queryable<TUser>().Where(string.Format(@"FState=1 and FRoleID
                                                                                in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID 
                                                                                where b.FType={1} and b.FFunctionID in({0}) AND a.FFactoryID={2})",
                                                                                funcIds7, (int)Constant.RoleType.视图权限, teamwork.FCreateFactoryID)).ToList();
                            break;
                        case (int)Constant.ProcessType.组装BOM包含新包材:
                            string funcIds8 = "5,6";//36
                            users = db.Queryable<TUser>().Where(string.Format(@"FState=1 and (FRoleID in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID 
                                                                                where b.FType={1} AND a.FFactoryID={5} and b.FFunctionID in(select FValue from TBasicCode where FType={0} and F1={2})) 
                                                                                or FRoleID in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID where b.FType={3}
                                                                                AND a.FFactoryID={5} and b.FFunctionID in({4})) )",
                            (int)Constant.BasicCode.物料视图编辑, (int)Constant.RoleType.物料视图编辑, (int)Constant.ViewType.包材视图,
                            (int)Constant.RoleType.事项权限, funcIds8, teamwork.FCreateFactoryID)).ToList();
                            break;
                        case (int)Constant.ProcessType.流程完成:
                            string funcIds9 = "7";//36
                            users = db.Queryable<TUser>().Where(string.Format(@"FState=1 and FRoleID
                                                                                in(SELECT DISTINCT a.FRole FROM FPower AS a LEFT JOIN TRole_Right AS b ON a.FRole=b.FRoleID 
                                                                                where b.FType={1} and b.FFunctionID in({0}) AND a.FFactoryID={2})",
                                                                                funcIds9, (int)Constant.RoleType.事项权限, teamwork.FCreateFactoryID)).ToList();
                            break;
                    }
                    if (users != null && users.Count > 0)
                    {
                        foreach (var user in users)
                        {
                            process.FChargeID += user.FID + ",";
                            process.FChargeName += user.FName + "、";
                        }
                        process.FChargeID = process.FChargeID.Trim(',');
                        process.FChargeName = process.FChargeName.Trim('、');
                    }
                    else
                    {
                        process.FChargeName = "暂无";
                        process.FChargeID = "-1";
                    }
                    taskList.Add(process);
                }
                if (taskList.Count() > 0) return db.Insertable(taskList).ExecuteCommand();
            }
            catch (Exception)
            {
                //创建失败，删除
                db.Deleteable<TFS_HalfMaterialFTeamProcess>().Where(s => s.FTeamID == teamId).ExecuteCommand();
            }
            return 0;
        }

        /// <summary>
        /// 旧配方处理流程进度
        /// </summary>
        public void HasMaterialTestCode(TFS_HalfMaterialFTeamwork teamInfo)
        {
            string proSql = BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.新半成品中间品香基, "F5", 2);
            proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F5", 2);
            proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.配方视图, "F3", 2);
            proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.生产工艺路线, "F3", 2);
            proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.生成版本, "F4", 2);
            AppSettingsHelper.GetSqlSugar().Ado.ExecuteCommand(proSql.Trim(';'));
            ChangeTeamProcess(teamInfo.FID);
        }

        /// <summary>
        /// 获取协同视图字段信息
        /// </summary>
        public List<TFS_ViewFieldInfo> GetTeamworkViewField(int intType)
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<TFS_ViewFieldInfo>().Where(s => s.FType == intType
            && s.FDeleted != (int)Constant.DeleteCode.已删除).OrderBy(s => s.FOrder).ToList();
        }

       


       



        /// <summary>
        /// 获取协同视图结果信息
        /// </summary>
        public DataTable GetTeamworkViewData(string selectSql, string whereSql, string joinSql = "")
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = string.Format(@"select distinct {0},TFS_ViewMaterial.FMaterialID from TFS_FTeamwork left join TFS_ViewMaterial on 
            TFS_FTeamwork.FID=TFS_ViewMaterial.FTeamID left join TFS_Material on TFS_Material.FID=TFS_ViewMaterial.FMaterialID
            {2} where {1}", selectSql, whereSql, string.IsNullOrEmpty(joinSql) ? "" : joinSql);
            return db.Ado.GetDataTable(strSql);
        }
        /// <summary>
        /// 获取协同视图结果信息
        /// </summary>
        public DataTable GetHalfMaterialTeamworkViewData(string selectSql, string whereSql, string joinSql = "")
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = string.Format(@"select distinct {0},TFS_ViewMaterial.FMaterialID from TFS_HalfMaterialFTeamwork left join TFS_ViewMaterial on 
            TFS_HalfMaterialFTeamwork.FID=TFS_ViewMaterial.FHalfMaterialTeamID left join TFS_Material on TFS_Material.FID=TFS_ViewMaterial.FMaterialID
            {2} where {1}", selectSql, whereSql, string.IsNullOrEmpty(joinSql) ? "" : joinSql);
            return db.Ado.GetDataTable(strSql);
        }


        /// <summary>
        /// 获取协同视图结果信息
        /// </summary>
        public DataTable GetTeamworkViewData2(string selectSql, string whereSql, string joinSql = "")
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            string strSql = string.Format(@"select distinct {0},TFS_ViewMaterial.FMaterialID from TFS_ViewMaterial 
            left join TFS_Material on TFS_Material.FID=TFS_ViewMaterial.FMaterialID
            left join TFS_MaterialInfo on TFS_ViewMaterial.FMaterialID=TFS_MaterialInfo.FDataID and TFS_MaterialInfo.FType=2
            left join TFS_PackageChild on TFS_PackageChild.FMaterialID =TFS_ViewMaterial.FMaterialID
            {2} where {1}", selectSql, whereSql, string.IsNullOrEmpty(joinSql) ? "" : joinSql);
            return db.Ado.GetDataTable(strSql);
        }

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

        /// <summary>
        /// BOM梳理结果数据处理
        /// </summary>
        public bool AnalysisBomData(List<TFS_Material> mateList, List<TFS_ViewMaterial> viewList, int teamId, int userId, string formulaIds, string halfIds)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            db.BeginTran();
            try
            {
                viewList = viewList.OrderBy(s => s.FLevel).ToList();
                List<TFS_Material> formulaList = new List<TFS_Material>();
                TFS_HalfMaterialFTeamwork teamInfo = db.Queryable<TFS_HalfMaterialFTeamwork>().Where(s => s.FID == teamId).First();
                TFS_Factory factory = null;
                string proSql = "";
                Dictionary<int, string> hasNewView = new Dictionary<int, string>();
                for (int i = 0; i < viewList.Count; i++)
                {
                    TFS_ViewMaterial vItem = viewList[i];
                    TFS_Material mItem = mateList.Find(s => s.FID == vItem.FBomMaterialID);

                    int oldId = mItem.FID, oldParent = mItem.FParentID;
                    Expression<Func<TFS_Material, bool>> expression;
                    if (string.IsNullOrEmpty(mItem.FCode)) expression = s => s.FPlmCode == mItem.FPlmCode && s.FVersionCode == mItem.FVersionCode;
                    else expression = s => s.FCode == mItem.FCode && s.FVersionCode == mItem.FVersionCode ;

                    TFS_Material mData = db.Queryable<TFS_Material>().Where(expression).First();
                    if (mData == null)//没物料新增物料
                    {
                        if (factory == null)
                        {
                            string tempSql = @"select * from TFS_Factory where FID=(SELECT FCreateFactoryID FROM TFS_HalfMaterialFTeamwork WHERE FID={0})";
                            factory = db.SqlQueryable<TFS_Factory>(string.Format(tempSql, teamId)).First();
                        }
                        if (factory != null)
                        {
                            mItem.FFactoryID = factory.FID;
                            mItem.FFactoryCode = factory.FCode;
                        }
                        //mItem.FTestCode = teamInfo.FTestCode;
                        mItem.FID = db.Insertable(mItem).IgnoreColumns(true).ExecuteReturnIdentity();
                        //if (vItem.FLevel > 1) formulaIds += "," + mItem.FID;
                    }
                    else
                    {
                        string name = string.IsNullOrEmpty(mData.FName) ? mItem.FName : mData.FName;
                        viewList[i].FBaseMaterialDesc = name;
                        mItem = mData;
                    }
                    //formulaIds = formulaIds.Replace(oldId.ToString(), mItem.FID.ToString());
                    halfIds = halfIds.Replace(oldId.ToString(), mItem.FID.ToString());
                    bool hasCreate = false;
                    bool isAddFormula = false;
                    //是否有委外视图
                    TFS_ViewMaterial vData = db.Queryable<TFS_ViewMaterial>().Where(s => s.FFactoryID == teamInfo.FCreateFactoryID
                    && s.FMaterialID == mItem.FID).First();
                    if (vData == null)
                    {
                        hasCreate = isAddFormula = true;
                        vItem.FFactoryID = teamInfo.FCreateFactoryID;
                        vItem.FFactoryCode = teamInfo.FCreateFactoryCode;
                        vItem.FHalfMaterialTeamID = teamInfo.FID;
                        vItem.FMaterialID = mItem.FID;
                        vItem.FBaseMaterialGroup = mItem.FMaterialGroup;
                        vItem.FBaseBasicMeter = mItem.FBaseUnit;
                        db.Insertable(vItem).IgnoreColumns(true).ExecuteCommand();
                        if (!hasNewView.ContainsKey(vItem.FViewType)) hasNewView.Add(vItem.FViewType, vItem.FFactoryID.ToString() + ",");
                        else hasNewView[vItem.FViewType] = hasNewView[vItem.FViewType] + vItem.FFactoryID.ToString() + ",";
                    }
                    //是否有工厂视图
                    vData = db.Queryable<TFS_ViewMaterial>().Where(s => s.FFactoryID == teamInfo.FProdFactoryID && s.FMaterialID == mItem.FID).First();
                    if (vData == null)
                    {
                        isAddFormula = true;
                        vItem.FFactoryID = teamInfo.FProdFactoryID;
                        vItem.FFactoryCode = teamInfo.FProdFactoryCode;
                        vItem.FHalfMaterialTeamID = teamInfo.FID;
                        vItem.FMaterialID = mItem.FID;
                        vItem.FBaseMaterialGroup = mItem.FMaterialGroup;
                        vItem.FBaseBasicMeter = mItem.FBaseUnit;
                        //所谓固定字段，但是分工厂且视图还不一样
                        if (vItem.FViewType == (int)Constant.ViewType.半成品视图 || vItem.FViewType == (int)Constant.ViewType.中间品视图
                            || vItem.FViewType == (int)Constant.ViewType.香基视图)
                        {
                            vItem.FQualityType3 = "04";
                            vItem.FQualityType5 = "09";
                        }
                        else if (vItem.FViewType == (int)Constant.ViewType.原料视图)
                        {
                            if (hasCreate) vItem.FQualityType4 = "05";
                        }
                        else if (vItem.FViewType == (int)Constant.ViewType.包材视图)
                        {
                            if (hasCreate) vItem.FQualityType4 = "05";
                            else vItem.FQualityType1 = "01";
                        }
                        db.Insertable(vItem).IgnoreColumns(true).ExecuteCommand();
                        if (!hasNewView.ContainsKey(vItem.FViewType)) hasNewView.Add(vItem.FViewType, vItem.FFactoryID.ToString() + ",");
                        else hasNewView[vItem.FViewType] = hasNewView[vItem.FViewType] + vItem.FFactoryID.ToString() + ",";
                    }
                    mItem.FIsNew = isAddFormula;
                    mItem.FOldID = oldId;
                    mItem.FLevelID = vItem.FLevel;
                    mItem.FParentID = oldParent;
                    //mItem.FTestCode = teamInfo.FNewTestCode;
                    if (mItem.FLevelID >= 1) formulaList.Add(mItem);
                }

                formulaIds = "";
                //2022-09-27：生成BOM层级关系，生成配方视图的时候再根据这个处理父子
                List<BomFormulaDto> bfList = new List<BomFormulaDto>();
                if (formulaList.Count > 0)
                {
                    foreach (TFS_Material first in formulaList.Where(s => s.FLevelID == 1))
                    {
                        bfList.Add(new BomFormulaDto() { mId = first.FID, isNew = first.FIsNew, childs = GetBomFormulaChild(first, formulaList, out string fids) });
                        formulaIds += first.FID + "," + fids;
                    }
                }

                string updateSql = "";

                formulaIds = formulaIds.Replace(",,", ",").Replace(",,", ",").Replace(",,", ",").Trim(',');
                if (!string.IsNullOrEmpty(formulaIds))
                {
                    updateSql += string.Format("FMaterialFormulaIDs='{0}',FViewType=FViewType+',2',", formulaIds);
                    updateSql += string.Format("FBomFormula='{0}',", JsonConvert.SerializeObject(bfList));
                }
                if (!string.IsNullOrEmpty(halfIds)) updateSql += string.Format("FMaterialHalfIDs='{0}',", halfIds);
                if (!string.IsNullOrEmpty(updateSql)) proSql += string.Format("update TFS_HalfMaterialFTeamwork set {1} where FID={0};", teamInfo.FID, updateSql.Trim(','));
                proSql += BaseBll.GetTaskSql2(-1, 2, teamId, (int)Constant.TaskType.BOM下载, 2);
                db.Ado.ExecuteCommand(proSql.Trim(';'));
                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return false;
            }
            return true;
        }

        public bool CreateMaterialTask(Dictionary<int, string> hasNewView, TFS_HalfMaterialFTeamwork teamInfo, int userId)
        {
            string proSql = "";
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            db.BeginTran();

            try
            {
                if (hasNewView.Count() > 0)
                {
                    hasNewView.OrderBy(s => s.Key);
                    string facoryIds = ""; bool hasOther = false;
                    foreach (var item in hasNewView)
                    {   
                        //创建视图事项
                        string factorys = item.Value.Trim(',');
                        BaseBll.CreateTaskData2(teamInfo.FID, userId, (item.Key + 2).ToString(), factorys);
                        facoryIds += factorys;
                        if (item.Key != (int)Constant.ViewType.原料视图) hasOther = true;
                    }
                    if (hasNewView.ContainsKey((int)Constant.ViewType.原料视图))
                    {
                        proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F2", 1);
                    }
                    else
                    {
                        proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F4", 2);
                    }
                    if (hasOther)
                    {
                        proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.新半成品中间品香基, "F2", 1);
                    }
                    else
                    {
                        proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.新半成品中间品香基, "F4", 2);
                    }
                    if (hasNewView.ContainsKey((int)Constant.ViewType.中间品视图) || hasNewView.ContainsKey((int)Constant.ViewType.香基视图)
                        || hasNewView.ContainsKey((int)Constant.ViewType.半成品视图))
                    {
                        proSql += string.Format("update TFS_HalfMaterialFTeamwork set FViewType=FViewType+',3,4' where FID={0};", teamInfo.FID);
                        BaseBll.CreateTaskData2(teamInfo.FID, userId, "8");
                    }
                    proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.配方视图, "F2", 1);
                }
                else
                {
                    proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.配方视图, "F2", 2);
                    proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.新半成品中间品香基, "F4", 2);
                    proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F4", 2);
                }
                //下面两个要根据包材判断，先改成进行中，hasNewView == 0 && 包材是旧的，完成
                int pVersion = (hasNewView.Count == 0 && teamInfo.FPackID < 1) ? 2 : 1;
                proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.生产工艺路线, "F2", pVersion);
                proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.生成版本, "F2", pVersion);
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return false;
            }

            return true;

         }

        private List<BomFormulaDto> GetBomFormulaChild(TFS_Material first, List<TFS_Material> formulaList, out string fids)
        {
            List<BomFormulaDto> dtoList = new List<BomFormulaDto>();
            List<TFS_Material> temps = formulaList.Where(s => s.FParentID == first.FOldID).ToList();
            fids = "";
            if (temps != null && temps.Count > 0)
            {
                foreach (TFS_Material item in temps)
                {
                    if (first.FIsNew || item.FIsNew)fids += item.FID + ",";//父级新则子一级全部都要、自己是新
                    dtoList.Add(new BomFormulaDto() { mId = item.FID, isNew = item.FIsNew, childs = GetBomFormulaChild(item, formulaList, out string nextIds) });
                    if (!string.IsNullOrEmpty(nextIds)) fids += nextIds + ",";
                }
            }
            return dtoList;
        }

        /// <summary>
        /// 创建成品视图和包材判断
        /// </summary>
        public bool CreateProductView(TFS_HalfMaterialFTeamwork teamInfo, List<TFS_Material> materialList, int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            db.BeginTran();
            try
            {
                TFS_PackageMain package = null;
                string proSql = "";
                //包材信息判断
                {
                    //string packCode = teamInfo.FPackCode;
                    //List<string> names = teamInfo.FSaleCode.Split('-').ToList();
                    //string name = names.Where(s => s.Contains("@")).FirstOrDefault();
                    //if (string.IsNullOrEmpty(name))
                    //{
                    //    name = names.Where(s => s.Contains("□")).FirstOrDefault();
                    //    if (!string.IsNullOrEmpty(name)) packCode = name.Substring(0, name.IndexOf("□"));
                    //}
                    //else
                    //{
                    //    packCode = name.Substring(0, name.IndexOf("@"));
                    //}
                    //if (!string.IsNullOrEmpty(packCode))
                    //{
                    //    teamInfo.FPackCode = packCode;
                    //}
                    package = db.Queryable<TFS_PackageMain>().Where(s => s.FCode == teamInfo.FPackCode).OrderBy(s => s.FID, OrderByType.Desc).First();
                    if (package == null)
                    {
                        db.Updateable<TFS_HalfMaterialFTeamwork>(new { FPackCode = teamInfo.FPackCode }).Where(s => s.FID == teamInfo.FID).ExecuteCommand();
                        //BaseBll.CreateTaskData(teamInfo.FID, userId, "9");//新增新包材事项
                        proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.组装BOM包含新包材, "F2", 0);//新包材流程进行中
                    } else
                    {
                        db.Updateable<TFS_HalfMaterialFTeamwork>(new { FPackID = package.FID, FPackCode = teamInfo.FPackCode }).Where(s => s.FID == teamInfo.FID).ExecuteCommand();
                        proSql += BaseBll.GetProcessSql2(teamInfo.FID, (int)Constant.ProcessType.组装BOM包含新包材, "F3", 0);//新包材流程完成
                    }
                    if (materialList != null && materialList.Count > 0)
                    {
                        TFS_Material material = materialList.Find(s => s.FType == "20");//默认取第一个20的，没找到取第一个
                        if (material == null) material = materialList.FirstOrDefault();
                        db.Updateable<TFS_HalfMaterialFTeamwork>(new { FMaterialHalfIDs = material.FID }).Where(s => s.FID == teamInfo.FID).ExecuteCommand();
                    }
                }
                //物料和成品视图
                {
                    TFS_Material mainMater = new TFS_Material()
                    {
                        FName = teamInfo.FSaleCode,
                        FDesc = teamInfo.FSaleCode,
                        FType = "10",
                        FCode = teamInfo.FMdmCode,
                        FTestCode = teamInfo.FFormulaTestCode,
                        FFactoryID = teamInfo.FCreateFactoryID,
                        FFactoryCode = teamInfo.FCreateFactoryCode,
                        FEditUser = userId
                    };
                    mainMater.FID = db.Insertable(mainMater).IgnoreColumns(true).ExecuteReturnIdentity();
                    TFS_ViewMaterial mainView = new TFS_ViewMaterial()
                    {
                        FMaterialID = mainMater.FID,
                        FHalfMaterialTeamID = teamInfo.FID,
                        FFactoryID = teamInfo.FCreateFactoryID,
                        FFactoryCode = teamInfo.FCreateFactoryCode,
                        FViewType = (int)Constant.ViewType.物料分类视图,
                        FLevel = 1,
                        FEditUser = userId,
                        FBaseMaterialCode = teamInfo.FMdmCode,
                        FBaseTestCode = teamInfo.FNewTestCode,
                        FBaseBasicMeter = teamInfo.FWeightUnit,
                        FBaseMaterialDesc = teamInfo.FSaleCode,
                        FBaseMaterialGroup = teamInfo.FMaterialGroup,
                        //默认值不同
                        FOrganizeMaterialType = teamInfo.FMaterialType,
                        FAccountPriceUnit = "1",
                        FAccountAccessType = "3000",
                        FAccountSaleOrderInventory = "3010",
                        FAccountCostAccountBatch = "1",
                        //2022-10-08 所谓的成品字段值是包材的规格、毛重、净重
                        FBaseSpecification = package != null ? package.FSpecs : "",
                        FBaseGrossWeight = package != null ? package.FGrossWeight : "",
                        FBaseNetWeight = package != null ? package.FNetWeight : "",
                        FTeamType=2
                    };
                    db.Insertable(mainView).IgnoreColumns(true).ExecuteCommand();
                    if (teamInfo.FProdFactoryID != teamInfo.FCreateFactoryID)
                    {

                        //mainMater.FFactoryID = teamInfo.FProdFactoryID;
                        //mainMater.FFactoryCode = teamInfo.FProdFactoryCode;
                        //mainMater.FID = db.Insertable(mainMater).IgnoreColumns(true).ExecuteReturnIdentity();

                        mainView.FFactoryID = teamInfo.FProdFactoryID;
                        mainView.FFactoryCode = teamInfo.FProdFactoryCode;
                        mainView.FMaterialID = mainMater.FID;
                        db.Insertable(mainView).IgnoreColumns(true).ExecuteCommand();
                    }
                    //成品视图
                    //BaseBll.CreateTaskData(teamInfo.FID, userId, "3", teamInfo.FCreateFactoryID + "," + teamInfo.FProdFactoryID);
                }
                //成品视图物料组复核，有权限的所有
                //BaseBll.CreateTaskData(teamInfo.FID, userId, "12");
                //修改流程状态（协同发起完成，成品视图进行中）
                //proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.协同发起, "F2", 1);
                //proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.成品视图, "F2", 1);
                //proSql += BaseBll.GetTaskSql2(-1, 2, teamInfo.FID, (int)Constant.TaskType.配方选择, 2);
                //proSql = proSql.Trim(';');
                int result = db.Ado.ExecuteCommand(proSql);
                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return false;
            }
            return true;
        }

        /// <summary>
        /// 判断物料表里有这个实验号的数量
        /// </summary>
        public List<TFS_Material> CheckMaterialListByTest(string testCode, string versionCode)
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<TFS_Material>().Where(s => s.FTestCode == testCode && s.FVersionCode == versionCode).ToList();
        }

        /// <summary>
        /// 根据模式，试验号判断物料表里有这个实验号的数量
        /// </summary>
        public List<TFS_Material> CheckMaterialListByTest2(string testCode, int FFactoryID)
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<TFS_Material>().Where(s => s.FTestCode == testCode && s.FFactoryID == FFactoryID).ToList();
        }

        /// <summary>
        /// 更新协同主信息进度
        /// </summary>
        public static void ChangeTeamProcess(int teamId, SqlSugarClient db = null)
        {
            if (db == null) db = AppSettingsHelper.GetSqlSugar();
            db.Ado.ExecuteCommand(string.Format(@"
                declare @process1 int;
                set @process1=(select count(1) from TFS_HalfMaterialFTeamProcess where FTeamID={0} and FState=2)*8;
                set @process1+=(select count(1) from TFS_HalfMaterialTask where FTeamID={0} and FState=2)*5;
                update TFS_HalfMaterialFTeamwork set FProgress=(case when @process1>99 then '99' else @process1 end)
                where FID={0} and FProgress!='100';
            ", teamId));
        }

        /// <summary>
        /// 更具描述查询是否有重复名称
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool CheckTeamName(string name) 
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            return db.Queryable<TFS_FTeamwork>().Any(m => m.FSaleCode == name&&m.FDeleted!= (int)Constant.DeleteCode.已删除);
        }

        /// <summary>
        /// 更新配方
        /// </summary>
        /// <param name="testCode">原配方</param>
        /// <param name="testCode2">新配方</param>
        /// <returns></returns>
        public List<TFS_Material> UpdateFormula(string testCode, string testCode2,int temId, TFS_Factory factory, string idList="")
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_Material> materialList = null;


            materialList = db.Queryable<TFS_Material>().Where(m => m.FTestCode == testCode).ToList();
            List<int> ids = materialList.Select(m => m.FID).ToList();
            //更新配方
            string sql = "";


            if (string.IsNullOrWhiteSpace(idList))
            {
                sql = string.Format("update TFS_Material set FTestCode='{0}' WHERE FID in ({1});update TFS_ViewMaterial set FHalfMaterialTeamID={2},FBaseTestCode='{0}' WHERE FMaterialID in ({1});update TFS_MaterialInfo set FTestCode='{0}',FBaseTestCode='{0}'  WHERE FDataID IN({1})", testCode2, string.Join(",", ids), temId);
            }
            else
            {
                sql = string.Format("update TFS_Material set FTestCode='{0}' WHERE FID in ({1});update TFS_MaterialInfo set FTestCode='{0}',FBaseTestCode='{0}'  WHERE FDataID IN({1})", testCode, idList);
            }
            if (materialList.Count() > 0)
            {
                db.Ado.ExecuteCommand(sql);
            }


            //List<int> factoryList = new List<int>();
            //if (factory != null) 
            //{
            //    if (factory.FType != (int)Constant.FactoryType.单工厂) 
            //    {
            //        factoryList.Add(factory.FID);
            //        factoryList.Add(factory.FFactoryID);
            //    }
            //    else
            //    {
            //        factoryList.Add(factory.FID);
            //    }




            //}




            return materialList;
        }
    }
}
