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 HalfMaterialTaskBll
    {
        /// <summary>
        /// 获取任务列表
        /// </summary>
        public List<object> GetList(TaskQuery tq, out int totalNumber)
        {
            totalNumber = 0;
            var db = AppSettingsHelper.GetSqlSugar();
            return db.Queryable<TFS_HalfMaterialTask, TFS_HalfMaterialFTeamwork, TBasicCode, TUser>((a, b, c, d) => new JoinQueryInfos(JoinType.Inner, a.FTeamID == b.FID,
                    JoinType.Inner, c.FType == 46 && a.FType == int.Parse(c.FValue), JoinType.Left, a.FEditUser == d.FID))
                // 事项状态
                .WhereIF(tq.FState > 0 && tq.FState != 99, (a, b) => a.FState == tq.FState)
                // 事项状态
                .WhereIF(tq.FState == 99, (a, b) => a.FState <= 1)
                .WhereIF(tq.FTestCode != null,(a,b)=>b.FNewTestCode.Contains(tq.FTestCode))
                // 销售号
                .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<object>("a.*,b.FNewTestCode,b.FVersionCode,a.FType as 'FormulaType',b.FSaleCode,b.FFormulaTestCode as FTestCode,b.FMdmCode,b.FFormulaName,b.FMaterialHalfIDs,cast(substring(c.FRemark,4,2)as int)as FViewType,d.FName AS 'FUserName1',(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);
        }



        public int CloseHalfMaterialTask(int teamId, int userId, int type)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_HalfMaterialTask> taskList = db.Queryable<TFS_HalfMaterialTask>().Where(s => s.FType == type && s.FTeamID == teamId).ToList();
            int result = 0;

            if (taskList != null && taskList.Count > 0)
            {
                TFS_HalfMaterialTask 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;
        }

        /// <summary>
        /// 关闭任务当是可以编辑
        /// </summary>
        /// <param name="teamId"></param>
        /// <param name="userId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public int CloseHalfMaterialTask2(int teamId, int userId, int type)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_HalfMaterialTask> taskList = db.Queryable<TFS_HalfMaterialTask>().Where(s => s.FType == type && s.FTeamID == teamId && s.FState == 1).ToList();
            int result = 0;

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

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

                result = db.Updateable(fmt).IgnoreColumns(true).WhereColumns("FID").ExecuteCommand();
            }
            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_HalfMaterialFTeamwork teamwork = db.Queryable<TFS_HalfMaterialFTeamwork>().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.FHalfMaterialTeamID == 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().FHalfMaterialTeamID;
                foreach (var view in viewList)
                {
                    result += db.Updateable<TFS_ViewMaterial>(new { FGroupCode = view.FGroupCode, FEditUser = userId, FEditDate = DateTime.Now })
                        .Where(s => s.FHalfMaterialTeamID == teamId && s.FMaterialID == view.FMaterialID && s.FViewType == view.FViewType).ExecuteCommand();
                }
                string taskSql = GetTaskSql(-1, 2, teamId, (int)Constant.TaskType.组编号申请, 2);
                taskSql += GetProcessSql(teamId, (int)Constant.ProcessType.生成版本, "F3", 2);
                db.Ado.ExecuteCommand(taskSql);
                HalfMaterialTeamworkBll.ChangeTeamProcess(teamId);
                db.CommitTran();
            }
            catch (Exception)
            {
                db.RollbackTran();
            }
            return result;
        }

        /// <summary>
        /// 事项变更SQL语句
        /// </summary>
        private 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_HalfMaterialTask a where {1} {2};", updateSql, string.Join(" and ", whereSql), sqlAppend);
        }

        /// <summary>
        /// 流程变更SQL语句
        /// </summary>
        private 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_HalfMaterialFTeamProcess a where a.FTeamID={0} {5} and FType={1} {4};", teamId,
            proType, viewDesc, timeSql, sqlAppend, proState > 0 ? ("and FState<" + proState) : "");
        }
    }
}
