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

namespace DeviceRepair.DataAccess
{
    public class TsSFCAccess : DbContext<InspBatchInfo>
    {
        private static readonly Logger log = LogManager.GetCurrentClassLogger();

        private static TsSFCAccess manager;
        public static TsSFCAccess Instance
        {
            get
            {
                if (manager == null)
                    manager = new TsSFCAccess();
                return manager;
            }
        }

        /// <summary>
        /// 判断批次是否存在
        /// </summary>
        /// <param name="Batch"></param>
        /// <returns></returns>
        public APIResponseData GetBatchInfoToStaff(string Batch)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"获取数据失败！" };
            try
            {
                db.ChangeDatabase("data");
                int Count = db.Queryable<InspBatchInfo>().Count(x => x.Batch.ToUpper().Equals(Batch.ToUpper()));

                apiResponseData.Code = 1;
                apiResponseData.Message = "";
                apiResponseData.Data = Count;
            }
            catch (SqlSugarException ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 判断当前账户是否PE QE
        /// </summary>
        /// <param name="UserCode"></param>
        /// <param name="UserName"></param>
        /// <param name="Post"></param>
        /// <returns></returns>
        public APIResponseData CurrentIsManager(string UserCode)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"获取数据失败！" };
            try
            {
                db.ChangeDatabase("addon");

                List<PostsInfo> Datas = db.Queryable<UserPostsInfo, PostsInfo>((t1, t2) => new object[] {
                      JoinType.Left,t1.Post == t2.Guid
                }).Where((t1, t2) => t1.UserCode.Equals(UserCode, StringComparison.CurrentCultureIgnoreCase) && t2.Status == "A").Select((t1, t2) => t2).ToList();

                int PostType = -1;

                if (Datas.Any(x => x.PostName == "OEM-QE"))
                    PostType = 0;

                if (Datas.Any(x => x.PostName == "OEM-PE"))
                    PostType = 1;

                apiResponseData.Code = 1;
                apiResponseData.Message = "";
                apiResponseData.Data = PostType;
            }
            catch (SqlSugarException ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 获取当前批次的QE PE邮箱
        /// </summary>
        /// <param name="Batch"></param>
        /// <returns></returns>
        public APIResponseData CurrentBatchManagerEmail(string Batch)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"获取数据失败！" };
            List<string> emailLst = new List<string>();
            try
            {
                db.ChangeDatabase("data");
                InspBatchInfo BatchInfo = db.Queryable<InspBatchInfo>().First(x => x.Batch.ToUpper().Equals(Batch.ToUpper()));
                if (BatchInfo != null)
                {
                    db.ChangeDatabase("addon");
                    List<ResourceAllocationsInfo> allocationsInfos = db.Queryable<ResourceAllocationsInfo>().Where(x => x.Product.Trim().Equals(BatchInfo.Product.ToUpper()) &&
                    x.Technology.Trim().ToUpper() == BatchInfo.Technology.Trim().ToUpper()).ToList();

                    if (allocationsInfos != null)
                    {
                        Guid[] guids = allocationsInfos.Select(x => x.Staff).ToArray();
                        List<StaffsInfo> staffs = db.Queryable<StaffsInfo>().Where(x => SqlFunc.ContainsArray(guids, x.Guid) && (x.Post == "0" || x.Post == "1")).ToList();
                        if (staffs != null && staffs.Count > 0)
                        {
                            emailLst.AddRange(staffs.Select(x => x.EMail).ToArray());
                        }
                    }
                }

                apiResponseData.Code = 1;
                apiResponseData.Message = "";
                apiResponseData.Data = emailLst;
            }
            catch (SqlSugarException ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 验证用户
        /// </summary>
        /// <param name="UserCode"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public APIResponseData ValideteToekn(string UserCode, string Password)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"获取数据失败！" };
            try
            {
                db.ChangeDatabase("data");
                int Count = db.Queryable<UserInfoInfo>().Count(x => x.UserCode.Equals(UserCode) && x.Password.Equals(Password) && x.Status == "A");

                apiResponseData.Code = 1;
                apiResponseData.Message = "";
                apiResponseData.Data = Count;
            }
            catch (SqlSugarException ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 获取TsSFC系统用户权限
        /// </summary>
        /// <param name="UserGuid"></param>
        /// <returns></returns>
        public APIResponseData GetUserAuths(Guid UserGuid)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"获取数据失败！" };
            try
            {
                db.ChangeDatabase("data");

                List<string> UserAuths = db.Ado.SqlQuery<string>(@"SELECT b.AuthCode FROM dbo.UserRoles a
INNER JOIN dbo.RoleAuths b ON a.RoleGuid = b.RoleGuid AND b.Status = 'A'
WHERE a.Status = 'A' AND a.UserGuid = @UserGuid", new { UserGuid }).ToList();

                apiResponseData.Code = 1;
                apiResponseData.Message = "";
                apiResponseData.Data = UserAuths;
            }
            catch (SqlSugarException ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

    }
}
