using Azure.Storage.Blobs.Models;
using HiTeachCC.Models;
using HTEXLib;
using HTEXLib.Builders;
using HTEXLib.Helpers.ShapeHelpers;
using HTEXLib.Translator;
using Ionic.Zip;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TEAMModelOS.SDK.Context.Configuration;
using TEAMModelOS.SDK.Context.Constant;
using TEAMModelOS.SDK.Context.Constant.Common;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Helper.Common.StringHelper;
using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
using TEAMModelOS.SDK.Module.AzureBlob.Container;

namespace HiTeachCC.Controllers
{
    [Route("common/import")]
    [ApiController]
    public class FileController: ControllerBase
    {
        public PPTX2HTEXTranslator _PPTX2HTEXTranslator { get; set; }
        private readonly AzureStorageFactory _azureStorage;
        private readonly IHttpClientFactory _clientFactory;

        public FileController(AzureStorageFactory azureStorage, PPTX2HTEXTranslator PPTX2HTEXTranslator, IHttpClientFactory clientFactory) {
            _clientFactory = clientFactory;
            this._PPTX2HTEXTranslator = PPTX2HTEXTranslator;
            _azureStorage = azureStorage;
        }

        [HttpPost("upload-file")]
        [RequestSizeLimit(204_800_000_00)] //最大20000m左右
        public async Task<IActionResult> BlobSaveFile([FromForm] IFormFile file)
        {
            string id_token = HttpContext.GetXAuth("IdToken");
            if (string.IsNullOrEmpty(id_token)) return BadRequest();
            var jwt = new JwtSecurityToken(id_token);
            if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
            var blob = jwt.Payload.Claims.Where(x => x.Type == "blob").First().Value;
            var temp = jwt.Payload.Claims.Where(x => x.Type == "temp").First().Value;
            //IFormFileCollection s =  Request.Form.Files;
            FileTypeMap fileTypeMap = new FileTypeMap();
            fileTypeMap.GetFileTypes().TryGetValue(FileType.GetExtention(file.FileName).ToLower(), out FileType fileTpye);
            string type = "";
            if (fileTpye != null)
            {
                type = fileTpye.Type;
            }
            List<IFormFile> files = new List<IFormFile>();
            files.Add(file);

            var model= await  _azureStorage.UploadFileByContainer(blob, file.OpenReadStream(), temp, file.FileName);
            return Ok(new { url= model }) ;
        }
        [HttpPost("upload-base64")]
        public async Task<IActionResult> BlobSaveBase64(JsonElement element)
        {
            string id_token = HttpContext.GetXAuth("IdToken");
            if (string.IsNullOrEmpty(id_token)) return BadRequest();
            var jwt = new JwtSecurityToken(id_token);
            if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
            var blob = jwt.Payload.Claims.Where(x => x.Type == "blob").First().Value;
            var temp = jwt.Payload.Claims.Where(x => x.Type == "temp").First().Value;
            FileTypeMap fileTypeMap = new FileTypeMap();
            List<string> models = new List<string>();
            List<string> files = element.ToObject<List<string>>();
            foreach (string str in files)
            {
                string[] strs = str.Split(',');
                string fileExt = StringHelper.SubMidString(strs[0], ":", ";");
                if (ContentTypeDict.extdict.TryGetValue(fileExt, out string ext))
                {
                    fileExt = ext;
                }
                else
                {
                    //解决多种扩展名不能获取的
                    string[] sp = StringHelper.SubMidString(strs[0], "/", ";").Split("-");
                    fileExt = sp[sp.Length - 1];
                    sp = fileExt.Split("+");
                    fileExt = "." + sp[sp.Length - 1];
                }
                Stream stream = new MemoryStream(Convert.FromBase64String(strs[1]));
                var model = await _azureStorage.UploadFileByContainer(blob, stream, temp,Guid.NewGuid().ToString()+fileExt);
                models.Add(model);
            };
            return Ok(new { urls= models });
        }
        private static (string, string) BlobUrlString(string sasUrl)
        {
            sasUrl = sasUrl.Substring(8);
            string[] sasUrls = sasUrl.Split("/");
            string ContainerName;
            ContainerName = sasUrls[1].Clone().ToString();
            string item = sasUrls[0] + "/" + sasUrls[1] + "/";
            string blob = sasUrl.Replace(item, "");
            return (ContainerName, blob);
        }
        public static bool IsBlobName(string BlobName)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(BlobName,
             @"(?!((^(con)$)|^(con)\\..*|(^(prn)$)|^(prn)\\..*|(^(aux)$)|^(aux)\\..*|(^(nul)$)|^(nul)\\..*|(^(com)[1-9]$)|^(com)[1-9]\\..*|(^(lpt)[1-9]$)|^(lpt)[1-9]\\..*)|^\\s+|.*\\s$)(^[^\\\\\\:\\<\\>\\*\\?\\\\\\""\\\\|]{1,255}$)");
        }

