using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.ApiACC.Controllers
{
    [Consumes("application/json", "multipart/form-data")]
    public class UploadController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerTrMaterialsRepository _materialsRepository;
        private readonly ISigerTrMaterialTypeRepository _materialTypeRepository;
        private readonly ISigerTrAssemblyMaintenanceRepository _assemblyMaintenanceRepository;
        private readonly ISigerTrProductStructureRepository _productStructureRepository;
        private readonly ISigerDict _sigerDict;
        private readonly ISigerEquipment _sigerEquipment;
        private readonly ISigerEquipmentPosition _sigerEquipmentPosition;
        private readonly ISigerRoutingEventNo _sigerRoutingEvenNo;
        private readonly ISigerRoutingOutStation _sigerRoutingOut;
        private readonly ISigerRoutingInStation _sigerRoutingIn;
        private readonly ISigerPackingFullQty _sigerPackingFull;
        private readonly ISigerCheckItem _checkItem;
        private readonly ISigerWOBookingItem _sigerWOBooking;
        private readonly IBasketSettingRepository _basketSetting;
        private readonly ITrParameterConfigRepository _parameterConfigRepository;
        private readonly ISeriNumCfg _serinumCfgRepository;
        private readonly IAutomationFixtureToolsCategoryRepository _fixtureToolsCategoryRepository;
        private readonly IAutomationFixtureToolsRepository _fixtureToolsRepository;
        private readonly IAutomationFixtureToolsProductRepository _fixtureToolsProductRepository;
        private readonly IAutomationFixtureToolsAssemblyRepository _fixtureToolsAssemblyRepository;
        private readonly IAutomationLocationRepository _autoLocationRepository;
        public UploadController(IUnitOfWork unitOfWork,ISigerTrMaterialsRepository materialsRepository, ISigerTrMaterialTypeRepository materialTypeRepository, 
            ISigerTrAssemblyMaintenanceRepository assemblyMaintenanceRepository, ISigerTrProductStructureRepository productStructureRepository
            , ISigerDict sigerDict, ISigerEquipment sigerEquipment, ISigerEquipmentPosition sigerEquipmentPosition, ISigerRoutingEventNo routingEvenNo
            , ISigerRoutingOutStation sigerRoutingOutStation, ISigerRoutingInStation sigerRoutingIn, ISigerPackingFullQty sigerPackingFull
            , ISigerCheckItem checkItem, ISigerWOBookingItem sigerWOBooking, IBasketSettingRepository basketSetting, ITrParameterConfigRepository parameterConfigRepository,
            ISeriNumCfg serinumCfgRepository, IAutomationFixtureToolsCategoryRepository fixtureToolsCategoryRepository, IAutomationFixtureToolsRepository fixtureToolsRepository,
            IAutomationFixtureToolsProductRepository fixtureToolsProductRepository, IAutomationFixtureToolsAssemblyRepository fixtureToolsAssemblyRepository,
            IAutomationLocationRepository autoLocationRepository)
        {
            _unitOfWork = unitOfWork;
            _materialsRepository = materialsRepository;
            _materialTypeRepository = materialTypeRepository;
            _assemblyMaintenanceRepository = assemblyMaintenanceRepository;
            _productStructureRepository = productStructureRepository;
            _sigerDict = sigerDict;
            _sigerEquipment = sigerEquipment;
            _sigerEquipmentPosition = sigerEquipmentPosition;
            _sigerRoutingEvenNo = routingEvenNo;
            _sigerRoutingOut = sigerRoutingOutStation;
            _sigerRoutingIn = sigerRoutingIn;
            _sigerPackingFull = sigerPackingFull;
            _checkItem = checkItem;
            _sigerWOBooking = sigerWOBooking;
            _basketSetting = basketSetting;
            _parameterConfigRepository = parameterConfigRepository;
            _serinumCfgRepository = serinumCfgRepository;
            _fixtureToolsCategoryRepository = fixtureToolsCategoryRepository;
            _fixtureToolsRepository = fixtureToolsRepository;
            _fixtureToolsProductRepository = fixtureToolsProductRepository;
            _fixtureToolsAssemblyRepository = fixtureToolsAssemblyRepository;
            _autoLocationRepository = autoLocationRepository;
        }

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

        private CommonImportResult UploadAction(TemplateNameEnums template, string temporaryFilePath)
        {
            CommonImportResult result;
            switch (template)
            {
                case TemplateNameEnums.MaterialTypeInfo:
                    result = ImportMaterialTypeInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.MaterialsInfo:
                    result = ImportMaterialsInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.AssemblyMaintenanceInfo:
                    result = ImportAssemblyMaintenanceInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.ProductStructureInfo:
                    result = ImportProductStructureInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.DictInfo:
                    result = ImportDictInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.EquipmentInfo:
                    result = ImportEquipmentInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.EquipmentPositionInfo:
                    result = ImportEquipmentPositionInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.RoutingEventNoInfo:
                    result = ImportRoutingEventNoInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.RoutingOutStationInfo:
                    result = ImportRoutingOutStationInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.RoutingInStationInfo:
                    result = ImportRoutingInStationInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.PackingFullQtyInfo:
                    result = ImportPackingFullQtyInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.OQCCheckItemInfo:
                    result = ImportOQCCheckItemInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.WOBookingItemInfo:
                    result = ImportWOBookingItemInfo(temporaryFilePath);
                    break;
                case TemplateNameEnums.Basketf:
                    result = ImportBasket(temporaryFilePath);
                    break;
                case TemplateNameEnums.RoutingstationInfo:
                    result = ImportRoutingData(temporaryFilePath);
                    break;
                case TemplateNameEnums.TrParameterConfig:
                    result = ImportTrParameterConfig(temporaryFilePath);
                    break;
                case TemplateNameEnums.SnRule:
                    result = ImportSnRule(temporaryFilePath);
                    break;
                case TemplateNameEnums.FixtureToolsCategoryTemplate:
                    result = ImportFixtureToolsCategory(temporaryFilePath);
                    break;
                case TemplateNameEnums.FixtureToolsTemplate:
                    result = ImportFixtureTools(temporaryFilePath);
                    break;
                case TemplateNameEnums.FixtureToolsProductTemplate:
                    result = ImportFixtureToolsProduct(temporaryFilePath);
                    break;
                case TemplateNameEnums.FixtureToolsAssmeblyTemplate:
                    result = ImportFixtureToolsAssembly(temporaryFilePath);
                    break;
                case TemplateNameEnums.AutomationLocationTemplate:
                    result = ImportAutomationLocation(temporaryFilePath);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            return result;
        }

        /// <summary>
        /// 物料类别信息导入
        /// </summary>
        /// <param name="temporaryFilePath"></param>
        /// <returns></returns>
        private CommonImportResult ImportMaterialTypeInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<MaterialTypeList> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<MaterialTypeList>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var products = excelHelper.ConvertSheetToList();
                if (!products.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _materialTypeRepository.ImportMaterialTypes(products, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportMaterialTypeInfo failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportMaterialsInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<MaterialTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<MaterialTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var materials = excelHelper.ConvertSheetToList();
                if (!materials.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _materialsRepository.ImportMaterials(materials, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportMaterialsInfo failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportAssemblyMaintenanceInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<AssemblyMaintenanceTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<AssemblyMaintenanceTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var assemblyMaintenances = excelHelper.ConvertSheetToList();
                if (!assemblyMaintenances.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _assemblyMaintenanceRepository.ImportAssemblyMaintenances(assemblyMaintenances, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportAssemblyMaintenanceListInfo failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportProductStructureInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<ProductStructureTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<ProductStructureTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var ProductStructures = excelHelper.ConvertSheetToList();
                if (!ProductStructures.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _productStructureRepository.ImportPorductStructure(ProductStructures, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportPorductStructureListInfo failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportDictInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<DictTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<DictTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var dicts = excelHelper.ConvertSheetToList();
                if (!dicts.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _sigerDict.ImportDict(dicts, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportDict failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportEquipmentInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<EquipmentTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<EquipmentTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var equipments = excelHelper.ConvertSheetToList();

                var errors = new List<string>();
                var rowIndex = 1;
                foreach (var p in equipments)
                {
                    rowIndex++;
                    var drivers = _sigerDict.Get(t => t.dval == p.eqdriver && t.status == (int)RowState.Valid && t.cat == AccDictCost.eqdriver&&t.projectId==ProjectId);
                    var types = _sigerDict.Get(t => t.dval == p.eqtype && t.status == (int)RowState.Valid && t.cat== AccDictCost.eqtype && t.projectId == ProjectId);
                    var model = _sigerEquipment.Get(t => (t.EqId == p.eqid || t.EqName == p.eqname) && t.projectId == ProjectId && t.status == (int)RowState.Valid);
                    var models = equipments.Where(t => (t.eqid == p.eqid || t.eqname == p.eqname));

                    if (drivers == null)
                        errors.Add($"{rowIndex},{(int)RequestEnum.NotFindDriver}");
                    if (types == null)
                        errors.Add($"{rowIndex},{(int)RequestEnum.MachineTypeNotFound}");
                    if (model != null || models.Count() > 1)
                    {
                        errors.Add($"{rowIndex},{(int)RequestEnum.MachineCodeOrNameIsExsit}");
                    }
                }
                if (errors.Any())
                {
                    return new CommonImportResult(0, string.Join(';', errors));
                }

                if (!equipments.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var entities = new List<SigerTrEquipment>();
                foreach (var p in equipments)
                {
                    var drivers = _sigerDict.Get(t => t.dval == p.eqdriver && t.status == (int)RowState.Valid);
                    var types = _sigerDict.Get(t => t.dval == p.eqtype && t.status == (int)RowState.Valid);
                    if (drivers != null && types != null)
                    {
                        var psEntity = new SigerTrEquipment
                        {
                            projectId = ProjectId,
                            EqName = p.eqname ?? "",
                            EqId = p.eqid ?? "",
                            EqDriver = !string.IsNullOrEmpty(drivers.dkey) ? drivers.dkey : "",
                            EqType = !string.IsNullOrEmpty(types.dkey) ? types.dkey : "",
                            Para = p.para ?? "",
                            UID = UserId.ToStr(),
                            TransDateTime = DateTime.Now
                        };
                        entities.Add(psEntity);
                    }
                }
                _sigerEquipment.Insert(entities);
                if (_unitOfWork.Commit() > 0)
                    return new CommonImportResult(1, "1");
                else
                    throw new BadRequestException(RequestEnum.ImportFailed);
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportEquipment failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportEquipmentPositionInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<EquipmentPositionTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<EquipmentPositionTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var EquipmentPositions = excelHelper.ConvertSheetToList();
                if (!EquipmentPositions.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _sigerEquipmentPosition.ImportEquipmentPosition(EquipmentPositions, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportDict failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportRoutingEventNoInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<RoutingEventNoTemplate> excelHelper = null;
            try
            { 
                excelHelper = new EpPlusExcelHelper<RoutingEventNoTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var eventnos = excelHelper.ConvertSheetToList();

                var errors = new List<string>();
                var rowIndex = 1;
                foreach (var p in eventnos)
                {
                    rowIndex++;
                    var dicts = _sigerDict.Get(t => t.dval == p.eventno && t.status == (int)RowState.Valid && t.cat == AccDictCostNoProjectId.eventno);
                    if (dicts == null)
                    {
                        errors.Add($"{rowIndex},{(int)RequestEnum.EventNoNotFind}");
                    }
                    else
                    {
                        var model = _sigerRoutingEvenNo.Get(t => t.EventNo.ToStr() == dicts.dkey && t.projectId == ProjectId && t.status == (int)RowState.Valid);
                        var repeats = eventnos.Where(t => t.eventno.ToStr() == dicts.dkey);
                        if (model != null || repeats.Count() > 1)
                        {
                            errors.Add($"{rowIndex},{(int)RequestEnum.EventNoIsExsit}");
                        }
                    }
                }
                if (errors.Any())
                {
                    return new CommonImportResult(0, string.Join(';', errors));
                }
                if (!eventnos.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }

                var entities = new List<SigerTrRoutingEventNo>();
                foreach (var p in eventnos)
                {
                    var dicts = _sigerDict.Get(t => t.dval == p.eventno && t.status == (int)RowState.Valid);
                    if (dicts != null)
                    {
                        var psEntity = new SigerTrRoutingEventNo
                        {
                            projectId = ProjectId,
                            EventNo = dicts.dkey.ToInt(),
                            Descr = p.descr ?? ""
                        };
                        entities.Add(psEntity);
                    }
                }
                _sigerRoutingEvenNo.Insert(entities);
                if (_unitOfWork.Commit() > 0)
                    return new CommonImportResult(1, "1");
                else
                    throw new BadRequestException(RequestEnum.ImportFailed);
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportEquipment failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportRoutingOutStationInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<RoutingOutStationTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<RoutingOutStationTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var outstations = excelHelper.ConvertSheetToList();
                if (!outstations.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _sigerRoutingOut.ImportRoutingOutStation(outstations, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportRoutingOutStation failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportRoutingInStationInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<RoutingInStationTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<RoutingInStationTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var instations = excelHelper.ConvertSheetToList();
                if (!instations.Any())
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }
                var result = _sigerRoutingIn.ImportRoutingInStation(instations, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportRoutingInStation failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportOQCCheckItemInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<OQCCheckItemTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<OQCCheckItemTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var chectitems = excelHelper.ConvertSheetToList();
                if (!chectitems.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _checkItem.ImportOQCCheckItem(chectitems, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportOQCCheckItem failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportPackingFullQtyInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<PackingFullQtyTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<PackingFullQtyTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var instations = excelHelper.ConvertSheetToList();
                if (!instations.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _sigerPackingFull.ImportPackingFullQty(instations, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportPackingFullQty failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportWOBookingItemInfo(string temporaryFilePath)
        {
            EpPlusExcelHelper<WOBookingItemTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<WOBookingItemTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var instations = excelHelper.ConvertSheetToList();
                if (!instations.Any())
                {
                    throw new BadRequestException(CommonEnum.DataNotNull);
                }
                var result = _sigerWOBooking.ImportWoBookingItem(instations, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportWOBookingItem failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }
        private CommonImportResult ImportBasket(string temporaryFilePath)
        {
            EpPlusExcelHelper<BasketTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<BasketTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var instations = excelHelper.ConvertSheetToList();
                var result = _basketSetting.ImportBasketItem(instations, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportWOBookingItem failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }
        private CommonImportResult ImportRoutingData(string temporaryFilePath)
        {
            EpPlusExcelHelper<RoutingData> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<RoutingData>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var instations = excelHelper.ConvertSheetToList();
                var result = _sigerRoutingIn.ImportRoutingData(instations, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportWOBookingItem failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportTrParameterConfig(string temporaryFilePath)
        {
            EpPlusExcelHelper<TrParameterConfigTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<TrParameterConfigTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var instations = excelHelper.ConvertSheetToList();
                var result = _parameterConfigRepository.ImportConfig(instations, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportTrParameterConfig failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }
        private CommonImportResult ImportSnRule(string temporaryFilePath)
        {
            EpPlusExcelHelper<SerinCfgConfigTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<SerinCfgConfigTemplate>(temporaryFilePath);
                var messages = excelHelper.CheckExcel();
                if (messages.Any())
                {
                    return new CommonImportResult(0, string.Join(';', messages));
                }
                var instations = excelHelper.ConvertSheetToList();
                var result = _serinumCfgRepository.ImportSerinCfg(instations, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportTrParameterConfig failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }


        private CommonImportResult ImportFixtureToolsCategory(string temporaryFilePath)
        {
            EpPlusExcelHelper<FixtureToolsCategoryTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<FixtureToolsCategoryTemplate>(temporaryFilePath);
                var checkResult = excelHelper.CheckExcel();
                if (checkResult.Any())
                {
                    return new CommonImportResult(0, string.Join(';', checkResult));
                }
                var data = excelHelper.ConvertSheetToList();
                var result = _fixtureToolsCategoryRepository.ImportData(data, ProjectId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportFixtureToolsCategory failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportFixtureTools(string temporaryFilePath)
        {
            EpPlusExcelHelper<FixtureToolsTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<FixtureToolsTemplate>(temporaryFilePath);
                var checkResult = excelHelper.CheckExcel();
                if (checkResult.Any())
                {
                    return new CommonImportResult(0, string.Join(';', checkResult));
                }
                var data = excelHelper.ConvertSheetToList();
                var result = _fixtureToolsRepository.ImportData(data, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportFixtureTools failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportFixtureToolsProduct(string temporaryFilePath)
        {
            EpPlusExcelHelper<FixtureToolsProductTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<FixtureToolsProductTemplate>(temporaryFilePath);
                var checkResult = excelHelper.CheckExcel();
                if (checkResult.Any())
                {
                    return new CommonImportResult(0, string.Join(';', checkResult));
                }
                var data = excelHelper.ConvertSheetToList();
                var result = _fixtureToolsProductRepository.ImportData(data, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportFixtureToolsProduct failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportFixtureToolsAssembly(string temporaryFilePath)
        {
            EpPlusExcelHelper<FixtureToolsAssmeblyTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<FixtureToolsAssmeblyTemplate>(temporaryFilePath);
                var checkResult = excelHelper.CheckExcel();
                if (checkResult.Any())
                {
                    return new CommonImportResult(0, string.Join(';', checkResult));
                }
                var data = excelHelper.ConvertSheetToList();
                var result = _fixtureToolsAssemblyRepository.ImportData(data, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportFixtureToolsAssembly failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }

        private CommonImportResult ImportAutomationLocation(string temporaryFilePath)
        {
            EpPlusExcelHelper<AutomationLocationTemplate> excelHelper = null;
            try
            {
                excelHelper = new EpPlusExcelHelper<AutomationLocationTemplate>(temporaryFilePath);
                var checkResult = excelHelper.CheckExcel();
                if (checkResult.Any())
                {
                    return new CommonImportResult(0, string.Join(';', checkResult));
                }
                var data = excelHelper.ConvertSheetToList();
                var result = _autoLocationRepository.ImportData(data, ProjectId, UserId);
                return result;
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ImportAutomationLocation failed，error: " + e.Message);
                throw;
            }
            finally
            {
                excelHelper?.Dispose();
            }
        }
    }
}
