using DeviceRepair.Models;
using DeviceRepair.Models.Preserve;
using DeviceRepair.Models.SFC;
using DeviceRepair.Utils;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using TsSFCDevice.Client.Biz.Base.Service;
using TsSFCDevice.Client.Biz.Base.Utils;

namespace TsSFCDevice.Client.Biz.Impl
{
    public class CheckFormRepository
    {
        private readonly Logger log;
        private static CheckFormRepository 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 CheckFormRepository Instance
        {
            get
            {
                if (manager == null)
                    manager = new CheckFormRepository();
                return manager;
            }
        }

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

        #region 公共

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

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

        #endregion


        /// <summary>
        /// PM 的点检表数据
        /// </summary>
        /// <param name="FormName"></param>
        /// <returns></returns>
        public IList<MaintenanceFormVersionInfo> Get_PM_CheckForm_Datas(string FormName)
        {
            try
            {
                IList<MaintenanceFormVersionInfo> AllDatas = GetDatas();
                if (AllDatas == null || AllDatas.Count == 0)
                    return AllDatas;

                IList<MaintenanceFormVersionInfo> Datas = AllDatas.Where(x => x.FormBelong == "PM" &&
                    x.FormName.Contains(FormName)
                ).ToList();

                Datas.ForEach(item =>
                {
                    Dictionary<int, TsSFCUserInfo> userDict = Utility.SystemRuntimeInfo.CurrentUsersCaches.ToDictionary(s => s.Id, s => s);
                    // 计划创建人
                    if (userDict.ContainsKey(item.CreatUser))
                    {
                        item.CreatUserName = userDict[item.CreatUser].UserName;
                    }

                    // 计划修改人
                    if (item.ChangeUser.HasValue && userDict.ContainsKey(item.ChangeUser.Value))
                    {
                        item.ChangeUserName = userDict[item.ChangeUser.Value].UserName;
                    }
                });

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

        /// <summary>
        /// PM 的点检表数据
        /// </summary>
        /// <param name="FormName"></param>
        /// <returns></returns>
        public IList<MaintenanceFormVersionInfo> Get_AM_CheckForm_Datas(string FormName)
        {
            try
            {
                IList<MaintenanceFormVersionInfo> AllDatas = GetDatas();
                if (AllDatas == null || AllDatas.Count == 0)
                    return AllDatas;

                IList<MaintenanceFormVersionInfo> Datas = AllDatas.Where(x => x.FormBelong == "AM" &&
                    x.FormName.Contains(FormName)
                ).ToList();

                Datas.ForEach(item =>
                {
                    Dictionary<int, TsSFCUserInfo> userDict = Utility.SystemRuntimeInfo.CurrentUsersCaches.ToDictionary(s => s.Id, s => s);
                    // 计划创建人
                    if (userDict.ContainsKey(item.CreatUser))
                    {
                        item.CreatUserName = userDict[item.CreatUser].UserName;
                    }

                    // 计划修改人
                    if (item.ChangeUser.HasValue && userDict.ContainsKey(item.ChangeUser.Value))
                    {
                        item.ChangeUserName = userDict[item.ChangeUser.Value].UserName;
                    }
                });

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

        /// <summary>
        /// 获取全部点检表数据
        /// </summary>
        /// <returns></returns>
        public IList<MaintenanceFormVersionInfo> GetDatas()
        {
            IList<MaintenanceFormVersionInfo> Datas = new List<MaintenanceFormVersionInfo>();

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

                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.CheckForm, GetParameters(), out btResults);
                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                Datas = DTOHelper<MaintenanceFormVersionInfo>.DataTableToList(dsResults.Tables[0]);

                #region 换个地方
                //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;
                //        }
                //    });
                //} 
                #endregion

                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="PlanAutoID"></param>
        /// <returns></returns>
        public Tuple<DriveMaintencePlanInfo, MaintenanceFormVersionInfo> Get_CheckFormAndPlan_Single(int PlanAutoID, DateTime? MaintenanceDate = null)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("PlanAutoID", PlanAutoID + "");
                if (MaintenanceDate.HasValue)
                    ApiParameters.Add("MaintenanceDate", MaintenanceDate.Value.ToString("yyyy-MM-dd"));

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

                if (btResults == null || btResults.Length == 0)
                {
                    return null;
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                DriveMaintencePlanInfo Plan = DTOHelper<DriveMaintencePlanInfo>.DataTableToList(dsResults.Tables[0])?.FirstOrDefault();
                MaintenanceFormVersionInfo Form = DTOHelper<MaintenanceFormVersionInfo>.DataTableToList(dsResults.Tables[1])?.FirstOrDefault();

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

        /// <summary>
        /// 修改点检表状态
        /// </summary>
        /// <param name="FormID"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public APIResponseData Change_Form_Status(int FormID, string Status)
        {
            try
            {
                ApiParameters?.Clear();

                ApiParameters.Add("FormID", FormID + "");
                ApiParameters.Add("BeStatus", Status);

                var Rtn = Utility.SfcBizService.CurrentSvc.ChangeFormStatus(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="Datas"></param>
        /// <returns></returns>
        public APIResponseData AssigFormToDevice(List<SubmitAssignFormsToDevices> Datas)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);

                var Rtn = Utility.SfcBizService.CurrentSvc.AssigFormToDevice(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>
        /// 判断点检表数据是否存在
        /// </summary>
        /// <param name="VersionCode"></param>
        /// <param name="VersionRev"></param>
        /// <returns></returns>
        public bool Get_CheckForm_Exists(string VersionCode, string VersionRev)
        {
            try
            {
                int Count = 0;
                ApiParameters?.Clear();
                ApiParameters.Add("VersionCode", VersionCode);
                ApiParameters.Add("VersionRev", VersionRev);

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_CheckForm_Exists(GetParameters(), out Count);

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

        }

        /// <summary>
        /// 新增点检表
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        public APIResponseData Insert_CheckForm_Data(MaintenanceFormVersionInfo Data)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);

                var Rtn = Utility.SfcBizService.CurrentSvc.Insert_CheckForm_Data(GetParameters(), (new List<MaintenanceFormVersionInfo> { Data }).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>
        /// 修改点检表备注
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        public APIResponseData Change_CheckForm_Remark(MaintenanceFormVersionInfo Data)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);

                var Rtn = Utility.SfcBizService.CurrentSvc.Change_CheckForm_Remark(GetParameters(), (new List<MaintenanceFormVersionInfo> { Data }).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>
        /// 
        /// </summary>
        /// <param name="FormID"></param>
        /// <returns></returns>
        public MaintenanceFormVersionInfo Get_CheckForm_Single(int FormID)
        {
            try
            {
                //Get_CheckForm_Single
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("AutoID", FormID + "");

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

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