using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Request;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;
using System.IO;
using Siger.Middlelayer.Log;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.QmsRepository.Entities;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Common.Helpers;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Siger.ApiQMS.Controllers
{
    public class WorkCellStationController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IQmsCellStationRepository _qmsCellStationRepository;
        private readonly IQmscellRepository _qmscellRepository;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSection;


        public WorkCellStationController(IUnitOfWork unitOfWork,IQmsCellStationRepository qmsCellStationRepository, ISigerProjectLevelSectionRepository sigerProjectLevelSection, IQmscellRepository qmscellRepository)
        {
            _unitOfWork = unitOfWork;
            _qmsCellStationRepository = qmsCellStationRepository;
            _sigerProjectLevelSection = sigerProjectLevelSection;
            _qmscellRepository = qmscellRepository;
        }

        /// <summary>
        ///  
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="section"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetList(int productId,int section,int page,int pageSize)
        {
            var levelsections = _sigerProjectLevelSection.GetLevelSectionIds(section, ProjectId);
            var data = _qmsCellStationRepository.GetCellStationPagedList(productId, levelsections, ProjectId, page, pageSize);
            var result = data.Data.ToList();
            foreach (var d in result)
            {
                d.SectionDesc = GetAllTitle(d.Section);
            }
            return new PagedLongTotalObjectResult(result, data.Total, page, pageSize);
        }
        private string GetAllTitle(int sectionId)
        {
            var titles = _sigerProjectLevelSection.GetLevelSectionTitles(sectionId, ProjectId);
            var list = titles.ToList();
            return list.Any() ? string.Join('-', list) : string.Empty;
        }

        /// <summary>
        /// add
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody]RequestCellStation request)
        {
   
            var cellCombox = _qmscellRepository.Get(f => f.projectid == ProjectId && f.id == request.cell);
            if (cellCombox == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            if (_qmsCellStationRepository.IsExist(f => f.projectid == ProjectId && f.section == request.section))
                throw new BadRequestException(CommonEnum.RecordExits);

            if (_qmsCellStationRepository.IsExist(f => f.projectid == ProjectId && f.cell == request.cell && f.step == request.index))
                throw new BadRequestException(QMSEnum.StepExits);

            _qmsCellStationRepository.Insert(new Middlelayer.QmsRepository.Entities.siger_qms_cell_station
            {
                projectid = ProjectId,
                cell = request.cell,
                section = request.section,
                step = request.index,
                status = (int)RowState.Valid
            });

            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// update 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Modify([FromBody]RequestCellStation request)
        {
            var obj = _qmsCellStationRepository.Get(f => f.projectid == ProjectId && f.id == request.id);

            if (obj==null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            //if (_qmsCellStationRepository.IsExist(f => f.projectid == ProjectId && f.section == request.section ))
            //    throw new BadRequestException(CommonEnum.RecordExits);

            //if (_qmsCellStationRepository.IsExist(f=>f.projectid==ProjectId && f.cell==request.cell && f.step==request.index))
            //    throw new BadRequestException(QMSEnum.StepExits);

            obj.cell = request.cell;
            obj.section = request.section;
            obj.step = request.index;
            _qmsCellStationRepository.Update(obj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// del
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Del([FromBody]RequestIds request)
        {
            if (!request.ids.Any())
                throw new BadRequestException(RequestEnum.ParameterMiss);
            foreach (var id in request.ids)
            {
                var obj = _qmsCellStationRepository.Get(f => f.id == id);
                if (obj == null)
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                _qmsCellStationRepository.Delete(obj);
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult ExportExcel(int productId, int section)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            if (!Directory.Exists(rootDir))
                Directory.CreateDirectory(rootDir);

            var levelsections = _sigerProjectLevelSection.GetLevelSectionIds(section, ProjectId);
            var data = _qmsCellStationRepository.GetCellStationPagedList(productId, levelsections, ProjectId, 1,
                999999);
            var result = data.Data.ToList();

            var dataList = new List<ImportWorkCellStation>();
            var no = 1;
            foreach (var d in result)
            {
                var lineObj = _sigerProjectLevelSection.Get(f => f.id == d.Line);
                var sectionObj = _sigerProjectLevelSection.Get(f => f.id == d.Section);
                dataList.Add(new ImportWorkCellStation
                {
                    Line = lineObj != null ? lineObj.title : d.Line.ToString(),
                    Section = sectionObj != null ? sectionObj.title : d.Section.ToString(),
                    Cell = d.Cell,
                    NextCell = d.NextCell,
                    Index = d.Index,
                    No = no
                });
                no++;
            }

            if (dataList.Any())
            {
                EpPlusExcelHelper<ImportWorkCellStation> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<ImportWorkCellStation>();
                    var temporaryFileName = $"通道工作单元_InspectionStandardInfo_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(dataList, Path.Combine(rootDir, temporaryFileName), true);
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("ExportExcel ImportWorkCellStation Info failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

    }
}
