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.Log;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Request;
using Siger.Middlelayer.QmsRepository.Response;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;


namespace Siger.ApiQMS.Controllers
{
    public class WorkCellController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IQmscellRepository _qmscellRepository;
        private readonly IQmscellCfgRepository _qmscellCfg;

        public WorkCellController(IUnitOfWork unitOfWork, IQmscellRepository qmscellRepository, IQmscellCfgRepository qmscellCfg)
        {
            _unitOfWork = unitOfWork;
            _qmscellRepository = qmscellRepository;
            _qmscellCfg = qmscellCfg;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Getlist(int page,int pageSize)
        {
            var data = _qmscellRepository.GetCellComboxPagedList(ProjectId,page, pageSize);
            return new PagedLongTotalObjectResult(data.Data, data.Total, page, pageSize);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExportExcel()
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            var data = _qmscellRepository.GetCellComboxPagedList( ProjectId,1,9999999);
            if (!data.Data.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var dataList = new List<ImportWorkCell>();
     
            foreach (var item in data.Data)
            {
                dataList.Add(new ImportWorkCell
                {
                    No = item.id,
                    Cell= item.CellDesc,
                    NextCell= item.NextCellDesc
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<ImportWorkCell> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<ImportWorkCell>();
                    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("Export Inspection Standard Info failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult Items()
        {
            var data = _qmscellRepository.GetList(f => f.projectid == ProjectId && f.status == (int)RowState.Valid).ToList();
            var result = new List<ReponseKeyValueItem>();
            foreach(var d in data)
            {
                var cell = _qmscellCfg.Get(f => f.projectid == ProjectId && f.id == d.cell);
                var ncell=_qmscellCfg.Get(f => f.projectid == ProjectId && f.id == d.nextcell);

                var strItem = cell != null ? cell.cell:d.cell.ToString();
                var strItemNext = ncell != null ? ncell.cell : "";

                result.Add(new ReponseKeyValueItem
                {
                    Id = d.id,
                    Item = $"{strItem} -> {strItemNext}"
                });
            }

            return new ObjectResult(result);
        }
   
        [HttpPost]
        public IActionResult Add([FromBody]RequestQmsWorkCell request)
        {
            if (_qmscellRepository.IsExist(f=>f.projectid==ProjectId && f.cell==request.Cell && f.nextcell==request.NextCell))
                throw new BadRequestException(CommonEnum.RecordExits);
            _qmscellRepository.Insert(new Middlelayer.QmsRepository.Entities.siger_qms_cell
            {
                cell=request.Cell,
                nextcell=request.NextCell,
                projectid=ProjectId,
                status=(int)RowState.Valid
            });
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Modify([FromBody]RequestQmsWorkCell request)
        {
            var Obj = _qmscellRepository.Get(f => f.projectid == ProjectId && f.id == request.Id);
            if (Obj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            if (Obj.cell==request.Cell && Obj.nextcell==request.NextCell)
                return new ObjectResult(CommonEnum.Succefull);
            if (_qmscellRepository.IsExist(f => f.projectid == ProjectId && f.cell == request.Cell))
                throw new BadRequestException(CommonEnum.RecordExits);

            Obj.cell = request.Cell;
            Obj.nextcell = request.NextCell;
            _qmscellRepository.Update(Obj);

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

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