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

namespace Siger.ApiACC.Controllers
{

    public class RoutingEventNoController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerRoutingEventNo _sigerRoutingEvenNo;
        private readonly ISigerDict _sigerDict;
        public RoutingEventNoController(IUnitOfWork unitOfWork,ISigerRoutingEventNo routingEvenNo, ISigerDict sigerDict)
        {
            _unitOfWork = unitOfWork;
            _sigerRoutingEvenNo = routingEvenNo;
            _sigerDict = sigerDict;
        }
        [HttpGet]
        public IActionResult Getlist(int eventNo, string descr,int page = 1, int pagesize = 10)
        {
            Expression<Func<SigerTrRoutingEventNo, bool>> Funcat = f => f.projectId == ProjectId && f.status == RowState.Valid.GetHashCode();
            Expression<Func<SigerTrRoutingEventNo, bool>> Funkey = f => true;
            Expression<Func<SigerTrRoutingEventNo, bool>> FuneventNo = f => true;
            if (eventNo!=0)
                FuneventNo = f => f.EventNo== eventNo;
            if (!string.IsNullOrEmpty(descr))
                Funkey = f => f.Descr.Contains(descr);
            var predicate = Funcat.And(Funkey).And(FuneventNo);
            var data = _sigerRoutingEvenNo.GetPagedList(page, pagesize, predicate);

            var response = new List<ResponseRoutingEnentNo>();
            foreach(var item in data.Data)
            {
                response.Add(new ResponseRoutingEnentNo
                {
                    id = item.id,
                    eventno = item.EventNo,
                    descr=item.Descr,
                });
            }

            return new PagedObjectResult(response, data.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult Add([FromBody]RequestRouringEventNo eventNo)
        {
            var model = _sigerRoutingEvenNo.Get(t => t.EventNo == eventNo.EventNo && t.projectId == ProjectId && t.status == (int)RowState.Valid);
            if (model != null)
            {
                throw new BadRequestException(RequestEnum.DataExist);
            }
            _sigerRoutingEvenNo.Insert(new SigerTrRoutingEventNo
            {
                projectId = ProjectId,
                EventNo = eventNo.EventNo,
                Descr = eventNo.Descr,
            });
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpPost]
        public IActionResult Modify([FromBody]RequestModifyRouringEventNo eventNo)
        {
            var NewObj = _sigerRoutingEvenNo.Get(eventNo.id);
            if (NewObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var model = _sigerRoutingEvenNo.Get(t => t.EventNo == eventNo.EventNo && t.projectId == ProjectId && t.status == (int)RowState.Valid && t.id!=eventNo.id);
            if (model != null)
            {
                throw new BadRequestException(RequestEnum.DataExist);
            }

            NewObj.Descr = eventNo.Descr;
            NewObj.EventNo = eventNo.EventNo;
            _sigerRoutingEvenNo.Update(NewObj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpGet]
        public IActionResult Delete(int id)
        {
            var NewObj = _sigerRoutingEvenNo.Get(id);
            if (NewObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            NewObj.status = (int)RowState.Invalid;
            _sigerRoutingEvenNo.Update(NewObj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult ExportAll(int eventNo, string descr)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            Expression<Func<SigerTrRoutingEventNo, bool>> Funcat = f => f.projectId == ProjectId && f.status == RowState.Valid.GetHashCode();
            Expression<Func<SigerTrRoutingEventNo, bool>> Funkey = f => true;
            Expression<Func<SigerTrRoutingEventNo, bool>> FuneventNo = f => true;
            if (eventNo != 0)
                FuneventNo = f => f.EventNo == eventNo;
            if (!string.IsNullOrEmpty(descr))
                Funkey = f => f.Descr.Contains(descr);
            var predicate = Funcat.And(Funkey).And(FuneventNo);
            var data = _sigerRoutingEvenNo.GetList(predicate).ToList();
            if (!data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var dataList = new List<RoutingEventNoTemplate>();
            foreach (var item in data)
            {
                dataList.Add(new RoutingEventNoTemplate
                {
                    eventno = _sigerDict.GetDictValue(ProjectId, AccDictCostNoProjectId.eventno, item.EventNo.ToStr()),
                    descr = item.Descr
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<RoutingEventNoTemplate> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<RoutingEventNoTemplate>();
                    var temporaryFileName = $"结果维护模板_RoutingEventNo_{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("ExportRoutingEventNo failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}