using CsharpHttpHelper;
using DeviceRepairAndOptimization.Business;
using DeviceRepairAndOptimization.Data.MaintenanceForm;
using DeviceRepairAndOptimization.Models;
using DeviceRepairAndOptimization.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace DeviceRepairAndOptimization.Data
{
    public class MaintenanceFormVersionMaintenance
    {
        private static MaintenanceFormVersionMaintenance manager;

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

        /// <summary>
        /// 获取全部数据
        /// </summary>
        /// <returns></returns>
        public List<MaintenanceFormVersionModel> GetAll()
        {
            List<MaintenanceFormVersionModel> lst = null;

            try
            {
                switch (Models.Config.Configurations.Properties.ConnType?.ToLower())
                {
                    case "api":
                        #region api

                        APIResponseData result = ApiHelper.Instance.SendMessage(new HttpItem
                        {
                            URL = ServiceRoute.GetAllMaintenanceData,
                            Method = "Post",
                            ContentType = "application/json; charset=utf-8",
                            Postdata = JsonConvert.SerializeObject(new { querystring = "" })
                        });

                        if (result.Code == 1)
                        {
                            lst = JsonConvert.DeserializeObject<List<MaintenanceFormVersionModel>>(result.Data + "");
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }

                        #endregion
                        break;
                    case "sql":
                        #region sql

                        lst = MaintenanceFormVersionAccess.Instance().GetAll();

                        #endregion
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return lst;
        }

        public string GetFileSingle(int AutoID)
        {
            string filePath = string.Empty;
            try
            {
                if (AutoID == 0)
                    return filePath;

                switch (Models.Config.Configurations.Properties.ConnType?.ToLower())
                {
                    case "api":

                        filePath = ApiHelper.Instance.DownLoadFile(new HttpItem()
                        {
                            URL = "api/MaintenanceForm/DownloadFile?AutoID=" + AutoID,
                            Method = "get",
                            ContentType = "application/vnd.ms-excel"
                        });

                        ////创建Httphelper对象
                        //HttpHelper http = new HttpHelper();
                        ////创建Httphelper参数对象
                        //HttpItem item = new HttpItem()
                        //{
                        //    URL = "api/MaintenanceForm/DownloadFile?AutoID=" + AutoID,
                        //    Method = "get",
                        //    ContentType = "application/vnd.ms-excel",
                        //    ResultType = ResultType.Byte
                        //};
                        //HttpResult result = http.GetHtml(item);

                        //WebHeaderCollection header = result.Header;
                        //if (header != null)
                        //{
                        //    string fileName = header["FileName"];
                        //    if (!string.IsNullOrWhiteSpace(fileName))
                        //    {
                        //        string CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                        //        if (!Directory.Exists(Path.Combine(CurrentDirectory, "Cache")))
                        //            Directory.CreateDirectory(Path.Combine(CurrentDirectory, "Cache"));

                        //        File.WriteAllBytes(Path.Combine(CurrentDirectory, fileName), result.ResultByte);
                        //        filePath = Path.Combine(CurrentDirectory, fileName);
                        //    }
                        //}
                        break;
                    case "sql":

                        //entity = MaintenanceFormVersionAccess.Instance().GetSingle(AutoID);

                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return filePath;
        }

        /// <summary>
        /// 获取单条数据
        /// </summary>
        /// <param name="AutoID"></param>
        /// <returns></returns>
        public MaintenanceFormVersionModel GetSingle(int AutoID)
        {
            MaintenanceFormVersionModel entity = null;
            try
            {
                if (AutoID == 0)
                    return entity;

                switch (Models.Config.Configurations.Properties.ConnType?.ToLower())
                {
                    case "api":

                        APIResponseData result = ApiHelper.Instance.SendMessage(new HttpItem
                        {
                            URL = ServiceRoute.GetFormVersionSingle,
                            Method = "Post",
                            ContentType = "application/json; charset=utf-8",//返回类型    可选项有默认值
                            Postdata = JsonConvert.SerializeObject(new { autoid = AutoID })
                        });

                        if (result.Code == 1)
                        {
                            entity = JsonConvert.DeserializeObject<MaintenanceFormVersionModel>(result.Data + "");
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }

                        break;
                    case "sql":

                        entity = MaintenanceFormVersionAccess.Instance().GetSingle(AutoID);

                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return entity;
        }

        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="maintenance"></param>
        /// <returns></returns>
        public bool InsertSingle(MaintenanceFormVersionModel maintenance)
        {
            bool IsSuccess = false;
            try
            {
                if (maintenance == null)
                    return IsSuccess;

                switch (Models.Config.Configurations.Properties.ConnType?.ToLower())
                {
                    case "api":

                        APIResponseData result = ApiHelper.Instance.SendMessage(new CsharpHttpHelper.HttpItem
                        {
                            URL = ServiceRoute.AddFormVersionData,
                            Method = "Post",
                            ContentType = "application/json; charset=utf-8",
                            Postdata = JsonConvert.SerializeObject(maintenance)
                        });

                        if (result.Code == 1)
                        {
                            IsSuccess = bool.Parse(result.Data + "");
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }

                        break;
                    case "sql":

                        int AutoID = MaintenanceFormVersionAccess.Instance().InsertSingle(maintenance);
                        IsSuccess = AutoID > 0;
                        if (IsSuccess)
                        {
                            HistoryManager.Instance.FormHistoryWrite(AutoID, "新增");
                        }
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return IsSuccess;
        }

        /// <summary>
        ///替换/修改 点检表
        /// </summary>
        /// <param name="maintenance"></param>
        /// <returns></returns>
        public bool UpdataSingle(MaintenanceFormVersionModel maintenance)
        {
            bool IsSuccess = false;
            try
            {
                if (maintenance == null)
                    return IsSuccess;

                switch (Models.Config.Configurations.Properties.ConnType?.ToLower())
                {
                    case "api":

                        APIResponseData result = ApiHelper.Instance.SendMessage(new CsharpHttpHelper.HttpItem
                        {
                            URL = ServiceRoute.ReplaceFormVersion,
                            Method = "Post",
                            ContentType = "application/json; charset=utf-8",//返回类型    可选项有默认值
                            Postdata = JsonConvert.SerializeObject(maintenance)
                        });

                        if (result.Code == 1)
                        {
                            IsSuccess = bool.Parse(result.Data + "");
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }


                        break;
                    case "sql":

                        IsSuccess = MaintenanceFormVersionAccess.Instance().InsertSingle(maintenance) > 0;

                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return IsSuccess;
        }


        /// <summary>
        /// 修改备注
        /// </summary>
        /// <param name="maintenance"></param>
        /// <returns></returns>
        public bool ChangeRemark(MaintenanceFormVersionModel maintenance)
        {
            bool isSuccess = false;
            try
            {
                if (maintenance == null)
                    return isSuccess;

                switch (Models.Config.Configurations.Properties.ConnType?.ToLower())
                {
                    case "api":
                        string pdata = JObject.FromObject(maintenance).ToString();

                        APIResponseData result = ApiHelper.Instance.PostWebRequest(ServiceRoute.UpdateFormVersionRemark, pdata, GlobalInfo.token);

                        if (result.Code == 1)
                        {
                            isSuccess = bool.Parse(result.Data + "");
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }

                        break;
                    case "sql":

                        isSuccess = MaintenanceFormVersionAccess.Instance().ChangeRemark(maintenance, null);

                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return isSuccess;
        }

        /// <summary>
        /// 单行数据翻转当前状态(启用/禁用)
        /// </summary>
        ///// <param name="AutoID"></param>
        /// <returns></returns>
        public bool ChangeStauts(int AutoID, int UserID)
        {
            bool isSuccess = false;
            try
            {
                if (AutoID == 0)
                    return isSuccess;

                switch (Models.Config.Configurations.Properties.ConnType?.ToLower())
                {
                    case "api":

                        APIResponseData result = ApiHelper.Instance.SendMessage(new CsharpHttpHelper.HttpItem
                        {
                            URL = ServiceRoute.UpdateFormVersionStatus,
                            Method = "Post",
                            ContentType = "application/json; charset=utf-8",//返回类型    可选项有默认值
                            Postdata = JsonConvert.SerializeObject(new { autoid = AutoID, userid = UserID })
                        });

                        if (result.Code == 1)
                        {
                            isSuccess = bool.Parse(result.Data + "");
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }

                        break;
                    case "sql":

                        isSuccess = MaintenanceFormVersionAccess.Instance().ChangeStauts(AutoID, UserID);

                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return isSuccess;
        }

        /// <summary>
        /// 判断数据是否存在
        /// </summary>
        /// <param name="maintenance"></param>
        /// <returns></returns>
        public bool DataIsExists(MaintenanceFormVersionModel maintenance)
        {
            bool isSuccess = false;
            try
            {
                if (maintenance == null)
                    return isSuccess;

                switch (Models.Config.Configurations.Properties.ConnType?.ToLower())
                {
                    case "api":

                        APIResponseData result = ApiHelper.Instance.SendMessage(new CsharpHttpHelper.HttpItem
                        {
                            URL = ServiceRoute.ExistsFormVersionData,
                            Method = "Post",
                            ContentType = "application/json; charset=utf-8",
                            Postdata = JsonConvert.SerializeObject(new
                            {
                                FormName = maintenance.FormName,
                                VersionCode = maintenance.VersionCode,
                                VersionRev = maintenance.VersionRev
                            })
                        });

                        if (result.Code == 1)
                        {
                            isSuccess = bool.Parse(result.Data + "");
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }

                        break;
                    case "sql":

                        isSuccess = MaintenanceFormVersionAccess.Instance().DataIsExists(maintenance);

                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return isSuccess;
        }

        /// <summary>
        /// 根据关键字筛选
        /// </summary>
        /// <param name="filterValue"></param>
        /// <returns></returns>
        public List<MaintenanceFormVersionModel> GetQuery(string filterValue)
        {
            List<MaintenanceFormVersionModel> lst = null;
            try
            {
                switch (Models.Config.Configurations.Properties.ConnType?.ToLower())
                {
                    case "api":

                        APIResponseData result = ApiHelper.Instance.SendMessage(new CsharpHttpHelper.HttpItem
                        {
                            URL = ServiceRoute.QueryFormVersionData,
                            Method = "Post",
                            ContentType = "application/json; charset=utf-8",//返回类型    可选项有默认值
                            Postdata = JsonConvert.SerializeObject(new { filtervalue = filterValue })
                        });

                        if (result.Code == 1)
                        {
                            lst = JsonConvert.DeserializeObject<List<MaintenanceFormVersionModel>>(result.Data + "");
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }

                        break;
                    case "sql":

                        lst = MaintenanceFormVersionAccess.Instance().GetQuery(filterValue);

                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return lst;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task<string> UploadFile(string filePath)
        {
            try
            {
                string FileExtension = Path.GetExtension(filePath);
                string newName = $"{Guid.NewGuid()}{FileExtension}";

                using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    APIResponseData result = await ApiHelper.Instance.UploadFileAsync(ServiceRoute.UploadFormVersionFile, fileStream, newName);
                    if (result.Code == 1)
                        return result.Data + "";
                    else
                        throw new Exception(result.Message);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

    }
}