        private static string ReplaceLast(string input, string oldValue, string newValue)
        {
            int index = input.LastIndexOf(oldValue);
            if (index < 0)
            {
                return input;
            }
            else
            {
                StringBuilder sb = new StringBuilder(input.Length - oldValue.Length + newValue.Length);
                sb.Append(input.Substring(0, index));
                sb.Append(newValue);
                sb.Append(input.Substring(index + oldValue.Length,
                   input.Length - index - oldValue.Length));

                return sb.ToString();
            }
        }


        /// <summary>
        /// {"url":"https://***.blob.core.cn/xxx/1.pptx"}
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("parse-doc")]
        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
        public async Task<IActionResult> ParsePPTX(JsonElement request)
        {
            //string id_token = HttpContext.GetXAuth("IdToken");
            //if (string.IsNullOrEmpty(id_token)) return BadRequest();
            //var jwt = new JwtSecurityToken(id_token);
            //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
            //var blob = jwt.Payload.Claims.Where(x => x.Type == "blob").First().Value;
            //var res = jwt.Payload.Claims.Where(x => x.Type == "res").First().Value;
            //var sas = jwt.Payload.Claims.Where(x => x.Type == "sas").First().Value;
            request.TryGetProperty("id", out JsonElement _id);
            string blob = "hiteachcc";
            string res = $"{_id}/res";
            request.TryGetProperty("file", out JsonElement _file);
            string azureBlobSAS = System.Web.HttpUtility.UrlDecode(_file.ToString(), Encoding.UTF8);
            (string, string) a = BlobUrlString(azureBlobSAS);
            string ContainerName = a.Item1;
            string BlobName = a.Item2;
            bool flg = IsBlobName(BlobName);
            var codes = azureBlobSAS.Split("/");
            var file = codes[codes.Length - 1].Split(".");
            var ext = file[file.Length - 1];
            var FileName = ReplaceLast(codes[codes.Length - 1], "."+ ext,"");
            if (flg)
            {
                BlobAuth blobAuth = _azureStorage.GetBlobSasUriRead(ContainerName, BlobName);
                var response = await _clientFactory.CreateClient().GetAsync(new Uri(blobAuth.url));
                response.EnsureSuccessStatusCode();
                Stream stream = await response.Content.ReadAsStreamAsync();
                if (ext.ToLower() == "pptx" || ext.ToLower() == "xml")
                {
                    string index = await PPTXTranslator(blob, res, FileName, stream);
                    return Ok(new { index = index, status = 200 });
                }
                else if (ext.ToLower() == "docx" || ext.ToLower() == "doc")
                {
                    return Ok(new { index = "", status = 200 });
                }
                else if (ext.ToLower() == "htex" )
                {
                    var index = await HTEXTranslator(blob, res , FileName, stream);
                    return Ok(new { index = index, status = 200 });
                }
                //else if (ext.ToLower() == "pdf")
                //{
                //    PdfDocument inputDocument = PdfSharpCore.Pdf.IO.PdfReader.Open(stream, PdfDocumentOpenMode.Import);
                //    int count = inputDocument.PageCount;
                //    int limit = BaseConfigModel.Configuration.GetSection("HABOOKConfig:PDFLimit").Get<int>();
                //    if (count > limit)
                //    {
                //        return BadRequest("PDF file cannot exceed " + limit + " pages!");
                //    }
                //    return Ok(new { index = "" ,page= count });
                //}
                //else if (ext.ToLower() == "xls")
                //{
                //    return Ok(new { index = "" });
                //}
                else {
                    return Ok(new { status=500,msg= "不是正确的Blob链接！" });
                }
            }
            else { return Ok(new { status = 500, msg = "不是正确的Blob链接！" }); }
        }
        private async Task<string> HTEXTranslator(string containerid,string  res, string FileName, Stream stream)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //处理中文乱码问题
            Encoding encoding = Encoding.GetEncoding("GB2312");
            var options = new ReadOptions { Encoding = encoding };
            string index = null;
            bool hasindex = false;
            List<Task<string>> tasks = new List<Task<string>>();
            ZipFile zip = ZipFile.Read(stream, options);
            zip.AlternateEncoding = encoding;
            List<Stream> streams = new List<Stream>();
            foreach (var f in zip.Entries)
            {
                string name = FileName + "/" + f.FileName;
                if (f.IsDirectory)
                {
                    continue;
                }
                var uploadStream = f.OpenReader();
                byte[] buffer = new byte[uploadStream.Length];
                uploadStream.Read(buffer, 0, buffer.Length);
                Stream blobstream = new MemoryStream(buffer);
                streams.Add(blobstream);
                tasks.Add(_azureStorage.UploadFileByContainer(containerid, blobstream, res, $"{name}", false));
                if (name.Contains($"{FileName}/index.json"))
                {
                    hasindex = true;
                }
                uploadStream.Close();
            }

            zip.Dispose();
            stream.Close();
            if (hasindex)
            {
                await Task.WhenAll(tasks);
                foreach (var task in tasks)
                {
                    var url = System.Web.HttpUtility.UrlDecode(task.Result, Encoding.UTF8);
                    if (url.Contains($"{res}/{FileName}/index.json"))
                    {
                        index = url;
                    }
                }
            }
            //释放资源
            streams.ForEach(x => { x.Close(); });
            return index;
        }
        private async Task<string> PPTXTranslator(string id,string res, string FileName, Stream streamFile)
        {
            var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(id, $"{res}/{FileName}");
            string shaCode = Guid.NewGuid().ToString();
            HTEXLib.Htex htex = _PPTX2HTEXTranslator.Translate(streamFile);
            htex.name = FileName;
            var slides = htex.slides;
            List<Task<string>> tasks = new List<Task<string>>();
            HTEXIndex hTEX = new HTEXIndex() { name = FileName, size = htex.size, thumbnail = htex.thumbnail, id = shaCode };
            List<KeyValuePair<string, string>> blobslidenames = new List<KeyValuePair<string, string>>();
            foreach (var slide in slides)
            {
                string json = JsonHelper.ToJson(slide, ignoreNullValue: false);
                string guid = Guid.NewGuid().ToString();
                blobslidenames.Add(new KeyValuePair<string, string>(guid, json));
            }
           
            List<Sld> slds = new List<Sld>();
            foreach (var key in blobslidenames)
            {
                slds.Add(new Sld { type = "normal", url = $"{key.Key}.json", scoring = null }); ;
                tasks.Add(_azureStorage.UploadFileByContainer(id, key.Value, res, $"{FileName}/{key.Key}.json", false));
            }
            await Task.WhenAll(tasks);
            List<Task> tasksFiles = new List<Task>();
            foreach (var key in htex.stores.Keys)
            {
                if (key.EndsWith(".wdp") || key.EndsWith(".xlsx"))
                {
                    htex.stores.Remove(key);
                    continue;
                }
                var store = htex.stores[key];
                Store str = new Store() { path = key, contentType = store.contentType, isLazy = store.isLazy };
                if (!store.isLazy && store.contentType != null && ContentTypeDict.extdict.TryGetValue(store.contentType, out string ext) && store.url.Contains(";base64,"))
                {
                    string[] strs = store.url.Split(',');
                    Stream stream = new MemoryStream(Convert.FromBase64String(strs[1]));
                   // var urlstrs = key.Split("/");
                    var name =key.Replace("/","");
                    str.url = $"{name}";
                    tasksFiles.Add(_azureStorage.UploadFileByContainer(id, stream, res, FileName + "/" + name, false));
                       
                }
                else
                {
                    str.url = System.Web.HttpUtility.UrlDecode(store.url, Encoding.UTF8);  
                }
            }
            await Task.WhenAll(tasksFiles);
            hTEX.slides = slds;
            var blob = await _azureStorage.UploadFileByContainer(id, JsonHelper.ToJson(hTEX, ignoreNullValue: false),res, FileName + "/" + "index.json", false);
            return System.Web.HttpUtility.UrlDecode(blob, Encoding.UTF8); 
        }
        
    }


    public class HTEXIndex
    {
        public string id { get; set; }
        public string version { get; set; } = "1.0.20201210";
        public string name { get; set; }
        public HTEXLib.HtexSize size { get; set; }
        public List<Sld> slides { get; set; }
        //缩略图
        public string thumbnail { get; set; }
        //  public int page { get; set; }
        // public Dictionary<string, Store> stores { get; set; }
        public List<string> points { get; set; }
        public string periodId { get; set; }
        public List<string> gradeIds { get; set; }
        public string subjectId { get; set; }
        public string subjectName { get; set; }
        public string score { get; set; }
        public string code { get; set; }
        public string scope { get; set; }
        public int? multipleRule { get; set; }
    }
    public class Sld
    {
        /// <summary>
        /// normal,普通的hte页面 single 单选题 multiple 多选题 judge 判断题 complete 填空题 subjective 问答题 compose 综合题 
        /// </summary>
        public string type { get; set; }
        /// <summary>
        /// 单页PPTx htex 的解析链接或一个题目的链接
        /// </summary>
        public string url { get; set; }
        /// <summary>
        /// 题目的配分，如果为type为normal 及compose ,则 scoring=null
        /// </summary>
        public Scoring scoring { get; set; }
        /// <summary>
        /// 单页PPTx htex 的缩略图
        /// </summary>
        public string thumbnail { get; set; }
    }

    public class Scoring
    {
        public double score { get; set; }
        public List<string> ans { get; set; } = new List<string>();
    }
}
