using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore.Internal;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.FieldEnum;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.TlmRepository.Entities;
using Siger.Middlelayer.TlmRepository.Repositories.Interface;
using Siger.Middlelayer.TlmRepository.Request;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Utility.ImportEntities;
using System.Linq;
using Siger.Middlelayer.TlmRepository.Response;
using Siger.ApiCommon.Filters;
using NPOI.SS.Formula.Functions;

namespace Siger.ApiTLM.Controllers
{
    public class ToolConfigController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IProjectToollifeToolConfigRepository _toollifeToolConfigRepository;
        private readonly IToolLifeToolRepository _toolLifeToolRepository;

        public ToolConfigController(IUnitOfWork unitOfWork, IProjectToollifeToolConfigRepository toollifeToolConfigRepository
            , IToolLifeToolRepository toolLifeToolRepository)
        {
            _unitOfWork = unitOfWork;
            _toollifeToolConfigRepository = toollifeToolConfigRepository;
            _toolLifeToolRepository = toolLifeToolRepository;
        }
        /// <summary>
        /// 获取刀具设置
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesDefaultResponseType(typeof(ResponseGetToolConfig))]
        public IActionResult GetToolConfig([FromBody]RequestProjectToollifeToolConfig request)
        {
            request.ProjectId = ProjectId;
            var data = _toollifeToolConfigRepository.GetPagedList(request);
            return new PagedObjectResult(data.Data, data.Total, request.Page, request.PageSize);
        }
        /// <summary>
        /// 获取刀具设置
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesDefaultResponseType(typeof(ResponseGetToolConfig))]
        public IActionResult GetToolConfigForApp([FromBody]RequestProjectToollifeToolConfig request)
        {
            request.ProjectId = ProjectId;
            request.Page = 0;
            var data = _toollifeToolConfigRepository.GetPagedList(request).Data.FirstOrDefault();
            if (data == null)
            {
                return new ObjectResult(new ResponseGetToolConfig());
            }
            return new ObjectResult(data);
        }
        /// <summary>
        /// 设置刀具设置
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SetToolConfig([FromBody]RequestSetToollifeToolConfig request)
        {
            var uid = UserId;
            var pid = ProjectId;
            if (string.IsNullOrEmpty(request.ToolIds))
            {
                throw new BadRequestException(TlmEnum.ToolCodeNotFound);
            }
            var strToolIds = request.ToolIds.Split(',');
            if (!strToolIds.Any())
            {
                throw new BadRequestException(TlmEnum.ToolCodeNotFound);
            }
            var toolIds = new List<int>();
            strToolIds.ToList().ForEach(f => toolIds.Add(f.ToInt()));
            var queryList = _toollifeToolConfigRepository.GetList(f => f.Code == request.Code && f.Projectid == pid && f.Status != 0).ToList();
            queryList.ForEach(i => { i.Status = (int)RowState.Invalid; _toollifeToolConfigRepository.Update(i); });
            var handler = _toolLifeToolRepository.GetList(f => f.project_id == ProjectId && f.status != 0 && toolIds.Contains(f.id) && f.category == TlmSettingCategory.Handler).ToList();
            if (handler.Count > 1)
            {
                throw new BadRequestException(TlmEnum.HandleNoMore);
            }
            foreach (var item in toolIds)
            {
                var model = new ProjectToollifeToolConfigEntity
                {
                    Code = request.Code,
                    CreateTime = DateTime.Now,
                    Creator = UserId,
                    Editor = UserId,
                    Projectid = ProjectId,
                    ToolId = item
                };
                _toollifeToolConfigRepository.Insert(model);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 删除刀具设置
        /// </summary>
        /// <param name="code">刀具号</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DelToolConfig(string code)
        {
            var pid = ProjectId;
            var dataList = _toollifeToolConfigRepository.GetList(f => f.Code == code && f.Projectid == pid && f.Status != 0).ToList();
            if (!dataList.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            else
            {
                dataList.ForEach(i => { i.Status = (int)RowState.Invalid; _toollifeToolConfigRepository.Update(i); });
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.DeleteFaild);
        }
        /// <summary>
        /// 导出刀具设置
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ExportProjectToollifeToolConfig([FromQuery] RequestProjectToollifeToolConfig req)
        {
            req.ProjectId = ProjectId;
            req.Page = 0;
           
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var list = _toollifeToolConfigRepository.ExportToolConfigData(req);
            if (!list.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var temporaryFileName = $"ProjectToollifeToolConfig_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);
            var helper = new EpPlusExcelHelper<ProjectToollifeToolConfigReportEntity>();
            try
            {
                helper.GenerateExcel(list, fileName);
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("Export sparepart type failed, error: " + e.Message);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper.Dispose();
            }
        }
        /// <summary>
        /// 获取刀具相关信息
        /// </summary>
        /// <param name="type">1刀片2刀柄3附件4刀头</param>
        /// <param name="name"></param>
        /// <param name="number"></param>
        /// <param name="id"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetToolDataByType(TlmSettingCategory type, string name, string number, int id, int count)
        {
            var pid = ProjectId;
            var list = _toolLifeToolRepository.GetList(f => f.project_id == pid && f.status != 0 && f.category == type).OrderBy(o => o.id).ToList();
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(f => f.name.StartsWith(name)).ToList();
            }
            if (!string.IsNullOrEmpty(number))
            {
                list = list.Where(f => f.number.StartsWith(number)).ToList();
            }
            if (id != 0)
            {
                list = list.Where(f => f.id == id).ToList();
            }
            if (count != 0)
            {
                list = list.Take(count).ToList();
            }
            return new ObjectResult(list.Select(s => new { s.id, s.name, s.number }));
        }
    }

}