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.Middlelayer.Log;
using System;
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 Siger.Middlelayer.Utility.ImportEntities;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Common.Helpers;

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

        [HttpGet]
        public IActionResult GetList(int page, int pagesize, int toexcel)
        {
            var res = _standardCategoryRepository.GetPagedList(0, 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<ReponseInspectStandardCategory> data)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            if (!data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var dataList = new List<InspectStandardCategoryTemplate>();
            var index = 1;
            foreach (var item in data)
            {
                dataList.Add(new InspectStandardCategoryTemplate
                {
                    No = index,
                    name = item.name,
                    parentname = item.parentname
                });
                index++;
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<InspectStandardCategoryTemplate> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<InspectStandardCategoryTemplate>();
                    var temporaryFileName = $"检验项目类别_InspectStandardCategory_{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 Category failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpPost]
        public IActionResult Add([FromBody]RequestAddInspectStandardCategory req)
        {
            if (string.IsNullOrWhiteSpace(req.name))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            var entity = new siger_qms_inspection_standard_category
            {
                name = req.name,
                parentid = req.parentid.ToInt(),
                projectid = ProjectId
            };
            _standardCategoryRepository.Insert(entity);
            if(_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
        [HttpPost]
        public IActionResult Update([FromBody]RequestUpdateInspectStandardCategory req)
        {
            if (string.IsNullOrWhiteSpace(req.name))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            var entity = _standardCategoryRepository.Get(t => t.id == req.id && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid);
            if(entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var exsit = _standardCategoryRepository.Get(t => t.name == req.name && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid && t.id != req.id);
            if (exsit != null)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }

            entity.name = req.name;
            entity.parentid = req.parentid.ToInt();
            _standardCategoryRepository.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 = _standardCategoryRepository.GetList(t => req.ids.Contains(t.id) && t.status == (int)RowState.Valid &&
                t.projectid == ProjectId).ToList();
            if (!models.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var entities = new List<siger_qms_inspection_standard_category>();
            foreach (var model in models)
            {
                var lists = GetSonTypes(model.id);
                entities.Add(model);
                entities.AddRange(lists);
            }

            entities = entities.GroupBy(t => t.id).Select(t => t.FirstOrDefault()).ToList();
            foreach (var entity in entities)
            {
                if (entity == null)
                {
                    continue;
                }
                entity.status = (int)RowState.Invalid;
                _standardCategoryRepository.Update(entity);
            }

            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }            
        }
        private List<siger_qms_inspection_standard_category> GetSonTypes(int parentId)
        {
            var query = _standardCategoryRepository.GetList(t => t.parentid == parentId && t.status == (int)RowState.Valid && t.projectid == ProjectId);

            return query.ToList().Concat(query.ToList().SelectMany(t => GetSonTypes(t.id))).ToList();
        }

        [HttpGet]
        public IActionResult GetNameList()
        {
            var list = _standardCategoryRepository.GetSonCategorys(0, ProjectId).ToList();
            return new ObjectResult(list);
        }
    }
}