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
    {
        /// <summary>
        /// 修改数据信息
        /// </summary>
        public static int UpdateDataModel(Dictionary<string, object> updateModel, string tableName)
        {
            return AppSettingsHelper.GetSqlSugar().Updateable(updateModel).AS(tableName).WhereColumns("FID").ExecuteCommand();
        }

        /// <summary>
        /// 修改数据信息
        /// </summary>
        public static int UpdateDataModel(dynamic updateModel)
        {
            return AppSettingsHelper.GetSqlSugar().Updateable(updateModel).ExecuteCommand();
        }

        /// <summary>
        /// 删除数据信息
        /// </summary>
        public int DeleteDataById(Dictionary<string, object> 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<object>().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;
        }

        /// <summary>
        /// 删除数据信息
        /// </summary>
        public int DeleteDataById(int dataId, string tableName, bool realDel = false)
        {
            Dictionary<string, object> updateModel = new Dictionary<string, object>();
            updateModel.Add("FID", dataId);
            return DeleteDataById(updateModel, tableName, realDel);
        }

        /// <summary>
        /// 新增数据信息
        /// </summary>
        public int InsertDataModel(Dictionary<string, object> insertData, string tableName)
        {
            var model= AppSettingsHelper.GetSqlSugar().Insertable(insertData).AS(tableName).ExecuteReturnIdentity();
            return model;
        }

        /// <summary>
        /// 公共列表接口(前缀未Or_的为或条件检索，后缀为ID的是多唯一编号检索)
        /// </summary>
        public object GetPageList<T>(Dictionary<string, object> updateModel, out int totalCount, string selectKey = null, string orderBy = "FID desc")
        {
            totalCount = 0;
            int pageIndex = 1, pageSize = 15;
            List<string> paramName = new List<string>() { "FDeleted!=1" };
            List<SugarParameter> paramVal = new List<SugarParameter>();
            if (updateModel != null && updateModel.Count > 0)
            {
                List<string> orList = new List<string>();
                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<T>().Where(string.Join(" and ", paramName), paramVal).OrderBy(orderBy);
            if (!string.IsNullOrEmpty(selectKey)) temp = temp.Select(selectKey);
            return temp.ToPageList(pageIndex, pageSize, ref totalCount);
        }

        /// <summary>
        /// 根据类型获取字段对应关系
        /// </summary>
        public List<TFS_FieldInfo> GetFileInfoList(int typeId)
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<TFS_FieldInfo>().Where(s => s.FDeleted != (int)Constant.DeleteCode.已删除
            && s.FType == typeId).OrderBy(s => s.FOrder).ToList();
        }

        /// <summary>
        /// 根据键获取设置值
        /// </summary>
        public string GetSettingByKey(string setKey)
        {
            TFS_Setting setting = AppSettingsHelper.GetSqlSugar().Queryable<TFS_Setting>().Where(s => s.FState == 1 && s.FKey == setKey)
                .OrderBy(s => s.FID, OrderByType.Desc).First();
            if (setting != null) return setting.FValue;
            return "";
        }

        /// <summary>
        /// 根据键获取数据
        /// </summary>
        public static T GetTempModel<T>(int dataId, string keys = "")
        {
            if (string.IsNullOrEmpty(keys))
                return AppSettingsHelper.GetSqlSugar().Queryable<T>().Where("FID=" + dataId).First();
            return AppSettingsHelper.GetSqlSugar().Queryable<T>().Where("FID=" + dataId).Select(keys).First();
        }

        /// <summary>
        /// 根据键获取数据
        /// </summary>
        public static T GetTempModel<T>(string where, string keys = "")
        {
            if (string.IsNullOrEmpty(keys))
                return AppSettingsHelper.GetSqlSugar().Queryable<T>().Where(where).First();
            return AppSettingsHelper.GetSqlSugar().Queryable<T>().Where(where).Select(keys).First();
        }

        /// <summary>
        /// 根据键获取数据
        /// </summary>
        public Dictionary<string, object> GetTempDict<T>(int dataId, string keys = "")
        {
            if (string.IsNullOrEmpty(keys))
                return AppSettingsHelper.GetSqlSugar().Queryable<T>().Where("FID=" + dataId).ToDictionaryList().FirstOrDefault();
            return AppSettingsHelper.GetSqlSugar().Queryable<T>().Where("FID=" + dataId).Select<dynamic>(keys).ToDictionaryList().FirstOrDefault();
        }

        /// <summary>
        /// 事项变更修改流程进度
        /// proProgress（事项文字类型）：对应F+proProgress
        /// proState（事项状态）：0未开始，1进行中，2已完成
        /// </summary>
        public void UpdateTeamProcess(int teamId, int proType, int proProgress, int proState = -1, string appWhere = "1=1")
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            TBasicCode basicCode = db.Queryable<TBasicCode>().Where(s => s.FValue == proType.ToString()
            && s.FType == (int)Constant.BasicCode.流程类型).First();
            if (basicCode != null)
            {
                Dictionary<string, object> updateModel = new Dictionary<string, object>();
                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<TFS_FTeamProcess>(updateModel).Where(s => s.FTeamID == teamId && s.FType == proType)
                    .Where(appWhere).ExecuteCommand();
            }
        }

        /// <summary>
        /// 试验号变更修改流程进度
        /// </summary>
        /// <param name="teamId"></param>
        /// <param name="proType"></param>
        /// <param name="proProgress"></param>
        /// <param name="proState"></param>
        /// <param name="appWhere"></param>
        public void UpdateTeamProcess2(int teamId, int proType, int proProgress, int proState = -1, string appWhere = "1=1")
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            TBasicCode basicCode = db.Queryable<TBasicCode>().Where(s => s.FValue == proType.ToString()
            && s.FType == (int)Constant.BasicCode.变更试验号流程).First();
            if (basicCode != null)
            {
                Dictionary<string, object> updateModel = new Dictionary<string, object>();
                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<TFS_HalfMaterialFTeamProcess>(updateModel).Where(s => s.FTeamID == teamId && s.FType == proType)
                    .Where(appWhere).ExecuteCommand();
            }
        }

        /// <summary>
        /// 创建数据库表
        /// </summary>
        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);
        }

        /// <summary>
        /// 创建事项
        /// </summary>
        public static void CreateTaskData(int teamId, int userId, string taskTypes, string factoryId = "", bool onceMore = true, SqlSugarClient db = null)
        {
            List<TFS_Task> insertList = new List<TFS_Task>();
            List<TFS_Task> updateList = new List<TFS_Task>();
            List<MessageDto> messageList = new List<MessageDto>();
            try
            {
                if (db == null) db = AppSettingsHelper.GetSqlSugar();

                List<string> taskTypeList = taskTypes.Split(',').ToList();

                if (string.IsNullOrEmpty(factoryId))
                {
                    TFS_FTeamwork team = db.Queryable<TFS_FTeamwork>().Where(t => t.FID == teamId).First();
                    if (team != null) factoryId = team.FCreateFactoryID.ToString();
                }

                List<TBasicCode> basicCodeList = db.Queryable<TBasicCode>().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<string> funcVal = new List<string>();
                    string funcTypes = "4, 5";
                    switch (temp0)
                    {
                        case (int)Constant.BasicCode.事项权限:
                            funcType = (int)Constant.RoleType.事项权限;
                            funcTypes = "2";
                            funcVal.Add(temps[1]);
                            break;
                        case (int)Constant.BasicCode.物料视图编辑:
                            funcType = (int)Constant.RoleType.物料视图编辑;
                            funcTypes = "4, 5";
                            string tType = temps[1];
                            funcVal = db.Queryable<TBasicCode>().Where(s => s.FType == (int)Constant.BasicCode.物料视图编辑 &&
                            s.F1 == tType && s.FState == 1).Select(s => s.FValue).ToList();
                            break;
                    }
                    if (funcType > 0)
                    {
                        //List<TUser> users = db.Queryable<TUser, TRole_Right, FPower>((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<TUser>("a.FID,cast(c.FFactoryID as int),a.FName,a.FUser").ToList();

                        List<TUser> users = db.Queryable <FPower, TUser, TRole_Right>((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()))
                            .Where((a, b, c) => funcTypes.Contains(c.FType.ToString()) && funcVal.Contains(c.FFunctionID.ToString()))
                            .GroupBy("b.FID, a.FFactoryID, b.FName, b.FUser")
                            .Select<TUser>("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<TFS_Task>().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<TFS_Task>().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<string> funcVal = db.Queryable<TBasicCode>().Where(s => s.FType == (int)Constant.BasicCode.物料视图编辑 && s.F1 == tType && s.FState == 1).Select(s => s.FValue).ToList();
                List<TUser> users = db.Queryable<TUser, TRole_Right>((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<TUser>("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;
        }

        /// <summary>
        /// 更换试验号流程创建事项
        /// </summary>
        public static void CreateTaskData2(int teamId, int userId, string taskTypes, string factoryId = "", bool onceMore = true, SqlSugarClient db = null)
        {
            List<TFS_HalfMaterialTask> insertList = new List<TFS_HalfMaterialTask>();
            List<TFS_HalfMaterialTask> updateList = new List<TFS_HalfMaterialTask>();
            List<MessageDto> messageList = new List<MessageDto>();
            try
            {
                if (db == null) db = AppSettingsHelper.GetSqlSugar();

                if (string.IsNullOrEmpty(factoryId))
                {
                    TFS_HalfMaterialFTeamwork team = db.Queryable<TFS_HalfMaterialFTeamwork>().Where(t => t.FID == teamId).First();
                    if (team != null) factoryId = team.FCreateFactoryID.ToString();
                }


                List<string> taskTypeList = taskTypes.Split(',').ToList();

                List<TBasicCode> basicCodeList = db.Queryable<TBasicCode>().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<string> funcVal = new List<string>();
                    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<TBasicCode>().Where(s => s.FType == (int)Constant.BasicCode.物料视图编辑 &&
                            s.F1 == tType && s.FState == 1).Select(s => s.FValue).ToList();
                            break;
                    }
                    if (funcType > 0)
                    {
                        //List<TUser> users = db.Queryable<TUser, TRole_Right, FPower>((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<TUser>("a.FID,c.FFactoryID,a.FName,a.FUser").ToList();

                        List<TUser> users = db.Queryable<FPower, TUser, TRole_Right>((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<TUser>("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<TFS_HalfMaterialTask>().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<TFS_HalfMaterialTask>().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");
                }
            }
        }

        /// <summary>
        /// 发送微信消息
        /// </summary>
        public static void SendWeChatMessage(List<MessageDto> 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");
                    }
                }
            }
        }

        /// <summary>
        /// 事项变更SQL语句
        /// </summary>
        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<string> whereSql = new List<string>();
            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);
        }

        /// <summary>
        /// 试验号更换事项变更SQL语句
        /// </summary>
        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<string> whereSql = new List<string>();
            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);
        }

        /// <summary>
        /// 流程变更SQL语句
        /// </summary>
        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) : "");
        }


        /// <summary>
        /// 试验号流程变更SQL语句
        /// </summary>
        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) : "");
        }
    }
}
