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

namespace FactorySystemBll
{
    public class TaskBll
    {
        /// <summary>
        /// 获取任务列表
        /// </summary>
        public List<TaskRow> GetList(TaskQuery tq, out int totalNumber)
        {
            totalNumber = 0;
            var db = AppSettingsHelper.GetSqlSugar();
            return db.Queryable<TFS_Task, TFS_FTeamwork, TBasicCode>((a, b, c) => new JoinQueryInfos(JoinType.Inner, a.FTeamID == b.FID,
                    JoinType.Inner, c.FType == 33 && a.FType == int.Parse(c.FValue)))
                // 事项状态
                .WhereIF(tq.FState > 0 && tq.FState != 99, (a, b) => a.FState == tq.FState)
                // 事项状态
                .WhereIF(tq.FState == 99, (a, b) => a.FState <= 1)
                // 销售号
                .WhereIF(tq.FSaleCode != null, (a, b) => b.FSaleCode.Contains(tq.FSaleCode))
                // 当前流程
                .WhereIF(tq.FType > 0, (a, b) => a.FType == tq.FType)
                // 发起时间1
                .WhereIF(tq.FDateRange != null && tq.FDateRange[0] != "", (a, b) => a.FAddDate >= DateTime.Parse(tq.FDateRange[0]))
                .WhereIF(tq.FDateRange != null && tq.FDateRange[1] != "", (a, b) => a.FAddDate <= DateTime.Parse(tq.FDateRange[1]))
                // 责任人
                .WhereIF(tq.FUserID != null, a => (',' + a.FUserID + ',').Contains(',' + tq.FUserID + ','))
                // 协同
                .WhereIF(tq.FTeamID > 0, a => a.FTeamID == tq.FTeamID).OrderBy((a, b, c) => a.FID, OrderByType.Desc)
                .Select<TaskRow>("a.*,b.FSaleCode,b.FFormulaTestCode as FTestCode,b.FMdmCode,b.FFormulaName,b.FMaterialHalfIDs,cast(substring(c.FRemark,4,2)as int)as FViewType,(case when b.FBomJson IS NULL then 0 when cast(b.FBomJson as nvarchar) = '' then 0 else 1 end) as FHasBomJson,b.FBomJson")
                .ToPageList(tq.FPageIndex, tq.FPageSize, ref totalNumber);
        }

        /// <summary>
        /// 物料组复核
        /// </summary>
        public int ReviewMaterialGroup(Dictionary<string, object> inParam, int userId)
        {
            int result = 0;
            int teamId = int.Parse(inParam["FTeamID"].ToString());
            int taskId = int.Parse(inParam["FTaskID"].ToString());
            List<TFS_ViewMaterial> viewList = JsonConvert.DeserializeObject<List<TFS_ViewMaterial>>(inParam["FList"].ToString());
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            if (viewList.Count > 0)
            {
                foreach (var view in viewList)
                {
                    result += db.Updateable<TFS_ViewMaterial>(new { FBaseMaterialGroup = view.FBaseMaterialGroup })
                        .Where(s => s.FID == view.FID && s.FTeamID == teamId && s.FViewType == (int)Constant.ViewType.成品视图)
                        .ExecuteCommand();
                }
            }
            string taskSql = BaseBll.GetTaskSql(taskId, 2, teamId, (int)Constant.TaskType.成品视图物料组复核, 1);
            if (!string.IsNullOrEmpty(taskSql))
            {
                taskSql += BaseBll.GetProcessSql(teamId, (int)Constant.ProcessType.流程完成, "F2", 1);
                result += db.Ado.ExecuteCommand(taskSql);
                TeamworkBll.ChangeTeamProcess(teamId, db);
                BaseBll.CreateTaskData(teamId, userId, "13");
            }
            return result;
        }

        /// <summary>
        /// 组编号申请获取视图
        /// </summary>
        public List<TFS_ViewMaterial> GetDockGroupView(Dictionary<string, object> inParam)
        {
            int teamId = int.Parse(inParam["FTeamID"].ToString());
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            TFS_FTeamwork teamwork = db.Queryable<TFS_FTeamwork>().Where(s => s.FID == teamId).First();
            List<int> viewType = new List<int>
            {
                (int)Constant.ViewType.半成品视图,
                (int)Constant.ViewType.中间品视图,
                (int)Constant.ViewType.香基视图
            };
            return db.Queryable<TFS_ViewMaterial>().Where(s => s.FTeamID == teamId && s.FFactoryID == teamwork.FProdFactoryID
            && SqlFunc.IsNullOrEmpty(s.FGroupCode) && viewType.Contains(s.FViewType)).ToList();
        }

        /// <summary>
        /// 组编号申请处理视图
        /// </summary>
        public int DockMaterialGroup(List<TFS_ViewMaterial> viewList, int userId)
        {
            int result = 0;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            db.BeginTran();
            try
            {
                int teamId = viewList.First().FTeamID;
                foreach (var view in viewList)
                {
                    result += db.Updateable<TFS_ViewMaterial>(new { FGroupCode = view.FGroupCode, FEditUser = userId, FEditDate = DateTime.Now })
                        .Where(s => s.FTeamID == teamId && s.FMaterialID == view.FMaterialID && s.FViewType == view.FViewType).ExecuteCommand();
                }
                string taskSql = BaseBll.GetTaskSql(-1, 2, teamId, (int)Constant.TaskType.组编号申请, 2);
                taskSql += BaseBll.GetProcessSql(teamId, (int)Constant.ProcessType.生成版本, "F3", 2);
                db.Ado.ExecuteCommand(taskSql);
                TeamworkBll.ChangeTeamProcess(viewList.First().FTeamID, db);
                db.CommitTran();
            }
            catch (Exception)
            {
                db.RollbackTran();
            }
            return result;
        }

