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 TeamworkBll
    {
        /// 
        /// 公共列表接口
        /// 
        public object GetTeamworkPageList(Dictionary inParam, int userId, out int totalCount)
        {
            totalCount = 0;
            int pageIndex = 1, pageSize = 15;
            List paramName = new List() { "FDeleted!=1" };
            List paramVal = new List();
            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((a, b) => new JoinQueryInfos(JoinType.Left, a.FAddUser == b.FID)).Select(searchKey);
            List resultList = db.Queryable(temp).Where(string.Join(" and ", paramName), paramVal)
                .OrderBy("FID desc").ToPageList(pageIndex, pageSize, ref totalCount);
            if (resultList.Count() > 0)
            {
                List teamIds = resultList.Select(s => s.FID).ToList();
                List taskList = db.Queryable().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 int CreateProcessData(int teamId, int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            try
            {
                List typeList = db.Queryable().Where(s => s.FType == (int)Constant.BasicCode.流程类型 && s.FState == 1).ToList();
                List taskList = new List();
                foreach (var item in typeList)
                {
                    TFS_FTeamProcess process = new TFS_FTeamProcess()
                    {
                        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 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().Where(string.Format(@"FState=1 and FRoleID in(select distinct FRoleID from
                            TRole_Right where FType={1} and FFunctionID in({0}))", funcIds1, (int)Constant.RoleType.事项权限)).ToList();
                            break;
                        case (int)Constant.ProcessType.成品视图:
                            string funcIds2 = "1";//30
                            users = db.Queryable().Where(string.Format(@"FState=1 and FRoleID in(select distinct FRoleID from
                            TRole_Right where FType={1} and FFunctionID in(select FValue from TBasicCode where FType={0} and F1={2}))",
                            (int)Constant.BasicCode.物料视图编辑, (int)Constant.RoleType.物料视图编辑, funcIds2)).ToList();
                            break;
                        case (int)Constant.ProcessType.新半成品中间品香基:
                            string funcIds3 = "2,3,4";//30
                            users = db.Queryable().Where(string.Format(@"FState=1 and FRoleID in(select distinct FRoleID from
                            TRole_Right where FType={1} and FFunctionID in(select FValue from TBasicCode where FType={0} and F1 in({2})))",
                            (int)Constant.BasicCode.物料视图编辑, (int)Constant.RoleType.物料视图编辑, funcIds3)).ToList();
                            break;
                        case (int)Constant.ProcessType.新原料视图:
                            string funcIds4 = "5";//30
                            users = db.Queryable().Where(string.Format(@"FState=1 and FRoleID in(select distinct FRoleID from
                            TRole_Right where FType={1} and FFunctionID in(select FValue from TBasicCode where FType={0} and F1={2}))",
                            (int)Constant.BasicCode.物料视图编辑, (int)Constant.RoleType.物料视图编辑, funcIds4)).ToList();
                            break;
                        case (int)Constant.ProcessType.配方视图:
                            string funcIds5 = "2,7";//39
                            users = db.Queryable().Where(string.Format(@"FState=1 and FRoleID in(select distinct FRoleID from
                            TRole_Right where FType={1} and FFunctionID in({0}))", funcIds5, (int)Constant.RoleType.视图权限)).ToList();
                            break;
                        case (int)Constant.ProcessType.生产工艺路线:
                            string funcIds6 = "3,8";//39
                            users = db.Queryable().Where(string.Format(@"FState=1 and FRoleID in(select distinct FRoleID from
                            TRole_Right where FType={1} and FFunctionID in({0}))", funcIds6, (int)Constant.RoleType.视图权限)).ToList();
                            break;
                        case (int)Constant.ProcessType.生成版本:
                            string funcIds7 = "4,9";//39
                            users = db.Queryable().Where(string.Format(@"FState=1 and FRoleID in(select distinct FRoleID from
                            TRole_Right where FType={1} and FFunctionID in({0}))", funcIds7, (int)Constant.RoleType.视图权限)).ToList();
                            break;
                        case (int)Constant.ProcessType.组装BOM包含新包材:
                            string funcIds8 = "5,6";//36
                            users = db.Queryable().Where(string.Format(@"FState=1 and (FRoleID in(select distinct FRoleID from
                            TRole_Right where FType={1} and FFunctionID in(select FValue from TBasicCode where FType={0} and F1={2})) 
                            or FRoleID in(select distinct FRoleID from TRole_Right where FType={3} and FFunctionID in({4})) )",
                            (int)Constant.BasicCode.物料视图编辑, (int)Constant.RoleType.物料视图编辑, (int)Constant.ViewType.包材视图,
                            (int)Constant.RoleType.事项权限, funcIds8)).ToList();
                            break;
                        case (int)Constant.ProcessType.流程完成:
                            string funcIds9 = "7";//36
                            users = db.Queryable().Where(string.Format(@"FState=1 and FRoleID in(select distinct FRoleID from
                            TRole_Right where FType={1} and FFunctionID in({0}))", funcIds9, (int)Constant.RoleType.事项权限)).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().Where(s => s.FTeamID == teamId).ExecuteCommand();
            }
            return 0;
        }
        /// 
        /// 旧配方处理流程进度
        /// 
        public void HasMaterialTestCode(TFS_FTeamwork teamInfo)
        {
            string proSql = BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新半成品中间品香基, "F5", 2);
            proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F5", 2);
            proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.配方视图, "F3", 2);
            proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.生产工艺路线, "F3", 2);
            proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.生成版本, "F4", 2);
            AppSettingsHelper.GetSqlSugar().Ado.ExecuteCommand(proSql.Trim(';'));
            ChangeTeamProcess(teamInfo.FID);
        }
        /// 
        /// 获取协同视图字段信息
        /// 
        public List GetTeamworkViewField(int intType)
        {
            return AppSettingsHelper.GetSqlSugar().Queryable().Where(s => s.FType == intType
            && s.FDeleted != (int)Constant.DeleteCode.已删除).OrderBy(s => s.FOrder).ToList();
        }
       
       
        /// 
        /// 获取协同视图结果信息
        /// 
        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);
        }
        /// 
        /// 获取协同视图结果信息
        /// 
        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);
        }
        /// 
        /// BOM梳理结果数据处理
        /// 
        public bool AnalysisBomData(List mateList, List viewList, int teamId, int userId, string formulaIds, string halfIds)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            db.BeginTran();
            try
            {
                viewList = viewList.OrderBy(s => s.FLevel).ToList();
                List formulaList = new List();
                TFS_FTeamwork teamInfo = db.Queryable().Where(s => s.FID == teamId).First();
                TFS_Factory factory = null;
                string proSql = "";
                Dictionary hasNewView = new Dictionary();
                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> 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().Where(expression).First();
                    if (mData == null)//没物料新增物料
                    {
                        if (factory == null)
                        {
                            string tempSql = @"select * from TFS_Factory where FID=(SELECT FCreateFactoryID FROM TFS_FTeamwork WHERE FID={0})";
                            factory = db.SqlQueryable(string.Format(tempSql, teamId)).First();
                        }
                        if (factory != null)
                        {
                            mItem.FFactoryID = factory.FID;
                            mItem.FFactoryCode = factory.FCode;
                        }
                        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().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.FTeamID = 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().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.FTeamID = 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;
                    if (mItem.FLevelID >= 1) formulaList.Add(mItem);
                }
                formulaIds = "";
                //2022-09-27:生成BOM层级关系,生成配方视图的时候再根据这个处理父子
                List bfList = new List();
                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;
                    }
                }
                //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.CreateTaskData(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.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F2", 1);
                //    }
                //    else
                //    {
                //        proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F4", 2);
                //    }
                //    if (hasOther)
                //    {
                //        proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新半成品中间品香基, "F2", 1);
                //    }
                //    else
                //    {
                //        proSql += BaseBll.GetProcessSql(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_FTeamwork set FViewType=FViewType+',3,4' where FID={0};", teamInfo.FID);
                //        BaseBll.CreateTaskData(teamId, userId, "8");
                //    }
                //    proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.配方视图, "F2", 1);
                //}
                //else
                //{
                //    proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.配方视图, "F2", 2);
                //    proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新半成品中间品香基, "F4", 2);
                //    proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F4", 2);
                //}
                ////下面两个要根据包材判断,先改成进行中,hasNewView == 0 && 包材是旧的,完成
                //int pVersion = (hasNewView.Count == 0 && teamInfo.FPackID < 1) ? 2 : 1;
                //proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.生产工艺路线, "F2", pVersion);
                //proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.生成版本, "F2", pVersion);
                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_FTeamwork set {1} where FID={0};", teamInfo.FID, updateSql.Trim(','));
                proSql += BaseBll.GetTaskSql(-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 hasNewView, TFS_FTeamwork 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.CreateTaskData(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.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F2", 1);
                    }
                    else
                    {
                        proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F4", 2);
                    }
                    if (hasOther)
                    {
                        proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新半成品中间品香基, "F2", 1);
                    }
                    else
                    {
                        proSql += BaseBll.GetProcessSql(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_FTeamwork set FViewType=FViewType+',3,4' where FID={0};", teamInfo.FID);
                        BaseBll.CreateTaskData(teamInfo.FID, userId, "8");
                    }
                    proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.配方视图, "F2", 1);
                }
                else
                {
                    proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.配方视图, "F2", 2);
                    proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新半成品中间品香基, "F4", 2);
                    proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.新原料视图, "F4", 2);
                }
                //下面两个要根据包材判断,先改成进行中,hasNewView == 0 && 包材是旧的,完成
                int pVersion = (hasNewView.Count == 0 && teamInfo.FPackID < 1) ? 2 : 1;
                proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.生产工艺路线, "F2", pVersion);
                proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.生成版本, "F2", pVersion);
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return false;
            }
            return true;
         }
        private List GetBomFormulaChild(TFS_Material first, List formulaList, out string fids)
        {
            List dtoList = new List();
            List 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;
        }
        /// 
        /// 创建成品视图和包材判断
        /// 
        public bool CreateProductView(TFS_FTeamwork teamInfo, List materialList, int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            db.BeginTran();
            try
            {
                TFS_PackageMain package = null;
                string proSql = "";
                //包材信息判断
                {
                    //string packCode = teamInfo.FPackCode;
                    //List 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().Where(s => s.FCode == teamInfo.FPackCode).OrderBy(s => s.FID, OrderByType.Desc).First();
                    if (package == null)
                    {
                        db.Updateable(new { FPackCode = teamInfo.FPackCode }).Where(s => s.FID == teamInfo.FID).ExecuteCommand();
                        //BaseBll.CreateTaskData(teamInfo.FID, userId, "9");//新增新包材事项
                        proSql += BaseBll.GetProcessSql(teamInfo.FID, (int)Constant.ProcessType.组装BOM包含新包材, "F2", 0);//新包材流程进行中
                    } else
                    {
                        db.Updateable(new { FPackID = package.FID, FPackCode = teamInfo.FPackCode }).Where(s => s.FID == teamInfo.FID).ExecuteCommand();
                        proSql += BaseBll.GetProcessSql(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(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,
                        FTeamID = teamInfo.FID,
                        FFactoryID = teamInfo.FCreateFactoryID,
                        FFactoryCode = teamInfo.FCreateFactoryCode,
                        FViewType = (int)Constant.ViewType.物料分类视图,
                        FLevel = 1,
                        FEditUser = userId,
                        FBaseMaterialCode = teamInfo.FMdmCode,
                        FBaseTestCode = teamInfo.FTestCode,
                        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 : ""
                    };
                    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.GetTaskSql(-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;
        }
        /// 
        /// 判断物料表里有这个实验号的数量
        /// 
        public List CheckMaterialListByTest(string testCode, string versionCode)
        {
            return AppSettingsHelper.GetSqlSugar().Queryable().Where(s => s.FTestCode == testCode && s.FVersionCode == versionCode).ToList();
        }
        /// 
        /// 更新协同主信息进度
        /// 
        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_FTeamProcess where FTeamID={0} and FState=2)*8;
                set @process1+=(select count(1) from TFS_Task where FTeamID={0} and FState=2)*5;
                update TFS_FTeamwork set FProgress=(case when @process1>99 then '99' else @process1 end)
                where FID={0} and FProgress!='100';
            ", teamId));
        }
        /// 
        /// 更具描述查询是否有重复名称
        /// 
        /// 
        /// 
        public bool CheckTeamName(string name) 
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            return db.Queryable().Any(m => m.FSaleCode == name&&m.FDeleted!= (int)Constant.DeleteCode.已删除);
        }
    }
}