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

namespace Siger.ApiQMS.Controllers
{
    public class InspectStandardItemController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IInspectStandardItemRepository _standardItemRepository;
        private readonly IInspectStandardCategoryRepository _standardCategoryRepository;
        public InspectStandardItemController(IUnitOfWork unitOfWork, IInspectStandardItemRepository standardItemRepository,
            IInspectStandardCategoryRepository standardCategoryRepository)
        {
            _unitOfWork = unitOfWork;
            _standardItemRepository = standardItemRepository;
            _standardCategoryRepository = standardCategoryRepository;
        }

        [HttpGet]
        public IActionResult GetList(int page, int pagesize, int toexcel = 0)
        {
            var res = _standardItemRepository.GetPagedList(ProjectId, page, pagesize, toexcel);
            if(toexcel > 0)
            {
               return ExportExcel(res.Data.ToList());
            }
            return new PagedObjectResult(res.Data, res.Total, page, pagesize);
        }

        private IActionResult ExportExcel(List<ReponseInspectStandardItem> data)
        {
            
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            if (!data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var dataList = new List<InspectStandardItemTemplate>();
            var index = 1;
            foreach (var item in data)
            {
                dataList.Add(new InspectStandardItemTemplate
                {
                    No = index,
                    Category = item.categoryname,
                    UpperLimit = item.upperlimit.HasValue ? item.upperlimit.ToString() : "",
                    LowerLimit = item.lowerlimit.HasValue ? item.lowerlimit.ToString() : "",
                    SampleQuantity = item.samplequantity.ToString(),
                    ReceiveStandard = item.receivestandard.ToString()
                });
                index++;
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<InspectStandardItemTemplate> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<InspectStandardItemTemplate>();
                    var temporaryFileName = $"抽检标准维护_InspectStandardItem_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(dataList, Path.Combine(rootDir, temporaryFileName));
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("Export Inspect Standard Item failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Add([FromBody]RequestAddInspectStandardItem req)
        {
            if((string.IsNullOrEmpty(req.lowerlimit) && string.IsNullOrEmpty(req.upperlimit)) ||
                string.IsNullOrEmpty(req.samplequantity) || req.categoryid <= 0)
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            if(req.upperlimit.ToInt() <= req.lowerlimit.ToInt())
            {
                throw new BadRequestException(RequestEnum.MaxMinError);
            }

            var category = _standardCategoryRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                t.id == req.categoryid);
            if(category == null)
            {
                throw new BadRequestException(RequestEnum.CategoryNotNull);
            }

            var exsit = _standardItemRepository.Get(t => t.categoryid == req.categoryid && ((req.upperlimit.ToInt() >= t.lowerlimit &&
                req.upperlimit.ToInt() <= t.upperlimit || req.lowerlimit.ToInt() >= t.lowerlimit && req.lowerlimit.ToInt() <= t.upperlimit) &&
                t.upperlimit.HasValue && t.lowerlimit.HasValue || t.upperlimit.HasValue && !t.lowerlimit.HasValue && (req.lowerlimit.ToInt() <= t.upperlimit ||
                req.upperlimit.ToInt() <= t.upperlimit) || t.lowerlimit.HasValue && !t.upperlimit.HasValue && (req.lowerlimit.ToInt() >= t.lowerlimit ||
                req.upperlimit.ToInt() >= t.lowerlimit)) && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if(exsit != null)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }

            var entity = new siger_qms_inspection_standard_item
            {
                categoryid = category.id,
                upperlimit = req.upperlimit.ToInt(),
                lowerlimit = req.lowerlimit.ToInt(),
                samplequantity = req.samplequantity.ToInt(),
                receivestandard = req.receivestandard.ToInt(),
                projectid = ProjectId
            };
            _standardItemRepository.Insert(entity);
            if(_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);                
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
        [HttpPost]
        public IActionResult Update([FromBody]RequestUpdateInspectStandardItem req)
        {
            var entity = _standardItemRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                t.id == req.id);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            if ((string.IsNullOrEmpty(req.lowerlimit) && string.IsNullOrEmpty(req.upperlimit)) ||
                string.IsNullOrEmpty(req.samplequantity) || req.categoryid <= 0)
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            if (req.upperlimit.ToInt() <= req.lowerlimit.ToInt())
            {
                throw new BadRequestException(RequestEnum.MaxMinError);
            }

            var category = _standardCategoryRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                t.id == req.categoryid);
            if (category == null)
            {
                throw new BadRequestException(RequestEnum.CategoryNotNull);
            }

            var exsit = _standardItemRepository.Get(t => t.categoryid == req.categoryid && ((req.upperlimit.ToInt() >= t.lowerlimit &&
                req.upperlimit.ToInt() <= t.upperlimit || req.lowerlimit.ToInt() >= t.lowerlimit && req.lowerlimit.ToInt() <= t.upperlimit) &&
                t.upperlimit.HasValue && t.lowerlimit.HasValue || t.upperlimit.HasValue && !t.lowerlimit.HasValue && (req.lowerlimit.ToInt() <= t.upperlimit ||
                req.upperlimit.ToInt() <= t.upperlimit) || t.lowerlimit.HasValue && !t.upperlimit.HasValue && (req.lowerlimit.ToInt() >= t.lowerlimit ||
                req.upperlimit.ToInt() >= t.lowerlimit)) && t.id != req.id && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if (exsit != null)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }            

            entity.categoryid = req.categoryid;
            entity.upperlimit = req.upperlimit.ToInt();
            entity.lowerlimit = req.lowerlimit.ToInt();
            entity.samplequantity = req.samplequantity.ToInt();
            entity.receivestandard = req.receivestandard.ToInt();
            _standardItemRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);                
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
        [HttpPost]
        public IActionResult Delete([FromBody]RequestDeleteParameter req)
        {
            if (req.ids == null || !req.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var models = _standardItemRepository.GetList(t => req.ids.Contains(t.id) && t.status == (int)RowState.Valid &&
                t.projectid == ProjectId).ToList();
            if (!models.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            foreach(var model in models)
            {
                model.status = (int)RowState.Invalid;
                _standardItemRepository.Update(model);
            }

            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
    }
}