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

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

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

        /// <summary>
        /// 获取服务器时间
        /// </summary>
        /// <returns></returns>
        public DateTime ServiceTime()
        {
            try
            {
                return Utility.SfcBizService.CurrentSvc.ServiceTime();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取全部配置
        /// </summary>
        /// <returns></returns>
        public List<SysConfigInfo> GetSysConfigs()
        {
            IList<SysConfigInfo> Datas = new List<SysConfigInfo>();

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

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

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

        /// <summary>
        /// 批量编辑配置
        /// </summary>
        /// <param name="Datas"></param>
        /// <returns></returns>
        public APIResponseData EditConfigs(List<SysConfigInfo> Datas)
        {
            try
            {
                ApiParameters?.Clear();
                var Rtn = Utility.SfcBizService.CurrentSvc.EditConfigs(GetParameters(), Datas.ToDataTable());
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return new APIResponseData { Code = 1 };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取附件信息
        /// </summary>
        /// <returns></returns>
        public List<AttachmentInfo> GetAttachmentInfos(string TableName, string PrimaryKey, string PrimaryValue)
        {
            IList<AttachmentInfo> Datas = new List<AttachmentInfo>();

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

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

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

        /// <summary>
        /// 下载点检表文件
        /// </summary>
        /// <param name="FormID"></param>
        /// <returns></returns>
        public string DownLoadCheckForm(int FormID)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("AutoID", FormID + "");

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

                string fileName = $"{Guid.NewGuid()}_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                string CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                if (!Directory.Exists(Path.Combine(CurrentDirectory, "Cache")))
                    Directory.CreateDirectory(Path.Combine(CurrentDirectory, "Cache"));

                File.WriteAllBytes(Path.Combine(CurrentDirectory, "Cache", fileName), btResults);
                return Path.Combine(CurrentDirectory, "Cache", fileName);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取附件图片
        /// </summary>
        /// <param name="AutoID"></param>
        /// <returns></returns>
        public System.Drawing.Image GetAttachmentImage(int AutoID)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("AutoID", AutoID + "");

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

                using (MemoryStream ms = new MemoryStream(btResults))
                {
                    return System.Drawing.Bitmap.FromStream(ms, true);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取附件图片
        /// </summary>
        /// <param name="AutoID"></param>
        /// <returns></returns>
        public byte[] GetAttachmentImageByte(int AutoID)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("AutoID", AutoID + "");

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

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

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public APIResponseData UploadFile(string filePath)
        {
            try
            {
                string FileExtension = Path.GetExtension(filePath);

                ApiParameters?.Clear();
                ApiParameters.Add("FileExtension", FileExtension);

                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                try
                {
                    byte[] buffur = null;
                    buffur = new byte[fs.Length];
                    fs.Read(buffur, 0, (int)fs.Length);

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

                    return new APIResponseData { Code = 1, Data = Rtn.Data };
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    if (fs != null)
                    {

                        //关闭资源
                        fs.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取邮箱配置
        /// </summary>
        /// <param name="moduleCode"></param>
        /// <returns></returns>
        public SysEmailConfigInfo sysEmailConfigByModuleCode(string moduleCode)
        {
            IList<SysEmailConfigInfo> Datas = new List<SysEmailConfigInfo>();

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

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

                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return Datas?.ToList()?.FirstOrDefault();
            }
            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


    }
}