        /// <summary>
        /// 确认流程完成
        /// </summary>
        public int SureTeamWork(int teamId)
        {
            return AppSettingsHelper.GetSqlSugar().Ado.ExecuteCommand(string.Format(@"
            if(select count(1) from TFS_Task where FTeamID={0} and FState!=2 and FType!=13)=0
            begin
                update TFS_Task set FCanEdit=2 where FCanEdit!=2 and FTeamID={0};
                update TFS_Task set FState=2,FFinishDate=getdate() where FState!=2 and FTeamID={0};
                update TFS_FTeamProcess set FState=2,FFinishDate=getdate() where FState!=2 and FTeamID={0};
                update TFS_FTeamwork set FProgress='100' where FID={0};
            end", teamId));
        }

        /// <summary>
        /// 根据事项状态，进行下一步操作
        /// </summary>
        public void CheckTeamProcess(int teamId, int taskType, int userId)
        {
            string strSql = "";
            int stateOk = 2;//完成状态
            switch (taskType)
            {
                case (int)Constant.TaskType.新原料视图:
                    strSql = string.Format(@"update TFS_FTeamProcess set FState={1} where FType={3} and FTeamID={0} and 
                    (select count(1) from TFS_Task where FTeamID={0} and FType={2} and FState!={1})=0 and FState!={1};",
                    teamId, stateOk, taskType, (int)Constant.ProcessType.新原料视图);
                    break;
                case (int)Constant.TaskType.新包材视图:
                    strSql = string.Format(@"update TFS_FTeamProcess set FState={1} where FType={3} and FTeamID={0} and 
                    (select count(1) from TFS_Task where FTeamID={0} and FType={2} and FState!={1})=0 and FState!={1};",
                    teamId, stateOk, taskType, (int)Constant.ProcessType.组装BOM包含新包材);
                    break;
                case (int)Constant.TaskType.成品视图:
                case (int)Constant.TaskType.成品视图物料组复核:
                    string taskType2 = "3,12";
                    strSql = string.Format(@"update TFS_FTeamProcess set FState={1} where FType={3} and FTeamID={0} and 
                    (select count(1) from TFS_Task where FTeamID={0} and FType in ({2}) and FState!={1})=0 and FState!={1};",
                    teamId, stateOk, taskType2, (int)Constant.ProcessType.成品视图);
                    break;
                case (int)Constant.TaskType.新半成品视图:
                case (int)Constant.TaskType.新中间品视图:
                case (int)Constant.TaskType.新香基视图:
                    string taskType1 = "4,5,6";
                    strSql = string.Format(@"update TFS_FTeamProcess set FState={1} where FType={3} and FTeamID={0} and 
                    (select count(1) from TFS_Task where FTeamID={0} and FType in ({2}) and FState!={1})=0 and FState!={1};",
                    teamId, stateOk, taskType1, (int)Constant.ProcessType.新半成品中间品香基);
                    break;
                case (int)Constant.TaskType.组编号申请:
                    strSql += BaseBll.GetProcessSql(teamId, (int)Constant.ProcessType.生成版本, "F3", 2);
                    break;
                case (int)Constant.TaskType.流程确认完成:
                    //事项设置不可修改、协同进度100%、流程设置完成
                    strSql += string.Format("update TFS_Task set FCanEdit=0 where FTeamID={0};", teamId);
                    strSql += string.Format("update TFS_FTeamwork set FProgress='100' where FID={0};", teamId);
                    strSql += BaseBll.GetProcessSql(teamId, (int)Constant.ProcessType.流程完成, "F3", 2);
                    break;
            }

            //2022-10要求新增配方进度完成（视图全部完成）
            strSql += string.Format(@"update TFS_FTeamProcess set FState={1} where FType={3} and FTeamID={0} and 
            (select count(1) from TFS_Task where FTeamID={0} and FType in ({2}) and FState!={1})=0 and FState!={1};",
            teamId, stateOk, "3,4,5,6,7,11", (int)Constant.ProcessType.配方视图);

            if (!string.IsNullOrEmpty(strSql)) strSql += ";";

            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();

            //若流程除了最后个都完成
            if (db.Queryable<TFS_FTeamProcess>().Where(s => s.FTeamID == teamId && s.FState != stateOk
            && s.FType != (int)Constant.ProcessType.流程完成).Count() == 0)
            {
                strSql += BaseBll.GetProcessSql(teamId, (int)Constant.ProcessType.流程完成, "F2", 1);
                BaseBll.CreateTaskData(teamId, userId, "13");
            }
            db.Ado.ExecuteCommand(strSql);
            //更改协同进度
            TeamworkBll.ChangeTeamProcess(teamId);
        }
    }
}
