using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.ApiDNC.Utility;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.Log;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.DncRepository.Entities;
using Siger.Middlelayer.DncRepository.Repositories.Interface;
using Siger.Middlelayer.DncRepository.Request;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.ApiDNC.Controllers
{
    public class DNCBaLingLingController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectDncUserPowerRepository _sigerProjectDncUserPowerRepository;
        private readonly ISigerProjectDncProgramRepository _sigerProjectDncProgramRepository;
        private readonly ISigerProjectProductReport _sigerProjectProductReport;

        public DNCBaLingLingController(IUnitOfWork unitOfWork, ISigerProjectDncUserPowerRepository sigerProjectDncUserPowerRepository, ISigerProjectDncProgramRepository sigerProjectDncProgramRepository, ISigerProjectProductReport sigerProjectProductReport)
        {
            _unitOfWork = unitOfWork;
            _sigerProjectDncUserPowerRepository = sigerProjectDncUserPowerRepository;
            _sigerProjectDncProgramRepository = sigerProjectDncProgramRepository;
            _sigerProjectProductReport = sigerProjectProductReport;
        }
        /// <summary>
        /// 导入程序
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddProgramPost(RequestAddPrograms req)
        {
            var errors = new List<string>();
            if (string.IsNullOrEmpty(req.file_url1))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            string[] paths = req.file_url1.Split("/");
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "download/dnc/temporaryzip/", paths[paths.Length - 1]);
            System.IO.StreamReader file = System.IO.File.OpenText(path);
            var strJson = file.ReadToEnd();
            dynamic array = JsonConvert.DeserializeObject<List<siger_project_dnc_program>>(strJson);
            var list = new List<siger_project_dnc_program>();
            foreach (var item in array)
            {
                var newName = Guid.NewGuid() + item.file_name;
                var programPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload/dnc/programs/", item.file_name);
                var newPathh = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload/dnc/programs/", newName);
                if (!System.IO.File.Exists(programPath))
                {
                    errors.Add($"{item.program_code},{(int)RequestEnum.ProgramNotFind}");
                }
                else
                {
                    System.IO.File.Move(programPath, newPathh);
                }
                FileInfo files = new FileInfo(newPathh);
                var size = files.Length.ToString();//文件大小。byte
                var query = new siger_project_dnc_program();
                var url = FileUtility.GetDisplayPath(newPathh);
                query.program_code = item.program_code;
                query.productid = item.productid;
                query.createmid = UserId;
                query.projectid = ProjectId;
                query.createtime = UnixTimeHelper.GetNow();
                query.create_remark = item.create_remark == null ? "" : item.create_remark;
                query.checkmid = UserId;
                query.checkstatus = (int)CheckState.Checked;
                query.checktime = UnixTimeHelper.GetNow();
                query.checkinfo = (int)CheckInfo.OK;
                query.check_remark = item.check_remark == null ? "" : item.check_remark;
                query.file_url = url;
                query.file_name = item.file_name;
                query.file_size = size;
                query.toll_gate_code = item.toll_gate_code;
                query.process_code = item.process_code;
                query.machine_code = item.machine_code;
                query.program_version = item.program_version;
                var programs = _sigerProjectDncProgramRepository.GetList(q =>
                    q.toll_gate_code == query.toll_gate_code && q.status == (int)RowState.Valid).FirstOrDefault();
                if (programs != null && programs.program_code != query.program_code)
                {
                    errors.Add($"{item.program_code},{(int)RequestEnum.ProgramTollGateCodeExsit}");
                }

                list.Add(query);
            }
            
            
            if (errors.Any())
            {
                return new ImportObjectResult(0, string.Join(";", errors));
            }
            _sigerProjectDncProgramRepository.Insert(list);
            if (_unitOfWork.Commit() > 0)
            {
                return new ImportObjectResult(1, "1");
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

         /// <summary>
         /// 上传zip文件
         /// </summary>
         /// <returns></returns>
         [HttpPost]
         public async Task<IActionResult> Upload()
         {
            var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "download/dnc/temporaryzip");
            DeleteFolder(dir);
            var files = Request.Form.Files;
             //同时只能上传一个文件
             if (1 != files.Count)
             {
                 //只允许上传单个文件
                 throw new BadRequestException(RequestEnum.ErrorFileCount);
             }

             var formFile = files.First();
             var allowTypes = new ArrayList
                 {".zip"};
             var fileType = Path.GetExtension(formFile.FileName).ToLower();
             if (!allowTypes.Contains(fileType))
             {
                 //文件类型错误
                 throw new BadRequestException(RequestEnum.ErrorFileType);
             }
             var physicaPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                 CommonConst.DownloadProgramTemporaryZIPFilePath);
             if (!Directory.Exists(physicaPath))
             {
                 Directory.CreateDirectory(physicaPath);
             }
             try
             {
                 var filePath = Path.Combine(physicaPath, Guid.NewGuid() + fileType);
                 using (var stream = new FileStream(filePath, FileMode.Create))
                 {
                     await formFile.CopyToAsync(stream);
                 }
                 DNCHttpUtility.ExtractToDirectory(filePath);
                 return new ObjectResult(new
                 {
                     file_url = FileUtility.GetDisplayPath(filePath), name = formFile.FileName, size = formFile.Length
                 });
             }
             catch (Exception e)
             {
                 Logger.WriteLineError($"upload {formFile} failed, error:" + e.Message);
                 throw new BadRequestException(RequestEnum.ImportFailed);
             }
         }

         /// <summary>
         /// 上传关系文件
         /// </summary>
         /// <returns></returns>
         [HttpPost]
         public async Task<IActionResult> UploadFile()
         {
             var files = Request.Form.Files;

             //同时只能上传一个文件
             if (1 != files.Count)
             {
                 //只允许上传单个文件
                 throw new BadRequestException(RequestEnum.ErrorFileCount);
             }

             var formFile = files.First();
             var allowTypes = new ArrayList { ".txt",".json", ".eia", ".mpf", ".min", ".spf", ".cnc", ".nc", ".prg", ".dwg", ".jpg", ".eng" };
             var fileType = Path.GetExtension(formFile.FileName).ToLower();
             if (!allowTypes.Contains(fileType))
             {
                 //文件类型错误
                 throw new BadRequestException(RequestEnum.ErrorFileType);
             }
             var physicaPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CommonConst.DownloadProgramTemporaryZIPFilePath);
             if (!Directory.Exists(physicaPath))
             {
                 Directory.CreateDirectory(physicaPath);
             }
             try
             {
                 var filePath = Path.Combine(physicaPath, Guid.NewGuid() + fileType);
                 using (var stream = new FileStream(filePath, FileMode.Create))
                 {
                     await formFile.CopyToAsync(stream);
                 }
                 return new ObjectResult(new { file_url = FileUtility.GetDisplayPath(filePath), name = formFile.FileName, size = formFile.Length });
             }
             catch (Exception e)
             {
                 Logger.WriteLineError($"upload {formFile} failed, error:" + e.Message);
                 throw new BadRequestException(RequestEnum.ImportFailed);
             }
         }

         private void LoadJson()
         {
             using (StreamReader r = new StreamReader("file.json"))
             {
                 string json = r.ReadToEnd();
                 List<siger_project_dnc_program> items = JsonConvert.DeserializeObject<List<siger_project_dnc_program>>(json);
             }

         }
         /// <summary>
         /// 导出
         /// </summary>
         /// <param name="req"></param>
         /// <returns></returns>
         [HttpPost]
         public IActionResult DownloadProgram([FromBody]RequestDownloadPrograms req)
         {
            string rootPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var programResult = _sigerProjectDncProgramRepository.GetList(q => req.request.Contains(q.id));
            var list = new List<RequestDownloadProgramList>();
            foreach (var item in programResult)
            {
                var query = new RequestDownloadProgramList();
                query.program_code = item.program_code;
                query.productid = item.productid;
                query.file_name = item.file_name;
                query.toll_gate_code = item.toll_gate_code;
                query.process_code = item.process_code;
                query.machine_code = item.machine_code;
                query.program_version = item.program_version;
                list.Add(query);
            }
            var strJson = JsonConvert.SerializeObject(list);
            var programPath = Path.Combine(rootPath, CommonConst.DownloadProgramZIPFilePath);
            if (!Directory.Exists(programPath))
            {
                Directory.CreateDirectory(programPath);
            }
            StreamWriter sw = new StreamWriter(programPath + "program.json");//这里写上你要保存的路径
            sw.WriteLine(strJson);//按行写
            sw.Close();//关闭
            var jsonPath= $"Files/program.json";


            //获取程序后缀名
            var programs = new List<siger_project_dnc_program>();
            for (int i = 0; i < req.data.Count; i++)
            {
                var dncprogram = _sigerProjectDncProgramRepository.Get(q =>
                 q.status == (int)RowState.Valid && q.projectid == ProjectId && q.program_code== req.data[i] && q.id== req.request[i]);
                programs.Add(dncprogram);
            }
             

             var dicts = new Dictionary<string, string>();
            foreach (var program in programs)
             {
                 dicts.Add(program.file_name,program.file_url);
             }

             var result = DNCHttpUtility.DownloadPrograFile(dicts);
             return new ObjectResult(new { result, jsonPath });
         }
        /// <summary>
        /// 清空文件夹
        /// </summary>
        /// <param name="dir"></param>
         public static void DeleteFolder(string dir)
         {
             foreach (string d in Directory.GetFileSystemEntries(dir))
             {
                 if (System.IO.File.Exists(d))
                 {
                     FileInfo fi = new FileInfo(d);
                     if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                         fi.Attributes = FileAttributes.Normal;
                     System.IO.File.Delete(d);//直接删除其中的文件    
                 }
                 else
                 {
                     DirectoryInfo d1 = new DirectoryInfo(d);
                     if (d1.GetFiles().Length != 0)
                     {
                         DeleteFolder(d1.FullName);////递归删除子文件夹  
                     }
                     Directory.Delete(d);
                 }
             }
         }
    }
}