using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;
using Siger.Middlelayer.Share.ModuleEnum;

namespace Siger.ApiKPI.Controllers
{
    public class UploadController : BaseController
    {
        private readonly ISigerKpiItem _sigerKpitem;
        private readonly ISigerKpiTasklist _sigerKpiTasklist;
        private readonly ISigerProjectSectionRepository _sigerProjectSection;
        public UploadController(ISigerKpiItem sigerKpi, ISigerKpiTasklist sigerKpiTasklist, ISigerProjectSectionRepository sigerProjectSection)
        {
            _sigerKpitem = sigerKpi;
            _sigerKpiTasklist = sigerKpiTasklist;
            _sigerProjectSection = sigerProjectSection;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="templateName"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadExcel(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.ImportFileName);
           

            //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.Message);
                throw new BadRequestException(RequestEnum.ImportFailed);
            }
        }

        private CommonImportResult UploadAction(TemplateNameEnums template, string temporaryFilePath)
        {
            CommonImportResult result;
            switch (template)
            {
                case TemplateNameEnums.KpiItem:
                    result = ImportKpiItem(temporaryFilePath);
                    break;
                case TemplateNameEnums.KpiTaskAct:
                    result = ImportKpiTask(temporaryFilePath);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            return result;
        }
        /// <summary>
        /// 导入Task 当天日期目标值
        /// </summary>
        /// <param name="temporaryFilePath"></param>
        /// <returns></returns>
        private CommonImportResult ImportKpiTask(string temporaryFilePath)
        {
            EpPlusExcelHelper< ImportKpiTaskAct> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<ImportKpiTaskAct>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var taskActVal = excelHelper.ConvertSheetToList();
                var lstmsg = new List<string>();
                var busidateStr = DateTime.Now.ToString("yyyy-MM-dd");
                DateTime.TryParse(busidateStr, out DateTime busidate);
                foreach (var it in taskActVal)
                {
                    var permission = _sigerProjectSection.VerifyDepartment(UserId, it.Department);
                    if (!permission)
                    {
                        lstmsg.Add(it.Item + EnumHelper.GetEnumDesc(CommonEnum.NoDepartPermission));
                    }
                    var depart = _sigerProjectSection.Get(f => f.projectid == ProjectId && f.title == it.Department);
                    if (depart == null)
                    {
                        lstmsg.Add(it.Department + "不存在");
                    }
                    else
                    {
                        var item = _sigerKpitem.Get(f => f.projectId == ProjectId && f.Item == it.Item);
                        if (item==null)
                            lstmsg.Add(it.Item + " 指标不存在");
                        var task = _sigerKpiTasklist.Get(f => f.projectId == ProjectId && f.ItemId == item.id && f.Busidate==busidate);
                        if (task==null)
                            lstmsg.Add(it.Item + " 指标不存在");
                        if (task.Excption!=KpiExecption.Default)
                            lstmsg.Add(it.Item + " 指标已处理");
                    }
                   
                }
                if (lstmsg.Any())
                {
                    return new CommonImportResult(0, string.Join(';', lstmsg));
                }
                var result = _sigerKpiTasklist.ImportKpiTaskAct(taskActVal, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportKpiTask failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }
        /// <summary>
        /// 导入kpi 指标
        /// </summary>
        /// <param name="temporaryFilePath"></param>
        /// <returns></returns>
        private CommonImportResult ImportKpiItem(string temporaryFilePath)
        {
            EpPlusExcelHelper<ImportKpiItem> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<ImportKpiItem>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }

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