using DeviceRepair.Models;
using DeviceRepair.Models.Enum;
using DeviceRepair.Models.Record;
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 PreserveRepository
    {
        private readonly Logger log;
        private static PreserveRepository 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 PreserveRepository Instance
        {
            get
            {
                if (manager == null)
                    manager = new PreserveRepository();
                return manager;
            }
        }

        public PreserveRepository()
        {
            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>
        /// 获取单条保养记录
        /// </summary>
        /// <param name="EquipmentID"></param>
        /// <param name="Year"></param>
        /// <returns></returns>
        public MaintenanceRecordInfo Get_Preserve_Single(int RecordID)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("AutoID", RecordID + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_Preserve_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);
                IList<MaintenanceRecordInfo> Datas = DTOHelper<MaintenanceRecordInfo>.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="PlanAutoID"></param>
        /// <param name="EquipmentPrimaryID"></param>
        /// <param name="FormPrimaryID"></param>
        /// <returns></returns>
        public MaintenanceRecordInfo Get_Preserve_Single(int PlanAutoID, int EquipmentPrimaryID, int FormPrimaryID)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("PlanAutoID", PlanAutoID + "");
                ApiParameters.Add("EquipmentPrimaryID", EquipmentPrimaryID + "");
                ApiParameters.Add("FormPrimaryID", FormPrimaryID + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_Preserve_SingleByParams(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);
                IList<MaintenanceRecordInfo> Datas = DTOHelper<MaintenanceRecordInfo>.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="Data"></param>
        /// <returns></returns>
        public APIResponseData InsertData(MaintenanceRecordSubmit Data, EnumDeviceBelong Belong)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);
                ApiParameters.Add("Belong", Belong.ToString().Trim());

                DataSet dataSet = new DataSet();
                DataTable Record = new List<MaintenanceRecordInfo> { Data.Record }.ToDataTable();
                Record.TableName = "Record";
                dataSet.Tables.Add(Record);

                DataTable Files = Data.Files.ToDataTable();
                Files.TableName = "Files";
                dataSet.Tables.Add(Files);

                DataTable Imgs = Data.Imgs.ToDataTable();
                Imgs.TableName = "Imgs";
                dataSet.Tables.Add(Imgs);

                var Rtn = Utility.SfcBizService.CurrentSvc.Insert_PM_Preserve_Data(GetParameters(), dataSet);
                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="AutoID"></param>
        /// <returns></returns>
        public MaintenanceRecordSubmit Get_PreserveDetail_All(int AutoID)
        {
            byte[] btResults = null;
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);
                ApiParameters.Add("AutoID", AutoID + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_PreserveDetail_All(GetParameters(), out btResults);
                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                if (dsResults == null || dsResults.Tables.Count == 0)
                {
                    throw new Exception("未能获取到设备保养记录！");
                }

                MaintenanceRecordSubmit sub = new MaintenanceRecordSubmit();
                sub.Record = dsResults.Tables["MaintenanceRecordInfo"].ToList<MaintenanceRecordInfo>().First();
                sub.Files = dsResults?.Tables["Attachment"]?.ToList<AttachmentSubmitModel>();
                sub.Imgs = dsResults?.Tables["Image"]?.ToList<AttachmentSubmitModel>();

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

        /// <summary>
        /// 获取设备保养记录信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public List<MaintenanceRecordHistoryModel> Get_PreserveDetail_HisView(MaintenanceFilterModel filter, EnumDeviceBelong Belong)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("PlanID", filter.PlanID + "");
                ApiParameters.Add("EquipmentId", filter.EquipmentId + "");
                ApiParameters.Add("EquipmentName", filter.EquipmentName);
                ApiParameters.Add("StartDate", filter.StartDate.ToString("yyyy-MM-dd"));
                ApiParameters.Add("EndDate", filter.EndDate.ToString("yyyy-MM-dd"));
                ApiParameters.Add("MaintenanceType", filter.MaintenanceType.ToString());
                ApiParameters.Add("Banci", filter.Banci.ToString());
                ApiParameters.Add("Belong", Belong.ToString().Trim());

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_PreserveDetail_HisView(GetParameters(), out btResults);
                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                if (dsResults == null || dsResults.Tables.Count == 0)
                {
                    throw new Exception("未能获取到设备保养记录！");
                }
                return dsResults.Tables[0].ToList<MaintenanceRecordHistoryModel>();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }
    }
}
