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.ApiCommon.Result;
using System.Collections.Generic;
using Siger.Middlelayer.QmsRepository.Response;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common.AppSettings;
using System;
using System.IO;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.QmsRepository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;

namespace Siger.ApiQMS.Controllers
{
    public class StandardPartsController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IStandardPartsRepository _standardPartsRepository;
        private readonly ISigerProjectMachineAttributionRepository _machineAttributionRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        public StandardPartsController(IUnitOfWork unitOfWork, IStandardPartsRepository standardPartsRepository,
            ISigerProjectMachineAttributionRepository machineAttributionRepository, ISigerProjectMachineRepository machineRepository)
        {
            _unitOfWork = unitOfWork;
            _standardPartsRepository = standardPartsRepository;
            _machineAttributionRepository = machineAttributionRepository;
            _machineRepository = machineRepository;
        }
        [HttpGet]
        public IActionResult GetPageList(int machineid, int page, int pagesize, int toexcel)
        {
            var datas = _standardPartsRepository.GetPagedList(machineid, page, pagesize, ProjectId, toexcel);
            if(toexcel == 1)
            {
                return ExportExcel(datas.Data);
            }
            return new PagedObjectResult(datas.Data, datas.Total, page, pagesize);
        }

        private IActionResult ExportExcel(IEnumerable<ResponseStandardParts> data)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            if (!data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var dataList = new List<StandardParts>();
            int index = 1;
            foreach(var item in data)
            {
                dataList.Add(new StandardParts
                {
                    No = index,
                    MachineName = item.machinename,
                    Frequency = item.frequency,
                    UpdateUser = item.updator,
                    UpdateTime = item.updatetime,
                    Enable = item.status == (int)RowState.Valid ? 1 : 0
                });
                index++;
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<StandardParts> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<StandardParts>();
                    var temporaryFileName = $"标准件设置_StandardPartsSetting_{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 Standard Parts Setting failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 禁用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Delete([FromBody]RequestParameterStandardParts req)
        {
            if(req.machineIds == null || !req.machineIds.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var entities = _standardPartsRepository.GetList(t => req.machineIds.Contains(t.machineid) && t.projectid == ProjectId).ToList();
            foreach(var machineid in req.machineIds)
            {
                var entity = entities.FirstOrDefault(t => t.machineid == machineid);
                if (entity == null)
                {
                    var model = new siger_qms_standard_parts
                    {
                        machineid = machineid,
                        calibration_frequency = 0,
                        update_mid = UserId,
                        update_time = DateTime.Now,
                        projectid = ProjectId,
                        status = (int)RowState.Invalid
                    };
                    _standardPartsRepository.Insert(model);
                }
                else
                {
                    if (entity.status != (int)RowState.Valid)
                    {
                        return new ObjectResult(CommonEnum.Succefull);
                    }

                    entity.status = (int)RowState.Invalid;
                    entity.update_mid = UserId;
                    entity.update_time = DateTime.Now;
                    _standardPartsRepository.Update(entity);
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 启用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Enable([FromBody]RequestParameterStandardParts req)
        {
            if (req.machineIds == null || !req.machineIds.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var entities = _standardPartsRepository.GetList(t => req.machineIds.Contains(t.machineid) && t.projectid == ProjectId).ToList();
            foreach (var machineid in req.machineIds)
            {
                var entity = entities.FirstOrDefault(t => t.machineid == machineid);
                if (entity == null)
                {
                    var model = new siger_qms_standard_parts
                    {
                        machineid = machineid,
                        calibration_frequency = 0,
                        update_mid = UserId,
                        update_time = DateTime.Now,
                        projectid = ProjectId,
                        status = (int)RowState.Valid
                    };
                    _standardPartsRepository.Insert(model);
                }
                else
                {
                    if (entity.status == (int)RowState.Valid)
                    {
                        return new ObjectResult(CommonEnum.Succefull);
                    }

                    entity.status = (int)RowState.Valid;
                    entity.update_mid = UserId;
                    entity.update_time = DateTime.Now;
                    _standardPartsRepository.Update(entity);
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Update([FromBody]RequestStandardParts req)
        {
            if(!double.TryParse(req.frequency, out double frequency))
            {
                throw new BadRequestException(RequestEnum.InputValueError);
            }

            var entity = _standardPartsRepository.Get(t => t.machineid == req.machineid && t.projectid == ProjectId);
            if (entity == null)
            {
                var model = new siger_qms_standard_parts
                {
                    machineid = req.machineid,
                    calibration_frequency = frequency,
                    update_mid = UserId,
                    update_time = DateTime.Now,
                    projectid = ProjectId
                };
                _standardPartsRepository.Insert(model);
            }
            else
            {
                entity.calibration_frequency = frequency;
                entity.update_mid = UserId;
                entity.update_time = DateTime.Now;
                _standardPartsRepository.Update(entity);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetAllMachines(string sectionid)
        {
            var machineIds = new List<int>();
            if(sectionid.ToInt() > 0)
            {
                machineIds = _machineAttributionRepository.GetList(t => t.station == sectionid.ToInt() &&
                    t.projectid == ProjectId && t.status == (int)RowState.Valid && t.attribution == (int)MachineAttributionEnum.equipment)
                    .Select(t => t.machine).ToList();
            }
            var machines = _machineRepository.GetList(t => t.attribution == (int)MachineAttributionEnum.equipment &&
                t.projectid == ProjectId && t.status == (int)RowState.Valid)
                .Select(m => new
                {
                    m.id,
                    m.typeid,
                    m.title
                });
            if (sectionid.ToInt() > 0)
            {
                machines = machines.Where(t => machineIds.Contains(t.id));
            }
            return new ObjectResult(machines.ToList());
        }
    }
}