using System;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Exceptions;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.ApiCNC.Controllers
{
    [Consumes("application/json", "multipart/form-data")]
    public class UploadController : BaseController
    {
        private readonly IProductPlanRepository _planRepository;
        private readonly IProductionBeatSetRepository _beatSetRepository;
        private readonly ISigerProjectLevelRepository _projectLevelRepository;
        private readonly IMachineWordingModeRepository _wordingModeRepository;
        public UploadController(IProductPlanRepository planRepository, IMachineWordingModeRepository wordingModeRepository, IProductionBeatSetRepository beatSetRepository, ISigerProjectLevelRepository projectLevelRepository)
        {
            _planRepository = planRepository;
            _beatSetRepository = beatSetRepository;
            _projectLevelRepository = projectLevelRepository;
            _wordingModeRepository = wordingModeRepository;
        }

        [HttpPost]
        public IActionResult UploadImage(IFormFile formFile)
        {
            if (Request.Form?.Files == null)
            {
                throw new BadRequestException(ConfigEnum.UploadFileNotFound);
            }

            var date = DateTime.Now.ToString("yyyy-MM-dd");
           

            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, "image", date);
            var files = Request.Form.Files;
            var file = files[0];
            var temporaryFileName = Guid.NewGuid().ToString("N") + FileHelper.GetExtension(file.FileName);
            var fileName = Path.Combine(rootDir, temporaryFileName);

            using (var stream = new FileStream(fileName, FileMode.Create))
            {
                file.CopyTo(stream);
            }

            return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/image/{date}/{temporaryFileName}");
        }

        [HttpPost]
        public IActionResult Submit(string templateName)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new BadRequestException(ConfigEnum.FileNameIsEmpty);
            }

            var files = Request.Form.Files;
            if (files == null)
            {
                throw new BadRequestException(ConfigEnum.UploadFileNotFound);
            }

            var file = files[0];
            if (!FileHelper.IsExcelFile(file.FileName))
            {
                throw new BadRequestException(ConfigEnum.IsNotExcelFile);
            }
            var result = Enum.TryParse(typeof(TemplateNameEnums), templateName, true, out var template);
            if (!result)
            {
                throw new BadRequestException(ConfigEnum.TemplateFileNotFound);
            }
            var fileSetting = Config<FileSettings>.Get();
            if (fileSetting == null)
            {
                throw new BadRequestException(CommonEnum.GetCommCfgFailed);
            }
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            

            //save file
            var temporaryFileName = $"{templateName}_{DateTime.Now:yyyyMMddHHmmss}{FileHelper.GetExtension(file.FileName)}";
            var fileName = Path.Combine(rootDir, temporaryFileName);
            try
            {
                using (var stream = new FileStream(fileName, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                if (!System.IO.File.Exists(fileName))
                {
                    throw new BadRequestException(RequestEnum.ImportFailed);
                }
                var res = UploadAction((TemplateNameEnums)template, fileName);
                if (res.ret == 1)
                {
                    FileHelper.DeleteFile(temporaryFileName);
                    return new ImportObjectResult(res.ret, "1");
                }

                return new ImportObjectResult(res.ret, res.msg);
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"import {templateName} failed, error:" + e);
                throw new BadRequestException(RequestEnum.ImportFailed);
            }
        }

        private CommonImportResult UploadAction(TemplateNameEnums template, string temporaryFilePath)
        {
            CommonImportResult result;
            switch (template)
            {
                case TemplateNameEnums.ProducePlan:
                    result = ImportProducePlan(temporaryFilePath);
                    break;
                case TemplateNameEnums.ProductionPlan://生产计划管理
                    result = ImportProductionPlan(temporaryFilePath);
                    break;
                case TemplateNameEnums.BeatAllocation:
                    result = ImportBeatAllocation(temporaryFilePath);
                    break;
                case TemplateNameEnums.WorkModeList:
                    result = ImportWorkModeList(temporaryFilePath);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            return result;
        }

        private CommonImportResult ImportProducePlan(string temporaryFilePath)
        {
            EpPlusExcelHelper<ProducePlanList> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<ProducePlanList>(temporaryFilePath, _projectLevelRepository.GetProjectLanguage(ProjectId));
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }

                var plans = excelHelper.ConvertSheetToList();
                if (ProjectId == 153)
                {
                    var result = _planRepository.ImportXuGongProducePlan(plans, ProjectId);
                    return result;
                }
                else
                {
                    var result = _planRepository.ImportProducePlan(plans, ProjectId);
                    return result;
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }
        /// <summary>
        /// 生产计划管理
        /// </summary>
        /// <param name="temporaryFilePath"></param>
        /// <returns></returns>
        private CommonImportResult ImportProductionPlan(string temporaryFilePath)
        {
            EpPlusExcelHelper<ProductionPlanList> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<ProductionPlanList>(temporaryFilePath, _projectLevelRepository.GetProjectLanguage(ProjectId));
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var plans = excelHelper.ConvertSheetToList();
                var result = _planRepository.ImportProductionPlan(plans, ProjectId);
                return result;
            }
            catch
            {
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportBeatAllocation(string temporaryFilePath)
        {
            var excelHelper = new EpPlusForBeatSetHelper();
            try
            {
                var titles = _projectLevelRepository.GetLevelTitles(0, ProjectId).ToList();

                var messages = excelHelper.CheckExcel(temporaryFilePath, titles.Count);
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }

                var beats = excelHelper.ConvertSheetToList(titles.Count);
                var result = _beatSetRepository.ImportBeats(beats, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportBeatAllocation failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper.Dispose();
            }
        }

        private CommonImportResult ImportWorkModeList(string temporaryFilePath)
        {
            EpPlusExcelHelper<WorkModeList> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<WorkModeList>(temporaryFilePath, _projectLevelRepository.GetProjectLanguage(ProjectId));
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }

                var WorkModeLists = excelHelper.ConvertSheetToList();
                var result = _wordingModeRepository.ImportWorkModeLists(WorkModeLists, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportBoxList failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }
    }


}