using FactorySystemCommon;
using FactorySystemModel.BusinessModel;
using FactorySystemModel.EnumModel;
using FactorySystemModel.SqlSugarModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
namespace FactorySystemBll
{
    public class BaseBll
    {
        /// 
        /// 修改数据信息
        ///  
        public static int UpdateDataModel(Dictionary updateModel, string tableName)
        {
            return AppSettingsHelper.GetSqlSugar().Updateable(updateModel).AS(tableName).WhereColumns("FID").ExecuteCommand();
        }
        /// 
        /// 修改数据信息
        ///  
        public static int UpdateDataModel(dynamic updateModel)
        {
            return AppSettingsHelper.GetSqlSugar().Updateable(updateModel).ExecuteCommand();
        }
        /// 
        /// 删除数据信息
        ///  
        public int DeleteDataById(Dictionary updateModel, string tableName, bool realDel = false)
        {
            if (updateModel.TryGetValue("FID", out object objId) || updateModel.TryGetValue("dataId", out objId))
            {
                if (updateModel.ContainsKey("dataId")) updateModel.Remove("dataId");
                if (updateModel.ContainsKey("FID")) updateModel.Remove("FID");
                if (realDel)
                {
                    return AppSettingsHelper.GetSqlSugar().Deleteable().AS(tableName).Where("FID=" + objId).ExecuteCommand();
                }
                else
                {
                    updateModel.Add("FDeleted", (int)Constant.DeleteCode.已删除);
                    return AppSettingsHelper.GetSqlSugar().Updateable(updateModel).AS(tableName).Where("FID=" + objId).ExecuteCommand();
                }
            }
            return 0;
        }
        /// 
        /// 删除数据信息
        ///  
        public int DeleteDataById(int dataId, string tableName, bool realDel = false)
        {
            Dictionary updateModel = new Dictionary();
            updateModel.Add("FID", dataId);
            return DeleteDataById(updateModel, tableName, realDel);
        }
        /// 
        /// 新增数据信息
        ///  
        public int InsertDataModel(Dictionary insertData, string tableName)
        {
            var model= AppSettingsHelper.GetSqlSugar().Insertable(insertData).AS(tableName).ExecuteReturnIdentity();
            return model;
        }
        /// 
        /// 公共列表接口(前缀未Or_的为或条件检索,后缀为ID的是多唯一编号检索)
        ///  
        public object GetPageList(Dictionary updateModel, out int totalCount, string selectKey = null, string orderBy = "FID desc")
        {
            totalCount = 0;
            int pageIndex = 1, pageSize = 15;
            List paramName = new List() { "FDeleted!=1" };
            List paramVal = new List();
            if (updateModel != null && updateModel.Count > 0)
            {
                List orList = new List();
                if (updateModel.TryGetValue("FPageOrderBy", out object orderBy2))
                {
                    updateModel.Remove("FPageOrderBy");
                    orderBy = HttpUtility.UrlEncode(orderBy2.ToString());
                    if (string.IsNullOrEmpty(orderBy)) orderBy = "FID desc";
                }
                foreach (var item in updateModel)
                {
                    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
                    {
                        try
                        {
                            string keyVal = "@" + item.Key;
                            string keyName = item.Key;
                            if (item.Key.EndsWith("ID")) keyVal = "','+" + keyVal + "+','";
                            if (item.Key.StartsWith("Or_"))
                            {
                                keyName = keyName.Replace("Or_", "");
                                keyVal = keyVal.Replace("Or_", "");
                                orList.Add("','+cast(" + keyName + " as varchar(400))+',' like '%'+" + keyVal + "+'%'");
                            }
                            else
                            {
                                paramName.Add("','+cast(" + keyName + " as varchar(400))+',' like '%'+" + keyVal + "+'%'");
                            }
                            paramVal.Add(new SugarParameter("@" + keyName, item.Value.ToString()));
                        }
                        catch (Exception) { }
                    }
                }
                if (orList.Count() > 0) paramName.Add("(" + string.Join(" or ", orList) + ")");
            }
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            var temp = db.Queryable().Where(string.Join(" and ", paramName), paramVal).OrderBy(orderBy);
            if (!string.IsNullOrEmpty(selectKey)) temp = temp.Select(selectKey);
            return temp.ToPageList(pageIndex, pageSize, ref totalCount);
        }
        /// 
        /// 根据类型获取字段对应关系
        ///  
        public List GetFileInfoList(int typeId)
        {
            return AppSettingsHelper.GetSqlSugar().Queryable().Where(s => s.FDeleted != (int)Constant.DeleteCode.已删除
            && s.FType == typeId).OrderBy(s => s.FOrder).ToList();
        }
        /// 
        /// 根据键获取设置值
        ///  
        public string GetSettingByKey(string setKey)
        {
            TFS_Setting setting = AppSettingsHelper.GetSqlSugar().Queryable().Where(s => s.FState == 1 && s.FKey == setKey)
                .OrderBy(s => s.FID, OrderByType.Desc).First();
            if (setting != null) return setting.FValue;
            return "";
        }
        /// 
        /// 根据键获取数据
        ///  
        public static T GetTempModel(int dataId, string keys = "")
        {
            if (string.IsNullOrEmpty(keys))
                return AppSettingsHelper.GetSqlSugar().Queryable().Where("FID=" + dataId).First();
            return AppSettingsHelper.GetSqlSugar().Queryable().Where("FID=" + dataId).Select(keys).First();
        }
        /// 
        /// 根据键获取数据
        ///  
        public static T GetTempModel(string where, string keys = "")
        {
            if (string.IsNullOrEmpty(keys))
                return AppSettingsHelper.GetSqlSugar().Queryable().Where(where).First();
            return AppSettingsHelper.GetSqlSugar().Queryable().Where(where).Select(keys).First();
        }
        /// 
        /// 根据键获取数据
        ///  
        public Dictionary GetTempDict(int dataId, string keys = "")
        {
            if (string.IsNullOrEmpty(keys))
                return AppSettingsHelper.GetSqlSugar().Queryable().Where("FID=" + dataId).ToDictionaryList().FirstOrDefault();
            return AppSettingsHelper.GetSqlSugar().Queryable().Where("FID=" + dataId).Select(keys).ToDictionaryList().FirstOrDefault();
        }
        /// 
        /// 事项变更修改流程进度
        /// proProgress(事项文字类型):对应F+proProgress
        /// proState(事项状态):0未开始,1进行中,2已完成
        ///  
        public void UpdateTeamProcess(int teamId, int proType, int proProgress, int proState = -1, string appWhere = "1=1")
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            TBasicCode basicCode = db.Queryable().Where(s => s.FValue == proType.ToString()
            && s.FType == (int)Constant.BasicCode.流程类型).First();
            if (basicCode != null)
            {
                Dictionary updateModel = new Dictionary();
                switch (proProgress)
                {
                    case 1:
                        updateModel.Add("FDesc", basicCode.F1);
                        break;
                    case 2:
                        updateModel.Add("FDesc", basicCode.F2);
                        break;
                    case 3:
                        updateModel.Add("FDesc", basicCode.F3);
                        break;
                    case 4:
                        updateModel.Add("FDesc", basicCode.F4);
                        break;
                    case 5:
                        updateModel.Add("FDesc", basicCode.F5);
                        break;
                }
                if (proState > 0)
                {
                    updateModel.Add("FState", proState);
                    if (proState == 1) updateModel.Add("FStartDate", DateTime.Now);
                    else if (proState == 2) updateModel.Add("FFinishDate", DateTime.Now);
                }
                updateModel.Add("FProgress", proProgress);
                db.Updateable(updateModel).Where(s => s.FTeamID == teamId && s.FType == proType)
                    .Where(appWhere).ExecuteCommand();
            }
        }
        /// 
        /// 试验号变更修改流程进度
        ///  
        ///  
        ///  
        ///  
        ///  
        ///  
        public void UpdateTeamProcess2(int teamId, int proType, int proProgress, int proState = -1, string appWhere = "1=1")
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            TBasicCode basicCode = db.Queryable().Where(s => s.FValue == proType.ToString()
            && s.FType == (int)Constant.BasicCode.变更试验号流程).First();
            if (basicCode != null)
            {
                Dictionary updateModel = new Dictionary();
                switch (proProgress)
                {
                    case 1:
                        updateModel.Add("FDesc", basicCode.F1);
                        break;
                    case 2:
                        updateModel.Add("FDesc", basicCode.F2);
                        break;
                    case 3:
                        updateModel.Add("FDesc", basicCode.F3);
                        break;
                    case 4:
                        updateModel.Add("FDesc", basicCode.F4);
                        break;
                    case 5:
                        updateModel.Add("FDesc", basicCode.F5);
                        break;
                }
                if (proState > 0)
                {
                    updateModel.Add("FState", proState);
                    if (proState == 1) updateModel.Add("FStartDate", DateTime.Now);
                    else if (proState == 2) updateModel.Add("FFinishDate", DateTime.Now);
                }
                updateModel.Add("FProgress", proProgress);
                db.Updateable(updateModel).Where(s => s.FTeamID == teamId && s.FType == proType)
                    .Where(appWhere).ExecuteCommand();
            }
        }
        /// 
        /// 创建数据库表
        ///  
        public void CreateSqlSugarModel(string likeName)
        {
            string porPath = AppDomain.CurrentDomain.BaseDirectory.Trim('\\') + "\\SqlSugarModel";
            porPath = porPath.Replace("/", "\\").Replace("FactorySystemApi\\FactorySystemApi", "FactorySystemApi\\FactorySystemModel");
            string nameSpace = "FactorySystemModel.SqlSugarModel";
            AppSettingsHelper.GetSqlSugar().DbFirst.Where(it => it.Contains(likeName)).IsCreateAttribute().CreateClassFile(porPath, nameSpace);
        }
        /// 
        /// 创建事项
        ///  
        public static void CreateTaskData(int teamId, int userId, string taskTypes, string factoryId = "", bool onceMore = true, SqlSugarClient db = null)
        {
            List insertList = new List();
            List updateList = new List();
            List messageList = new List();
            try
            {
                if (db == null) db = AppSettingsHelper.GetSqlSugar();
                List taskTypeList = taskTypes.Split(',').ToList();
                if (string.IsNullOrEmpty(factoryId))
                {
                    TFS_FTeamwork team = db.Queryable().Where(t => t.FID == teamId).First();
                    if (team != null) factoryId = team.FCreateFactoryID.ToString();
                }
                List basicCodeList = db.Queryable().Where(s => s.FType == (int)Constant.BasicCode.事项类型
                && s.FState == 1 && taskTypeList.Contains(s.FValue)).ToList();
                PropertyInfo[] basicCodeProps = typeof(TBasicCode).GetProperties();
                for (int i = 0; i < taskTypeList.Count; i++)
                {
                    TBasicCode basicCode = basicCodeList.Find(s => s.FValue == taskTypeList[i]);
                    if (basicCode == null) continue;
                    string[] temps = basicCode.FRemark.Split('_');
                    int temp0 = int.Parse(temps[0]), funcType = -1;
                    string taskDesc = basicCode.F1;
                    List funcVal = new List();
                    switch (temp0)
                    {
                        case (int)Constant.BasicCode.事项权限:
                            funcType = (int)Constant.RoleType.事项权限;
                            funcVal.Add(temps[1]);
                            break;
                        case (int)Constant.BasicCode.物料视图编辑:
                            funcType = (int)Constant.RoleType.物料视图编辑;
                            string tType = temps[1];
                            funcVal = db.Queryable().Where(s => s.FType == (int)Constant.BasicCode.物料视图编辑 &&
                            s.F1 == tType && s.FState == 1).Select(s => s.FValue).ToList();
                            break;
                    }
                    if (funcType > 0)
                    {
                        //List users = db.Queryable((a, b, c) => new JoinQueryInfos(JoinType.Left, a.FRoleID == b.FRoleID, 
                        //    JoinType.Left, a.FID == int.Parse(c.FUserID)))
                        //         .Where((a, b) => a.FState == 1 && a.FDeleted != 1 && b.FType == funcType && funcVal.Contains(b.FFunctionID.ToString()))
                        //         .Where(string.IsNullOrEmpty(factoryId) ? "1=1" : string.Format("c.FFactoryID in({0})", factoryId))
                        //         .GroupBy("a.FID,c.FFactoryID,a.FName,a.FUser").Select("a.FID,cast(c.FFactoryID as int),a.FName,a.FUser").ToList();
                        List users = db.Queryable ((a, b, c) => new JoinQueryInfos(
                            JoinType.Left, a.FUserID.Equals(b.FID.ToString()),
                            JoinType.Left, a.FRole.Equals(c.FRoleID.ToString())
                            ))
                            .Where((a, b, c) => factoryId.Contains(a.FFactoryID))
                            .Where((a, b, c) => b.FState == 1 && b.FDeleted != 1)
                            .Where((a, b, c) => c.FType == funcType && funcVal.Contains(c.FFunctionID.ToString()))
                            .GroupBy("b.FID, a.FFactoryID, b.FName, b.FUser")
                            .Select("b.FID, cast(a.FFactoryID as int), b.FName, b.FUser")
                            .ToList();
                        if (users.Count() > 0)
                        {
                            if (string.IsNullOrEmpty(factoryId))
                            {
                                TFS_Task newTask = new TFS_Task()
                                {
                                    FName = basicCode.FName,
                                    FDesc = taskDesc,
                                    FTeamID = teamId,
                                    FEditUser = userId,
                                    FFactoryID = -1,
                                    FAddDate = DateTime.Now,
                                    FCanEdit = 1,
                                    FEditDate = DateTime.Now,
                                    FType = int.Parse(basicCode.FValue),
                                    FUserID = string.Join(",", users.GroupBy(ss => ss.FID).Select(sss => sss.Key)),
                                    FUserName = string.Join("、", users.GroupBy(ss => ss.FName).Select(sss => sss.Key)),
                                    FState = 1
                                };
                                TFS_Task oldTask = db.Queryable().Where(s => s.FTeamID == teamId && s.FType == newTask.FType
                                && s.FFactoryID == newTask.FFactoryID).First();
                                if (oldTask == null)
                                {
                                    insertList.Add(newTask);
                                    messageList.Add(new MessageDto()
                                    {
                                        message = newTask.FDesc,
                                        userId = string.Join(",", users.GroupBy(ss => ss.FDockID).Select(sss => sss.Key))
                                    });
                                }
                                else
                                {
                                    oldTask.FUserID = newTask.FUserID;
                                    updateList.Add(oldTask);
                                }
                            }
                            else
                            {
                                foreach (var factory in users.GroupBy(s => s.FFactoryID))
                                {
                                    TFS_Task newTask = new TFS_Task()
                                    {
                                        FName = basicCode.FName,
                                        FDesc = taskDesc,
                                        FTeamID = teamId,
                                        FEditUser = userId,
                                        FFactoryID = factory.Key,
                                        FAddDate = DateTime.Now,
                                        FCanEdit = 1,
                                        FEditDate = DateTime.Now,
                                        FType = int.Parse(basicCode.FValue),
                                        FUserID = string.Join(",", factory.GroupBy(ss => ss.FID).Select(sss => sss.Key)),
                                        FUserName = string.Join("、", factory.GroupBy(ss => ss.FName).Select(sss => sss.Key)),
                                        FState = 1
                                    };
                                    TFS_Task oldTask = db.Queryable().Where(s => s.FTeamID == teamId && s.FType == newTask.FType
                                    && s.FFactoryID == factory.Key).First();
                                    if (oldTask == null)
                                    {
                                        insertList.Add(newTask);
                                        messageList.Add(new MessageDto()
                                        {
                                            message = newTask.FDesc,
                                            userId = string.Join(",", factory.GroupBy(ss => ss.FDockID).Select(sss => sss.Key))
                                        });
                                    }
                                    else
                                    {
                                        oldTask.FUserID = newTask.FUserID;
                                        updateList.Add(oldTask);
                                    }
                                }
                            }
                        }
                    }
                }
                if (insertList.Count() > 0)
                {
                    db.Insertable(insertList).ExecuteCommand();
                    SendWeChatMessage(messageList);
                }
                if (updateList.Count() > 0) db.Updateable(updateList).ExecuteCommand();
            }
            catch (Exception ex)
            {
                if (onceMore)
                {
                    CreateTaskData(teamId, userId, taskTypes, factoryId, false);
                }
                else
                {
                    insertList.AddRange(updateList);
                    ExceptionHelper.AddSystemJournal(null, insertList, ex.Message, userId, "TeamworkBll.CreateTaskData");
                }
            }
        }
        public static int CreateMaterialTask(int teamId, int userId, int type, int factoryId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            int funcType = (int)Constant.RoleType.物料视图编辑;
            string tType = "10";
            int taskId = -1;
            try
            {
                List funcVal = db.Queryable().Where(s => s.FType == (int)Constant.BasicCode.物料视图编辑 && s.F1 == tType && s.FState == 1).Select(s => s.FValue).ToList();
                List users = db.Queryable((a, b) => new JoinQueryInfos(JoinType.Left, a.FRoleID == b.FRoleID))
                    .Where((a, b) => a.FState == 1 && a.FDeleted != 1 && b.FType == funcType && funcVal.Contains(b.FFunctionID.ToString()))
                    .Where(string.Format("a.FFactoryID in({0})", factoryId))
                    .GroupBy("a.FID,a.FFactoryID,a.FName,a.FUser").Select("a.FID,a.FFactoryID,a.FName,a.FUser").ToList();
                if (users.Count > 0) {
                    TFS_FMaterialTask materialTask = new TFS_FMaterialTask();
                    materialTask.FMaterialTeamID = teamId;
                    materialTask.FType = type;
                    materialTask.FFactoryID = factoryId;
                    materialTask.FCanEdit = 1;
                    materialTask.FAddUser = userId;
                    materialTask.FAddDate = DateTime.Now;
                    materialTask.FState = 1;
                    if (type == 15)
                    {
                        materialTask.FName = "物料分类";
                        materialTask.FDesc = "物料分类选择";
                    }
                    else
                    {
                        materialTask.FName = "物料视图";
                        materialTask.FDesc = "物料视图编辑";
                    }
                    materialTask.FUserID = string.Join(",", users.GroupBy(ss => ss.FID).Select(sss => sss.Key));
                    materialTask.FUserName = string.Join("、", users.GroupBy(ss => ss.FName).Select(sss => sss.Key));
                    taskId = db.Insertable(materialTask).IgnoreColumns(true).ExecuteReturnIdentity();
                }                
            }
            catch (Exception ex)
            {
                taskId = -1;
            }            
            return taskId;
        }
        /// 
        /// 更换试验号流程创建事项
        ///  
        public static void CreateTaskData2(int teamId, int userId, string taskTypes, string factoryId = "", bool onceMore = true, SqlSugarClient db = null)
        {
            List insertList = new List();
            List updateList = new List();
            List messageList = new List();
            try
            {
                if (db == null) db = AppSettingsHelper.GetSqlSugar();
                if (string.IsNullOrEmpty(factoryId))
                {
                    TFS_HalfMaterialFTeamwork team = db.Queryable().Where(t => t.FID == teamId).First();
                    if (team != null) factoryId = team.FCreateFactoryID.ToString();
                }
                List taskTypeList = taskTypes.Split(',').ToList();
                List basicCodeList = db.Queryable().Where(s => s.FType == (int)Constant.BasicCode.变更试验号事项
                && s.FState == 1 && taskTypeList.Contains(s.FValue)).ToList();
                PropertyInfo[] basicCodeProps = typeof(TBasicCode).GetProperties();
                for (int i = 0; i < taskTypeList.Count; i++)
                {
                    TBasicCode basicCode = basicCodeList.Find(s => s.FValue == taskTypeList[i]);
                    if (basicCode == null) continue;
                    string[] temps = basicCode.FRemark.Split('_');
                    int temp0 = int.Parse(temps[0]), funcType = -1;
                    string taskDesc = basicCode.F1;
                    List funcVal = new List();
                    switch (temp0)
                    {
                        case (int)Constant.BasicCode.事项权限:
                            funcType = (int)Constant.RoleType.事项权限;
                            funcVal.Add(temps[1]);
                            break;
                        case (int)Constant.BasicCode.物料视图编辑:
                            funcType = (int)Constant.RoleType.物料视图编辑;
                            string tType = temps[1];
                            funcVal = db.Queryable().Where(s => s.FType == (int)Constant.BasicCode.物料视图编辑 &&
                            s.F1 == tType && s.FState == 1).Select(s => s.FValue).ToList();
                            break;
                    }
                    if (funcType > 0)
                    {
                        //List users = db.Queryable((a, b, c) => new JoinQueryInfos(JoinType.Left, a.FRoleID == b.FRoleID,
                        //     JoinType.Left, a.FID == int.Parse(c.FUserID)))
                        //          .Where((a, b) => a.FState == 1 && a.FDeleted != 1 && b.FType == funcType && funcVal.Contains(b.FFunctionID.ToString()))
                        //          .Where(string.IsNullOrEmpty(factoryId) ? "1=1" : string.Format("c.FFactoryID in({0})", factoryId))
                        //          .GroupBy("a.FID,c.FFactoryID,a.FName,a.FUser").Select("a.FID,c.FFactoryID,a.FName,a.FUser").ToList();
                        List users = db.Queryable((a, b, c) => new JoinQueryInfos(
                            JoinType.Left, a.FUserID.Equals(b.FID.ToString()),
                            JoinType.Left, a.FRole.Equals(c.FRoleID.ToString())
                            ))
                            .Where((a, b, c) => factoryId.Contains(a.FFactoryID))
                            .Where((a, b, c) => b.FState == 1 && b.FDeleted != 1)
                            .Where((a, b, c) => c.FType == funcType && funcVal.Contains(c.FFunctionID.ToString()))
                            .GroupBy("b.FID, a.FFactoryID, b.FName, b.FUser")
                            .Select("b.FID, cast(a.FFactoryID as int), b.FName, b.FUser")
                            .ToList();
                        if (users.Count() > 0)
                        {
                            if (string.IsNullOrEmpty(factoryId))
                            {
                                TFS_HalfMaterialTask newTask = new TFS_HalfMaterialTask()
                                {
                                    FName = basicCode.FName,
                                    FDesc = taskDesc,
                                    FTeamID = teamId,
                                    FEditUser = userId,
                                    FFactoryID = -1,
                                    FAddDate = DateTime.Now,
                                    FCanEdit = 1,
                                    FEditDate = DateTime.Now,
                                    FType = int.Parse(basicCode.FValue),
                                    FUserID = string.Join(",", users.GroupBy(ss => ss.FID).Select(sss => sss.Key)),
                                    FUserName = string.Join("、", users.GroupBy(ss => ss.FName).Select(sss => sss.Key)),
                                    FState = 1
                                };
                                TFS_HalfMaterialTask oldTask = db.Queryable().Where(s => s.FTeamID == teamId && s.FType == newTask.FType
                                && s.FFactoryID == newTask.FFactoryID).First();
                                if (oldTask == null)
                                {
                                    insertList.Add(newTask);
                                    messageList.Add(new MessageDto()
                                    {
                                        message = newTask.FDesc,
                                        userId = string.Join(",", users.GroupBy(ss => ss.FDockID).Select(sss => sss.Key))
                                    });
                                }
                                else
                                {
                                    oldTask.FUserID = newTask.FUserID;
                                    updateList.Add(oldTask);
                                }
                            }
                            else
                            {
                                foreach (var factory in users.GroupBy(s => s.FFactoryID))
                                {
                                    TFS_HalfMaterialTask newTask = new TFS_HalfMaterialTask()
                                    {
                                        FName = basicCode.FName,
                                        FDesc = taskDesc,
                                        FTeamID = teamId,
                                        FEditUser = userId,
                                        FFactoryID = factory.Key,
                                        FAddDate = DateTime.Now,
                                        FCanEdit = 1,
                                        FEditDate = DateTime.Now,
                                        FType = int.Parse(basicCode.FValue),
                                        FUserID = string.Join(",", factory.GroupBy(ss => ss.FID).Select(sss => sss.Key)),
                                        FUserName = string.Join("、", factory.GroupBy(ss => ss.FName).Select(sss => sss.Key)),
                                        FState = 1
                                    };
                                    TFS_HalfMaterialTask oldTask = db.Queryable().Where(s => s.FTeamID == teamId && s.FType == newTask.FType
                                    && s.FFactoryID == factory.Key).First();
                                    if (oldTask == null)
                                    {
                                        insertList.Add(newTask);
                                        messageList.Add(new MessageDto()
                                        {
                                            message = newTask.FDesc,
                                            userId = string.Join(",", factory.GroupBy(ss => ss.FDockID).Select(sss => sss.Key))
                                        });
                                    }
                                    else
                                    {
                                        oldTask.FUserID = newTask.FUserID;
                                        updateList.Add(oldTask);
                                    }
                                }
                            }
                        }
                    }
                }
                if (insertList.Count() > 0)
                {
                    db.Insertable(insertList).ExecuteCommand();
                    SendWeChatMessage(messageList);
                }
                if (updateList.Count() > 0) db.Updateable(updateList).ExecuteCommand();
            }
            catch (Exception ex)
            {
                if (onceMore)
                {
                    CreateTaskData(teamId, userId, taskTypes, factoryId, false);
                }
                else
                {
                    insertList.AddRange(updateList);
                    ExceptionHelper.AddSystemJournal(null, insertList, ex.Message, userId, "TeamworkBll.CreateTaskData");
                }
            }
        }
        /// 
        /// 发送微信消息
        ///  
        public static void SendWeChatMessage(List messageList)
        {
            if (!AppSettingsHelper.GetAppSettingVal("SendWeChatMsg").Equals("1")) return;
            WeChatMsg.SendPLMMsgInterface ws = new WeChatMsg.SendPLMMsgInterface();
            string tempResult = "";
            foreach (MessageDto msg in messageList)
            {
                foreach (string userId in msg.userId.Split(','))
                {
                    try
                    {
                        tempResult = ws.SendMsg(userId, msg.message, "FMC");
                    }
                    catch (Exception)
                    {
                        ExceptionHelper.AddSystemJournal(null, msg, tempResult, -1, "BaseController.SendWeChatMessage");
                    }
                }
            }
        }
        /// 
        /// 事项变更SQL语句
        ///  
        public static string GetTaskSql(int taskId, int taskState, int teamId = -1, int taskType = -1, int taskEdit = -1, string sqlAppend = "")
        {
            string updateSql = string.Format("a.FState={0}", taskState);
            if (taskState == 2) updateSql += ",FFinishDate=isnull(a.FFinishDate, getdate())";
            if (taskEdit > 0) updateSql += string.Format(",a.FCanEdit={0}", taskEdit);
            List whereSql = new List();
            if (taskId > 0) whereSql.Add(string.Format("a.FID={0}", taskId));
            if (teamId > 0) whereSql.Add(string.Format("a.FTeamID={0}", teamId));
            if (taskType > 0) whereSql.Add(string.Format("a.FType={0}", taskType));
            if (whereSql.Count == 0 && string.IsNullOrEmpty(sqlAppend)) return "";
            if (!string.IsNullOrEmpty(sqlAppend) && whereSql.Count > 0) sqlAppend = " and " + sqlAppend;
            return string.Format(@"update a set {0} from TFS_Task a where {1} {2};", updateSql, string.Join(" and ", whereSql), sqlAppend);
        }
        /// 
        /// 试验号更换事项变更SQL语句
        ///  
        public static string GetTaskSql2(int taskId, int taskState, int teamId = -1, int taskType = -1, int taskEdit = -1, string sqlAppend = "")
        {
            string updateSql = string.Format("a.FState={0}", taskState);
            if (taskState == 2) updateSql += ",FFinishDate=isnull(a.FFinishDate, getdate())";
            if (taskEdit > 0) updateSql += string.Format(",a.FCanEdit={0}", taskEdit);
            List whereSql = new List();
            if (taskId > 0) whereSql.Add(string.Format("a.FID={0}", taskId));
            if (teamId > 0) whereSql.Add(string.Format("a.FTeamID={0}", teamId));
            if (taskType > 0) whereSql.Add(string.Format("a.FType={0}", taskType));
            if (whereSql.Count == 0 && string.IsNullOrEmpty(sqlAppend)) return "";
            if (!string.IsNullOrEmpty(sqlAppend) && whereSql.Count > 0) sqlAppend = " and " + sqlAppend;
            return string.Format(@"update a set {0} from TFS_HalfMaterialTask a where {1} {2};", updateSql, string.Join(" and ", whereSql), sqlAppend);
        }
        /// 
        /// 流程变更SQL语句
        ///  
        public static string GetProcessSql(int teamId, int proType, string viewDesc, int proState, string sqlAppend = "")
        {
            string timeSql = proState.ToString();
            if (proState == 1) timeSql += ",FStartDate=getdate()";
            else if (proState == 2) timeSql += ",FFinishDate=getdate()";
            return string.Format(@"update a set a.FDesc=(select {2} from TBasicCode where FType=34 and FValue={1}),
            FState={3} from TFS_FTeamProcess a where a.FTeamID={0} {5} and FType={1} {4};", teamId,
            proType, viewDesc, timeSql, sqlAppend, proState > 0 ? ("and FState<" + proState) : "");
        }
        /// 
        /// 试验号流程变更SQL语句
        ///  
        public static string GetProcessSql2(int teamId, int proType, string viewDesc, int proState, string sqlAppend = "")
        {
            string timeSql = proState.ToString();
            if (proState == 1) timeSql += ",FStartDate=getdate()";
            else if (proState == 2) timeSql += ",FFinishDate=getdate()";
            return string.Format(@"update a set a.FDesc=(select {2} from TBasicCode where FType=34 and FValue={1}),
            FState={3} from TFS_HalfMaterialFTeamProcess a where a.FTeamID={0} {5} and FType={1} {4};", teamId,
            proType, viewDesc, timeSql, sqlAppend, proState > 0 ? ("and FState<" + proState) : "");
        }
    }
}