using DeviceRepair.Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;

namespace DeviceRepair.DataAccess
{
    /// <summary>
    /// 设备维修
    /// </summary>
    public class MaintenanceAccess : DbContext<DeviceWarrantyRequestForm>
    {
        private static MaintenanceAccess manager;
        public static MaintenanceAccess Instance
        {
            get
            {
                if (manager == null)
                    manager = new MaintenanceAccess();
                return manager;
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public APIResponseData GetDatas(DeviceWarrantyRequestFormFilter FilterInfo)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"获取数据失败！" };
            try
            {
                db.ChangeDatabase("main");
                var exp = Expressionable.Create<DeviceWarrantyRequestForm>();
                if (FilterInfo != null)
                {
                    //exp.AndIF(!string.IsNullOrWhiteSpace(FilterInfo.EquipmentID), x => x.EquipmentID.Equals(FilterInfo.EquipmentID, StringComparison.CurrentCultureIgnoreCase));
                    //exp.AndIF(FilterInfo.StartTime.HasValue, x => x.CreatOn >= FilterInfo.StartTime.Value);
                    //exp.AndIF(FilterInfo.EndTime.HasValue, x => x.CreatOn <= FilterInfo.EndTime.Value);
                    //exp.AndIF(FilterInfo.Status == DeviceWarrantyRequestFormStatus.AwaitingRepair,
                    //    x => SqlFunc.Subqueryable<DeviceWarrantyRequestMaintaionInfo>().Where(s => s.FormID == x.AutoID).NotAny());
                    //exp.AndIF(FilterInfo.Status == DeviceWarrantyRequestFormStatus.AwaitingApproval,
                    //   x => SqlFunc.Subqueryable<DeviceWarrantyRequestMaintaionInfo>().Where(s => s.FormID == x.AutoID && s.SubmitBy > 0).Any());
                    //exp.AndIF(FilterInfo.Status == DeviceWarrantyRequestFormStatus.BeComplate,
                    //   x => SqlFunc.Subqueryable<DeviceWarrantyRequestMaintaionInfo>().Where(s => s.FormID == x.AutoID && s.SubmitBy > 0 && s.ValidateBy > 0).Any());


                    exp.AndIF(!string.IsNullOrWhiteSpace(FilterInfo.EquipmentID), x => x.EquipmentID.Contains(FilterInfo.EquipmentID));
                    exp.AndIF(FilterInfo.StartTime.HasValue, x => x.CreatOn >= FilterInfo.StartTime.Value);
                    exp.AndIF(FilterInfo.EndTime.HasValue, x => x.CreatOn <= FilterInfo.EndTime.Value);
                    exp.AndIF(FilterInfo.Status == DeviceWarrantyRequestFormStatus.AwaitingRepair,
                        x => SqlFunc.Subqueryable<DeviceWarrantyRequestMaintaionInfo>().Where(s => s.FormID == x.AutoID).NotAny());
                    exp.AndIF(FilterInfo.Status == DeviceWarrantyRequestFormStatus.AwaitingApproval,
                       x => SqlFunc.Subqueryable<DeviceWarrantyRequestMaintaionInfo>().Where(s => s.FormID == x.AutoID && s.SubmitBy > 0).Any());
                    exp.AndIF(FilterInfo.Status == DeviceWarrantyRequestFormStatus.BeComplate,
                       x => SqlFunc.Subqueryable<DeviceWarrantyRequestMaintaionInfo>().Where(s => s.FormID == x.AutoID && s.SubmitBy > 0 && s.ValidateBy > 0).Any());

                    bool isDown = FilterInfo.DownStatus == DeviceRunningStatus.Stop;
                    exp.AndIF(FilterInfo.DownStatus != DeviceRunningStatus.All,
                        x => x.IsDown == isDown);
                }

                List<DeviceWarrantyRequestForm> Datas = CurrentDb.AsQueryable().With(SqlWith.NoLock).Where(exp.ToExpression()).ToList();

                //List<DeviceWarrantyRequestForm> Datas = CurrentDb.AsQueryable().Where(exp.ToExpression()).ToList();

                //int[] pks = Datas.Select(x => x.AutoID).ToArray();
                //Dictionary<int, DeviceWarrantyRequestMaintaionInfo> Maintaions = db.Queryable<DeviceWarrantyRequestMaintaionInfo>()
                //    .With(SqlWith.NoLock)
                //    .Where(x => SqlFunc.ContainsArray(pks, x.FormID)).ToList().ToDictionary(x => x.FormID, x => x);

                //int[] mpks = Maintaions.Select(x => x.Value.AutoID).ToArray();
                //List<DeviceWarrantyRequestAccessoriesInfo> Accessories = db.Queryable<DeviceWarrantyRequestAccessoriesInfo>()
                //    .With(SqlWith.NoLock)
                //    .Where(x => SqlFunc.ContainsArray(mpks, x.MaintaionID)).ToList();

                //foreach (DeviceWarrantyRequestForm item in Datas)
                //{
                //    if (Maintaions.ContainsKey(item.AutoID))
                //    {
                //        item.MaintaionInfo = Maintaions[item.AutoID];
                //        if (Accessories.Any(x => x.MaintaionID == item.MaintaionInfo.AutoID))
                //        {
                //            item.MaintaionInfo.Accessories = Accessories.Where(x => x.MaintaionID == item.MaintaionInfo.AutoID)?.ToList();
                //        }
                //    }
                //}

                apiResponseData.Code = 1;
                apiResponseData.Data = Datas;
                apiResponseData.Message = "";
            }
            catch (SqlSugarException e)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 设备维修
        /// </summary>
        /// <param name="Entity"></param>
        /// <returns></returns>
        public APIResponseData DeviceMaintion(DeviceWarrantyRequestMaintaionInfo Entity, List<DeviceWarrantyRequestAccessoriesInfo> AccessoriesItems, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"数据插入失败！" };
            try
            {
                if (Entity == null)
                {
                    throw new Exception("待插入的数据库对象不能为空！");
                }

                DateTime CurrentTime = DateTime.Now;

                db.ChangeDatabase("main");
                db.BeginTran();

                if (Entity.AutoID > 0)
                {
                    /// 修改
                    Entity.ModifyBy = Operation.Operator;
                    Entity.ModifyOn = CurrentTime;
                }
                else
                {
                    /// 新增
                    Entity.CreatOn = CurrentTime;
                    Entity.CreateBy = Operation.Operator;
                    Entity.Guid = Guid.NewGuid();
                }


                if (Entity.IsSubmit)
                {
                    Entity.SubmitBy = Operation.Operator;
                    Entity.SubmitOn = CurrentTime;
                }

                DeviceWarrantyRequestMaintaionInfo MaintaionInfo = db.Saveable(Entity).ExecuteReturnEntity();
                if (MaintaionInfo != null)
                {
                    bool IsSuccess = true;
                    if (AccessoriesItems != null)
                    {
                        foreach (var item in AccessoriesItems)
                        {
                            item.Guid = Guid.NewGuid();
                            item.MaintaionID = MaintaionInfo.AutoID;
                            item.CreatBy = Operation.Operator;
                            item.CreatOn = CurrentTime;
                        }

                        IsSuccess = db.Saveable(AccessoriesItems).ExecuteCommand() == AccessoriesItems.Count;
                    }

                    if (IsSuccess)
                    {
                        db.CommitTran();
                        apiResponseData.Code = 1;
                        apiResponseData.Message = string.Empty;
                    }
                }
                else
                {
                    db.RollbackTran();
                }

            }
            catch (SqlSugarException e)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;

                if (((System.Data.SqlClient.SqlException)ex).Number == 2627)
                {
                    apiResponseData.Message = $"当前数据已被处理，请刷新后再试!";
                }
                else
                {
                    apiResponseData.Message = ex.Message;
                }
            }
            return apiResponseData;
        }

