using DeviceRepair.Models;
using DeviceRepair.Models.Device;
using DeviceRepair.Models.Plan;
using DeviceRepair.Models.Plan.View;
using DeviceRepair.Models.SFC;
using DeviceRepair.Utils;
using NLog;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using TsSFCDevice.Client.Biz.Base.Service;
using TsSFCDevice.Client.Biz.Base.Utils;

namespace TsSFCDevice.Client.Biz.Impl
{
    public class PlanRepository
    {
        private readonly Logger log;
        private static PlanRepository manager;

        private IDictionary<string, string> m_ApiParameters;
        /// <summary>
        /// API输入参数
        /// </summary>
        public IDictionary<string, string> ApiParameters
        {
            get
            {
                return m_ApiParameters;
            }
            set
            {
                m_ApiParameters = value;
            }
        }

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

        public PlanRepository()
        {
            log = LogManager.GetCurrentClassLogger();
            m_ApiParameters = new Dictionary<string, string>();
        }

        #region PM

        /// <summary>
        /// 获取PM保养计划数据
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <param name="Year"></param>
        /// <returns></returns>
        public IList<AnnualMaintenancePlan> Get_PM_PLAN_Datas(string EquipmentID = "", int Year = 0)
        {
            IList<AnnualMaintenancePlan> Datas = new List<AnnualMaintenancePlan>();
            if (Year == 0)
                Year = DateTime.Today.Year;

            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();

                ApiParameters.Add("EquipmentID", EquipmentID);
                ApiParameters.Add("Year", Year + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.PM_PLAN, GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<AnnualMaintenancePlan> plans = DTOHelper<AnnualMaintenancePlan>.DataTableToList(dsResults.Tables[0]);

                if (Utility.SystemRuntimeInfo.CurrentDeviceCaches != null && Utility.SystemRuntimeInfo.CurrentDeviceCaches.Count > 0 && plans != null && plans.Count > 0)
                {
                    // 此处去除掉没有权限操作的设备
                    int[] DevIds = Utility.SystemRuntimeInfo.CurrentDeviceCaches.Select(x => x.AutoID).ToArray();
                    Datas = plans.Where(x => DevIds.Contains(x.EquipmentID)).ToList();
                }

                if (Utility.SystemRuntimeInfo.CurrentUsersCaches != null && Utility.SystemRuntimeInfo.CurrentUsersCaches.Count > 0)
                {
                    // 赋值各种操作员信息
                    Datas.AsParallel().ForEach(x =>
                    {
                        Dictionary<int, TsSFCUserInfo> userDict = Utility.SystemRuntimeInfo.CurrentUsersCaches.ToDictionary(s => s.Id, s => s);

                        // 计划创建人
                        if (userDict.ContainsKey(x.CreatUser))
                        {
                            x.CreatUserName = userDict[x.CreatUser].UserName;
                        }

                        // 计划修改人
                        if (x.ChangeUser.HasValue && userDict.ContainsKey(x.ChangeUser.Value))
                        {
                            x.ChangeUserName = userDict[x.ChangeUser.Value].UserName;
                        }
                    });
                }
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取PM保养计划数据
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <param name="Year"></param>
        /// <returns></returns>
        public IList<AnnualMaintenancePlan> Get_AM_PLAN_Datas(string EquipmentID = "", int Year = 0)
        {
            IList<AnnualMaintenancePlan> Datas = new List<AnnualMaintenancePlan>();
            if (Year == 0)
                Year = DateTime.Today.Year;

            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();

                ApiParameters.Add("EquipmentID", EquipmentID);
                ApiParameters.Add("Year", Year + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.AM_PLAN, GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<AnnualMaintenancePlan> plans = DTOHelper<AnnualMaintenancePlan>.DataTableToList(dsResults.Tables[0]);

                if (Utility.SystemRuntimeInfo.CurrentDeviceCaches != null && Utility.SystemRuntimeInfo.CurrentDeviceCaches.Count > 0 && plans != null && plans.Count > 0)
                {
                    // 此处去除掉没有权限操作的设备
                    int[] DevIds = Utility.SystemRuntimeInfo.CurrentDeviceCaches.Select(x => x.AutoID).ToArray();
                    Datas = plans.Where(x => DevIds.Contains(x.EquipmentID)).ToList();
                }

                if (Utility.SystemRuntimeInfo.CurrentUsersCaches != null && Utility.SystemRuntimeInfo.CurrentUsersCaches.Count > 0)
                {
                    // 赋值各种操作员信息
                    Datas.AsParallel().ForEach(x =>
                    {
                        Dictionary<int, TsSFCUserInfo> userDict = Utility.SystemRuntimeInfo.CurrentUsersCaches.ToDictionary(s => s.Id, s => s);

                        // 计划创建人
                        if (userDict.ContainsKey(x.CreatUser))
                        {
                            x.CreatUserName = userDict[x.CreatUser].UserName;
                        }

                        // 计划修改人
                        if (x.ChangeUser.HasValue && userDict.ContainsKey(x.ChangeUser.Value))
                        {
                            x.ChangeUserName = userDict[x.ChangeUser.Value].UserName;
                        }
                    });
                }
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取当前年月的待保修项
        /// </summary>
        /// <returns></returns>
        public IList<View_CurrentMonthPlanTips> Get_PM_PLAN_CurrentMonth()
        {
            byte[] btResults = null;
            try
            {
                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.PM_PLAN_CurrentMonth, GetParameters(), out btResults);
                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<View_CurrentMonthPlanTips> Datas = DTOHelper<View_CurrentMonthPlanTips>.DataTableToList(dsResults.Tables[0]);
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 取导出数据
        /// </summary>
        /// <param name="Year"></param>
        /// <returns></returns>
        public IList<View_YearsMaintenancePlansExport> Get_PM_PLAN_Xlsx(int Year = 0)
        {
            IList<View_YearsMaintenancePlansExport> Datas = new List<View_YearsMaintenancePlansExport>();
            if (Year == 0)
                Year = DateTime.Today.Year;

            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("Year", Year + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_PM_PLAN_Xlsx(GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<View_YearsMaintenancePlansExport> xlsxDatas = DTOHelper<View_YearsMaintenancePlansExport>.DataTableToList(dsResults.Tables[0]);
                if (xlsxDatas == null)
                {
                    throw new Exception("实例化当前导出数据时发生异常错误！");
                }

                if (Utility.SystemRuntimeInfo.CurrentDeviceCaches != null && Utility.SystemRuntimeInfo.CurrentDeviceCaches.Count > 0 && xlsxDatas != null && xlsxDatas.Count > 0)
                {
                    // 此处去除掉没有权限操作的设备
                    string[] EquipmentIds = Utility.SystemRuntimeInfo.CurrentDeviceCaches
                        .Select(x => x.EquipmentID).ToArray();
                    Datas = xlsxDatas.Where(x => EquipmentIds.Contains(x.EquipmentID)).ToList();
                }

                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取计划任务进度
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <param name="Year"></param>
        /// <returns></returns>
        public IList<View_PM_Plan_ProgressInfo> Get_PM_PLAN_ProgressInfo(int EquipmentID, int Year)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();

                ApiParameters.Add("EquipmentID", EquipmentID + "");
                ApiParameters.Add("Year", Year + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_PM_PLAN_ProgressInfo(GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<View_PM_Plan_ProgressInfo> Datas = DTOHelper<View_PM_Plan_ProgressInfo>.DataTableToList(dsResults.Tables[0]);
                if (Datas == null)
                {
                    throw new Exception("实例化当前计划数据时发生异常错误！");
                }
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        #endregion

        #region AM

        /// <summary>
        /// 取导出数据
        /// </summary>
        /// <param name="Year"></param>
        /// <returns></returns>
        public IList<View_AMYearsMaintenancePlansExport> Get_AM_PLAN_Xlsx(int Year = 0)
        {
            IList<View_AMYearsMaintenancePlansExport> Datas = new List<View_AMYearsMaintenancePlansExport>();
            if (Year == 0)
                Year = DateTime.Today.Year;

            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("Year", Year + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_AM_PLAN_Xlsx(GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<View_AMYearsMaintenancePlansExport> xlsxDatas = DTOHelper<View_AMYearsMaintenancePlansExport>.DataTableToList(dsResults.Tables[0]);
                if (xlsxDatas == null)
                {
                    throw new Exception("实例化当前导出数据时发生异常错误！");
                }

                if (Utility.SystemRuntimeInfo.CurrentDeviceCaches != null && Utility.SystemRuntimeInfo.CurrentDeviceCaches.Count > 0 && xlsxDatas != null && xlsxDatas.Count > 0)
                {
                    // 此处去除掉没有权限操作的设备
                    string[] EquipmentIds = Utility.SystemRuntimeInfo.CurrentDeviceCaches
                        .Select(x => x.EquipmentID).ToArray();
                    Datas = xlsxDatas.Where(x => EquipmentIds.Contains(x.EquipmentID)).ToList();
                }

                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取每日保养的计划完成情况
        /// </summary>
        /// <param name="MaintenanceDate"></param>
        /// <returns></returns>
        public IList<DailyPlanCompleteStatus> AM_PLAN_Scheduler(int PlanAutoID)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("PlanAutoID", PlanAutoID + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.AM_PLAN_Scheduler, GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<DailyPlanCompleteStatus> Datas = DTOHelper<DailyPlanCompleteStatus>.DataTableToList(dsResults.Tables[0]);
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取计划任务进度
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <param name="Year"></param>
        /// <returns></returns>
        public IList<View_PM_Plan_ProgressInfo> Get_AM_PLAN_ProgressInfo(int EquipmentID, int Year)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();

                ApiParameters.Add("EquipmentID", EquipmentID + "");
                ApiParameters.Add("Year", Year + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_AM_PLAN_ProgressInfo(GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<View_PM_Plan_ProgressInfo> Datas = DTOHelper<View_PM_Plan_ProgressInfo>.DataTableToList(dsResults.Tables[0]);
                if (Datas == null)
                {
                    throw new Exception("实例化当前计划数据时发生异常错误！");
                }
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        #endregion

        /// <summary>
        /// 新增或修改PM计划
        /// </summary>
        /// <param name="Datas"></param>
        /// <returns></returns>
        public APIResponseData Insert_OR_Edit_PM_PLAN(List<DriveMaintencePlanInfo> Datas, string Belong)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);
                ApiParameters.Add("Belong", Belong);

                var Rtn = Utility.SfcBizService.CurrentSvc.Insert_OR_Edit_PM_PLAN(GetParameters(), Datas.ToDataTable());
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return new APIResponseData { Code = 1, Message = Rtn.Message };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 删除PM计划
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <param name="Year"></param>
        /// <returns></returns>
        public APIResponseData Del_PM_PLAN(int EquipmentID, int Year, string Belong)
        {
            try
            {
                ApiParameters?.Clear();

                ApiParameters.Add("EquipmentID", EquipmentID + "");
                ApiParameters.Add("Year", Year + "");
                ApiParameters.Add("Belong", Belong);

                var Rtn = Utility.SfcBizService.CurrentSvc.Del_PM_PLAN(GetParameters());
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return new APIResponseData { Code = 1, Message = Rtn.Message };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取当前计划是否存的保养记录
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <param name="Year"></param>
        /// <param name="Belong"></param>
        /// <returns></returns>
        public IList<PlanProgress> Get_PlanRecordProgress(int EquipmentID, int Year, string Belong)
        {
            byte[] btResults = null;
            try
            {
                ApiParameters?.Clear();

                ApiParameters.Add("EquipmentID", EquipmentID + "");
                ApiParameters.Add("Year", Year + "");
                ApiParameters.Add("Belong", Belong);

                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.PLAN_Pregress, GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                if (dsResults == null || dsResults.Tables.Count == 0)
                {
                    return null;
                }
                IList<PlanProgress> plans = DTOHelper<PlanProgress>.DataTableToList(dsResults.Tables[0]);
                return plans;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取单条PM计划任务进度
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <param name="Year"></param>
        /// <returns></returns>
        public AnnualMaintenancePlan PM_PLAN_Single(int EquipmentID, int Year, string Belong)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("EquipmentID", EquipmentID + "");
                ApiParameters.Add("Year", Year + "");
                ApiParameters.Add("Belong", Belong);

                var Rtn = Utility.SfcBizService.CurrentSvc.PM_PLAN_Single(GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<AnnualMaintenancePlan> Datas = DTOHelper<AnnualMaintenancePlan>.DataTableToList(dsResults.Tables[0]);
                if (Datas == null)
                {
                    throw new Exception("实例化当前计划数据时发生异常错误！");
                }
                return Datas.FirstOrDefault();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取设备在年度的全部保养信息
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <param name="Year"></param>
        /// <param name="Belong"></param>
        /// <returns></returns>
        public DeviceAnnPlanView Get_EquiAnnualPlans(int EquipmentID, int Year, string Belong)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("EquipmentID", EquipmentID + "");
                ApiParameters.Add("Year", Year + "");
                ApiParameters.Add("Belong", Belong);

                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.Get_EquiAnnualPlans, GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                DeviceAnnPlanView dev = new DeviceAnnPlanView()
                {
                    Dev = DTOHelper<DeviceInformationInfo>.DataTableToList(dsResults.Tables["DeviceInformationInfo"])?.FirstOrDefault(),
                    Plans = DTOHelper<DriveMaintencePlanInfo>.DataTableToList(dsResults.Tables["DriveMaintencePlanInfo"])?.ToList(),
                    Records = DTOHelper<MaintenanceRecordInfo>.DataTableToList(dsResults.Tables["MaintenanceRecordInfo"])?.ToList(),
                };

                if (dsResults.Tables["Table"] != null && dsResults.Tables["Table"].Rows.Count > 0)
                {
                    dev.AM_FormCode = dsResults.Tables["Table"].Rows[0]["AM_FormCode"] + "";
                    dev.PM_FormCode = dsResults.Tables["Table"].Rows[0]["PM_FormCode"] + "";
                }

                return dev;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取单计划数据
        /// </summary>
        /// <param name="AutoID"></param>
        /// <returns></returns>
        public DriveMaintencePlanInfo Get_PLAN_Single(int AutoID)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("AutoID", AutoID + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_PLAN_Single(GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<DriveMaintencePlanInfo> Datas = DTOHelper<DriveMaintencePlanInfo>.DataTableToList(dsResults.Tables[0]);
                if (Datas == null)
                {
                    throw new Exception("实例化当前计划数据时发生异常错误！");
                }
                return Datas.FirstOrDefault();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 判断当前开工设备是否存在未完成的保养计划
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <returns></returns>
        public APIResponseData Get_EquipmentPlanIsComplete(string EquipmentID, int Banci)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("EquipmentID", EquipmentID);
                ApiParameters.Add("Banci", Banci + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_EquipmentPlanIsComplete(GetParameters());
                return new APIResponseData { Code = Rtn.Code, Message = Rtn.Message };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        #region 公共

        internal string GetParameters(string cOperator = "", bool bFlag = true)
        {

            return ParametersObject.GetInstance(cOperator).GetJsonSerialized(m_ApiParameters);
        }

        #endregion
    }
}
