using FactorySystemCommon;
using FactorySystemModel.EnumModel;
using FactorySystemModel.RequestModel;
using FactorySystemModel.ResponseModel;
using FactorySystemModel.SqlSugarModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;

namespace FactorySystemBll
{
    public class MaterialTaskBll
    {
        /// <summary>
        /// 获取任务列表
        /// </summary>
        public List<MaterialTaskRow> GetList(MaterialTaskQuery mtq, out int totalNumber)
        {
            totalNumber = 0;
            var db = AppSettingsHelper.GetSqlSugar();
            return db.Queryable<TFS_FMaterialTask, TFS_FMaterialTeamwork, TUser>((a, b, c) => new JoinQueryInfos(JoinType.Inner, a.FMaterialTeamID == b.FID, JoinType.Left, a.FAddUser == c.FID))
                // 事项状态
                .WhereIF(mtq.FState > 0 && mtq.FState != 99, (a, b) => a.FState == mtq.FState)
                // 物料号
                .WhereIF(!string.IsNullOrEmpty(mtq.FMaterialCode), (a, b) => b.FMaterialCode.Equals(mtq.FMaterialCode))
                // 类型
                .WhereIF(mtq.FType >= 0, (a, b) => a.FType == mtq.FType)
                // 发起时间
                .WhereIF(mtq.FDateRange != null && mtq.FDateRange[0] != "", (a, b) => a.FAddDate >= DateTime.Parse(mtq.FDateRange[0]))
                .WhereIF(mtq.FDateRange != null && mtq.FDateRange[1] != "", (a, b) => a.FAddDate <= DateTime.Parse(mtq.FDateRange[1]))
                // 责任人
                .WhereIF(mtq.FUserID != null, (a, b) => (',' + a.FUserID + ',').Contains(',' + mtq.FUserID + ','))
                //// 协同
                //.WhereIF(mtq.FMaterialTeamID > 0, (a, b) => a.FMaterialTeamID == mtq.FMaterialTeamID)
                .OrderBy((a, b) => a.FID, OrderByType.Desc)
                .Select<MaterialTaskRow>("a.*,b.FMaterialName,b.FMaterialCode,b.FTestCode,b.FMaterialType, c.FName as FAddUserName").OrderBy((a) => a.FID, OrderByType.Desc)
                .ToPageList(mtq.FPageIndex, mtq.FPageSize, ref totalNumber);
        }

        public List<TFS_FMaterialTask> GetMaterialTasks(int teamId)
        {
            var db = AppSettingsHelper.GetSqlSugar();
            List<TFS_FMaterialTask> tasks = db.Queryable<TFS_FMaterialTask>().Where(t => t.FMaterialTeamID == teamId).ToList();

            return tasks;
        }

        /// <summary>
        /// 创建物料新增事项
        /// </summary>
        public int CreateMaterialTask(int teamId, int teamworkType, int userId, int type, int factoryId, List<TUser> users)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            int taskId = -1;

            try
            {
                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;
                    materialTask.FTeamworkType = teamworkType;
                    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));

                    if (type == 0)
                    {
                        materialTask.FName = "物料分类";
                        materialTask.FDesc = "物料分类选择";
                    }
                    else if (type == 1)
                    {
                        materialTask.FName = "物料视图";
                        materialTask.FDesc = "物料视图编辑";
                    }
                    else
                    {
                        materialTask.FName = "确认视图";
                        materialTask.FDesc = "物料视图确认";
                    }

                    taskId = db.Insertable(materialTask).IgnoreColumns(true).ExecuteReturnIdentity();
                }
            }
            catch (Exception ex)
            {
                taskId = -1;
            }

            return taskId;
        }

        public int CloseMaterialTask(int teamId, int userId, int type)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_FMaterialTask> taskList = db.Queryable<TFS_FMaterialTask>().Where(s => s.FType == type && s.FMaterialTeamID == teamId && s.FState == 1).ToList();
            int result = 0;

            if (taskList != null && taskList.Count > 0)
            {
                TFS_FMaterialTask fmt = taskList[0];

                // fmt.FCanEdit = 2;
                fmt.FState = 2;
                fmt.FEditUser = userId;
                fmt.FEditDate = DateTime.Now;

                result = db.Updateable(fmt).IgnoreColumns(true).WhereColumns("FID").ExecuteCommand();
            }

            return result;
        }

        public int CloseAllMaterialTask(int teamId, int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_FMaterialTask> taskList = db.Queryable<TFS_FMaterialTask>().Where(s => s.FMaterialTeamID == teamId).ToList();
            int result = 0;

            if (taskList != null && taskList.Count > 0)
            {
                foreach(TFS_FMaterialTask task in taskList)
                {
                    task.FCanEdit = 2;
                    task.FState = 2;
                    task.FEditUser = userId;
                    task.FEditDate = DateTime.Now;

                    result = db.Updateable(task).IgnoreColumns(true).WhereColumns("FID").ExecuteCommand();
                }
            }

            return result;
        }

        /**
         * 20230505 修改权限BUG
         * 获取事项用户，用于判断是否生成路线和事项
         * **/
        public List<TUser> GetTaskUsers(int taskType, string viewType, int factoryId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TUser> users = null;
            string funcType = null;
            List<string> funcVal = null;

            // 物料分类任务 | 物料编辑任务
            if (taskType == 0 || taskType == 1)
            {
                funcType = "4, 5";
                funcVal = db.Queryable<TBasicCode>().Where(s => (s.FType == (int)Constant.BasicCode.物料视图编辑 || s.FType == (int)Constant.BasicCode.物料基础编辑) &&
                    viewType.Equals(s.F1) && // 视图编辑中的物料分类
                    s.FState == 1).Select(s => s.FValue).ToList();
            }
            // 物料确认任务
            else if (taskType == 2)
            {
                funcType = "2";
                funcVal = new List<string> { "7" };
            }

            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.ToString().Contains(a.FFactoryID))
                   .Where((a, b, c) => b.FState == 1 && b.FDeleted != 1)
                   .Where((a, b, c) => funcType.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();

            return users;
        }
    }
}
