#if !Nancy
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Http;
using 电子展板.Base;
using 电子展板.Models;
using 电子展板.Utility;
using 电子展板.Utility.Core;
using 电子展板.Utility.Other;
using 电子展板.Utility.Web;
using static System.Net.Mime.MediaTypeNames;

namespace 电子展板.WebModule
{
    public class IndexController : ApiController
    {
        /// 主界面
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route(""), Route("index.html")]
        public ActionResult Index()
        {
            return Resouce("/Views/Index.html", "text/html");
        }

        /// <summary>
        /// 获得配置信息
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("getConfig")]
        public ActionResult GetConfig()
        {
            return Json(GlobalVariable.Config);
        }
        /// <summary>
        /// 上传图片。
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("uploadImage")]
        public ActionResult UploadImage()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string tempPath = Path.GetTempPath();
            var provider = new WithExtensionMultipartFormDataStreamProvider(tempPath, UUID.StrSnowId);
            var fileData = Request.Content.ReadAsMultipartAsync(provider).Result;
            if (fileData.FileData.Count == 0)
            {
                return Error();
            }
            var file = fileData.FileData[0];
            byte[] data = null;
            using (ByteArrayStream byteArrayStream = new ByteArrayStream())
            {
                using (var stream = System.IO.File.OpenRead(file.LocalFileName))
                {
                    stream.CopyTo(byteArrayStream);
                }
                System.IO.File.Delete(file.LocalFileName);
                data = byteArrayStream.ToByteArray();
            }
            string filename = Path.GetFileName(file.LocalFileName);
            GlobalVariable.Config.FileUploadList.Add(new UploadFiles { Name = filename, Bin = data });
            GlobalVariable.SaveConfig();

            string virtualPath = "/upload/" + filename;
            return Success("上传成功", virtualPath);
        }

        /// <summary>
        /// 图形显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("upload/{id}")]
        public ActionResult GetUploadFile([FromUri] string id)
        {
            string contentType = System.Web.MimeMapping.GetMimeMapping(id);
            UploadFiles uploadFiles = GlobalVariable.Config.FileUploadList.FirstOrDefault(x => x.Name == id);
            if (uploadFiles == null)
                return null;
            return File(uploadFiles.Bin, id, contentType);
        }

        /// <summary>
        /// 保存配置文件
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        [HttpPost, Route("save")]
        public ActionResult Save([FromBody] MyConfig config)
        {
            //保存
            PropertyInfo[] propertyInfos = typeof(MyConfig).GetProperties();
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                if (propertyInfo.Name == "FileUploadList")
                {
                    continue;
                }
                object value = propertyInfo.GetValue(config);
                propertyInfo.SetValue(GlobalVariable.Config, value);
            }
            GlobalVariable.SaveConfig();
            //保存并修改界面
            EventBus.Instance.Publish("save", "");
            return Success();
        }



        private ActionResult File(byte[] bytes, string name, string contentType)
        {
            ActionResult response = new ActionResult(HttpStatusCode.OK);
            response.Content = new StreamContent(new MemoryStream(bytes));
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            response.Content.Headers.ContentLength = bytes.Length;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = HttpUtility.UrlEncode(name)
            };
            response.Headers.Add("Access-Control-Expose-Headers", "FileName");
            response.Headers.Add("FileName", HttpUtility.UrlEncode(name));
            return response;
        }


        private ActionResult Json(object obj)
        {
            return new ActionResult { Content = new StringContent(obj.ToJson(), Encoding.UTF8, "application/json") };
        }

        public ActionResult Resouce(string viewName, string contentType)
        {
            string packUri = $"pack://application:,,,/Assets{viewName}";
            byte[] bytes = null;
            using (Stream stream = System.Windows.Application.GetResourceStream(new Uri(packUri, UriKind.RelativeOrAbsolute)).Stream)
            {
                bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
            }
            ActionResult response = new ActionResult(HttpStatusCode.OK);
            response.Content = new ByteArrayContent(bytes);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            response.Content.Headers.ContentLength = bytes.Length;
            return response;
        }

        protected ActionResult Success(string message = "恭喜您，操作成功。", object data = null)
        {
            return Json(new { state = 1, message, data });
        }

        protected ActionResult Error(string message = "对不起，操作失败。", object data = null)
        {
            return Json(new { state = 2, message, data });
        }
    }


    public class ActionResult : System.Net.Http.HttpResponseMessage
    {
        public ActionResult() : base(HttpStatusCode.OK)
        {

        }
        public ActionResult(HttpStatusCode statusCode) : base(statusCode)
        {
        }
    }
}
#endif