using COMMON;
using Microsoft.AspNetCore.Http;
using Models;
using Models.Models;
using SERVER.LIB;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SERVER
{
    /// <summary>
    /// 文件数据
    /// </summary>
    public class ModelFile
    {
        /// <summary>
        /// 文件数据
        /// </summary>
        /// <param name="type"></param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="count"></param>
        /// <param name="count_"></param>
        /// <returns></returns>
        public static IEnumerable<TBL_MODEL_FILE_DATA> SelModelFile(out int count,out int count_,string type = "", int start = 0, int length = 0)
        {
            count = CacheData.TBL_MODEL_FILE_DATA.Count();
            count_ = CacheData.TBL_MODEL_FILE_DATA.Where(x =>string.IsNullOrEmpty(type) || x.Directory.Contains(type)).Count();
            return CacheData.TBL_MODEL_FILE_DATA.Where(x=> string.IsNullOrEmpty(type) || x.Directory.Contains(type)).OrderByDescending(x=>x.UploadDateTime).Skip(start).Take(length);
        }

        /// <summary>
        /// 文件数据删除
        /// </summary>
        /// <param name="db"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool DelModelFile(int id, HotelServiceContext db = null)
        {
            if (db == null)
                // 一般情况下都会从控制器传入过来
                db = XC_Data.GetMinDataBase();
            TBL_MODEL_FILE_DATA tump = db.TBL_MODEL_FILE_DATAS.First(x => x.MFD_ID == id);
            db.Entry(tump).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
            // 删除文件标记
            bool isdel = false;
            if (FtpHelper.GetFileSize(Path.Combine(tump.Directory, tump.XML_FileName)) > 0)
                if(FtpHelper.DeleteFileName(Path.Combine(tump.Directory, tump.XML_FileName)))
                    isdel = true;
                else
                    isdel = false;
            else
                isdel = true;
            // 执行数据库数据删除
            if (isdel)
            {
                CacheData.Clear(CacheData.CacheDataEnum.TBL_MODEL_FILE_DATA);
                return db.SaveChanges() > 0;
            }
            else return false;
        } 


        /// <summary>
        /// 文件数据添加
        /// </summary>
        /// <param name="db"></param>
        /// <param name="type"></param>
        /// <param name="files"></param>
        /// <param name="Author"></param>
        /// <returns></returns>
        public static async Task<Dictionary<string, int>> AddModelFile(int type, List<IFormFile> files, string Author, HotelServiceContext db = null)
        {
            try
            {

           
            Dictionary<string, int> res = new Dictionary<string, int>();

            if (db == null)
                    // 一般情况下都会从控制器传入过来
                    db = XC_Data.GetMinDataBase();
            string path = "485Model";
            switch (type)
            {
                case 0:
                    path = "485Model";
                    break;
                case 1:
                    path = "BaseModel";
                    break;
                case 2:
                    path = "RCUModel";
                    break;
                default:
                    return res;
            }
            long size = files.Sum(f => f.Length);


            foreach (IFormFile formFile in files)
            {
                if (formFile.Length > 0)
                {
                    TBL_MODEL_FILE_DATA data = new TBL_MODEL_FILE_DATA();
                    data.Author = Author;
                    data.Available = 1;
                    data.Directory = @$"\Data\Model\{path}";
                    data.XLM_MD5 = "555";
                    data.Remark = "Web上传~";
                    data.XML_FileName = formFile.FileName;

                    var filePath = Path.GetTempFileName();

                    using (var stream = System.IO.File.Create(filePath))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                    //xml md5
                    using (var md5 = MD5.Create())
                    {
                            //Encoding.ASCII.GetBytes()
                        data.XLM_MD5 = BitConverter.ToString(md5.ComputeHash(System.IO.File.ReadAllBytes(filePath))).Replace("-", "").ToUpper();
                    }
                    db.TBL_MODEL_FILE_DATAS.Add(data);
                    //文件存在 /BLV_Studio//Data/Model/485Model444BLV-C5_测试.xml
                    if (FtpHelper.GetFileSize(data.Directory + "/" + formFile.FileName) > -1)
                    {
                        res.Add(data.XML_FileName, -1);
                        continue;
                    }
                    if (FtpHelper.FileUpLoad(filePath, formFile.FileName, data.Directory))
                    {

                        System.IO.File.Delete(filePath);
                        res.Add(data.XML_FileName, db.SaveChanges());
                    }
                    else
                    {
                        //FtpHelper.DeleteFileName(data.Directory + formFile.FileName);
                        res.Add(data.XML_FileName, -2);
                    }
                }
            }
            return res;
            }
            catch (Exception ex)
            {
                LogHelp.Error("ftp file : " + ex.ToString());
                return null;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static dynamic GetFtp(out int count, out int count_,int start = 0, int length = 0, string type = "")
        {
           
            List<dynamic> res = new List<dynamic>();
            try
            {
                var data = SelModelFile(out count,out count_, type, start, length);
            foreach (var item in data)
            {
                int size = FtpHelper.GetFileSize(Path.Combine(item.Directory, item.XML_FileName));
                res.Add(new { data = item, size });
            }
            
        }
            catch (Exception ex)
            {
                LogHelp.Error("ftp file : " + ex.ToString());
                count_ = 0;
                count = 0;
                res = null;
            }
            return res;
        }
    }
}