        /// <summary>
        /// 停机单新增
        /// </summary>
        /// <param name="Form"></param>
        /// <returns></returns>
        public APIResponseData DeviceDownFormAdd(DeviceWarrantyRequestForm Form, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"数据插入失败！" };
            try
            {
                if (Form == null)
                {
                    throw new Exception("待插入的数据库对象不能为空！");
                }

                DateTime CurrentTime = DateTime.Now;

                db.ChangeDatabase("main");
                db.BeginTran();

                #region  2024年5月21日 会议，确定一个设备，同时能存在多个维修单
                //// 当前设备存在未完成的设备停机单
                //if (db.Queryable<DeviceWarrantyRequestForm>().Any(x =>
                //   x.EquipmentID == Form.EquipmentID &&
                //   (
                //    !SqlFunc.Subqueryable<DeviceWarrantyRequestMaintaionInfo>().Where(s => s.FormID == x.AutoID).Any() ||
                //   SqlFunc.Subqueryable<DeviceWarrantyRequestMaintaionInfo>().Where(s => s.FormID == x.AutoID && (s.SubmitBy == 0 || s.ValidateBy == 0)).Any())
                //))
                //{
                //    throw new Exception("当前设备存在未完成的设备停机单！");
                //} 
                #endregion

                Form.GUID = Guid.NewGuid();
                Form.CreatBy = Operation.Operator;
                Form.CreatorName = Operation.OperatorName;
                Form.CreatOn = CurrentTime;

                if (db.Saveable(Form).ExecuteCommand() > 0)
                {
                    db.CommitTran();
                    apiResponseData.Code = 1;
                    apiResponseData.Message = string.Empty;
                }
                else
                {
                    db.RollbackTran();
                }
            }
            catch (SqlSugarException e)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 停机单 - 评估
        /// </summary>
        /// <param name="AutoID"></param>
        /// <param name="Operation"></param>
        /// <returns></returns>
        public APIResponseData DownFormAssessment(DeviceWarrantyEvaluatorInfo Evaluator, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"数据处理失败！" };
            try
            {
                if (Evaluator.FormID <= 0)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                if (!Operation.OperatorGUID.HasValue || Operation.OperatorGUID == Guid.Empty)
                {
                    throw new Exception("传入的操作人参数无效！");
                }

                DateTime CurrentTime = DateTime.Now;
                db.ChangeDatabase("main");

                DeviceWarrantyRequestForm Entity = db.Queryable<DeviceWarrantyRequestForm>().First(x => x.AutoID == Evaluator.FormID);
                if (Entity == null)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                if (Evaluator.EvaluatorCode.ToUpper() != "QE" && Evaluator.EvaluatorCode.ToUpper() != "PE")
                {
                    throw new Exception($"程序出错，未知的评估编码：{Evaluator.EvaluatorCode.ToUpper()}！");
                }

                Evaluator.CreatorName = Operation.OperatorName;
                Evaluator.CreateBy = Operation.Operator;
                Evaluator.CreatOn = CurrentTime;
                Evaluator.Guid = Guid.NewGuid();

                //switch (AssessmentCode.ToUpper())
                //{
                //    case "QA":
                //        Entity.EvaluatornameQa = Operation.OperatorName;
                //        Entity.EvaluatoronQa = CurrentTime;
                //        Entity.EvaluatorcodeQa = Operation.OperatorGUID;
                //        break;
                //    case "EA":
                //        Entity.EvaluatornameEa = Operation.OperatorName;
                //        Entity.EvaluatoronEa = CurrentTime;
                //        Entity.EvaluatorcodeEa = Operation.OperatorGUID;
                //        break;
                //    case "MT":
                //        Entity.EvaluatornameMt = Operation.OperatorName;
                //        Entity.EvaluatoronMt = CurrentTime;
                //        Entity.EvaluatorcodeMt = Operation.OperatorGUID;
                //        break;
                //    case "TL":
                //        Entity.EvaluatornameTl = Operation.OperatorName;
                //        Entity.EvaluatoronTl = CurrentTime;
                //        Entity.EvaluatorcodeTl = Operation.OperatorGUID;
                //        break;
                //    default:
                //        break;
                //}

                if (db.Insertable(Evaluator).ExecuteCommand() > 0)
                {
                    apiResponseData.Code = 1;
                    apiResponseData.Message = string.Empty;
                }
            }
            catch (SqlSugarException e)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 修改停机单 停机状态
        /// </summary>
        /// <param name="AutoID"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public APIResponseData ChangeDownStatus(int AutoID, bool Status, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"数据处理失败！" };
            try
            {
                if (AutoID <= 0)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                DateTime CurrentTime = DateTime.Now;
                db.ChangeDatabase("main");

                DeviceWarrantyRequestForm Entity = db.Queryable<DeviceWarrantyRequestForm>().First(x => x.AutoID == AutoID);
                if (Entity == null)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                Entity.IsDown = Status;
                if (db.Updateable(Entity).UpdateColumns(it => new { it.IsDown }).ExecuteCommand() > 0)
                {
                    apiResponseData.Code = 1;
                    apiResponseData.Message = string.Empty;
                }
            }
            catch (SqlSugarException e)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 双重验证
        /// </summary>
        /// <param name="t">1：技术人员确认 2：工程师或维修主管确认</param>
        /// <param name="Operation"></param>
        /// <returns></returns>
        public APIResponseData ValidateMaintenance(int AutoID, int t, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"数据处理失败！" };
            try
            {
                if (AutoID <= 0)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                DateTime CurrentTime = DateTime.Now;
                db.ChangeDatabase("main");

                DeviceWarrantyRequestMaintaionInfo Entity = db.Queryable<DeviceWarrantyRequestMaintaionInfo>().First(x => x.FormID == AutoID);
                if (Entity == null)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                if (t == 1)
                {
                    Entity.ValidateBy = Operation.Operator;
                    Entity.ValidateOn = CurrentTime;
                }
                else if (t == 2)
                {
                    Entity.Validate2By = Operation.Operator;
                    Entity.Validate2On = CurrentTime;
                }
                else
                {
                    throw new Exception("传入的确认人岗位错误！");
                }

                if (db.Updateable(Entity).ExecuteCommand() > 0)
                {
                    apiResponseData.Code = 1;
                    apiResponseData.Message = string.Empty;
                }
            }
            catch (SqlSugarException e)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 生产部门 - 设备恢复确认
        /// </summary>
        /// <param name="AutoID"></param>
        /// <param name="Operation"></param>
        /// <returns></returns>
        public APIResponseData DeviceResumptionComfirm(int AutoID, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"数据处理失败！" };
            try
            {
                if (AutoID <= 0)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                DateTime CurrentTime = DateTime.Now;
                db.ChangeDatabase("main");

                DeviceWarrantyRequestForm Entity = db.Queryable<DeviceWarrantyRequestForm>().First(x => x.AutoID == AutoID);
                if (Entity == null)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                if (Entity.MaintaionItems != null && Entity.MaintaionItems.SubmitBy > 0 &&
                    ((Entity.InProduction && Entity.EvaluatorItems?.Count == 2) || !Entity.InProduction) &&
                    ((Entity.MaintaionItems.BeValidate && Entity.MaintaionItems.Validate2By > 0 && Entity.MaintaionItems.ValidateBy > 0) || !Entity.MaintaionItems.BeValidate)
                    && Entity.RestorationConfirmationBy == 0
                    )
                {
                    Entity.RestorationConfirmationOn = CurrentTime;
                    Entity.RestorationConfirmationBy = Operation.Operator;
                    Entity.RestorationConfirmationOnName = Operation.OperatorName;

                    if (db.Updateable(Entity).ExecuteCommand() > 0)
                    {
                        apiResponseData.Code = 1;
                        apiResponseData.Message = string.Empty;
                    }
                }
                else
                {
                    throw new Exception("待处理的停机单状态异常，请重试！");
                }


            }
            catch (SqlSugarException e)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }
    }
}
