using System;
using System.Collections.Generic;
using System.Linq;

using FMSAdmin.Data;
using FMSAdmin.Helpers;
using FMSAdmin.Entities;
using Microsoft.Extensions.Logging;
using FMSAdmin.Models;

namespace FMSAdmin.Services {
    public class EquipmentHistoryService {
        private readonly ILogger<EquipmentHistoryService> _logger;
        private readonly FMSContext _context;

        public EquipmentHistoryService(
            ILogger<EquipmentHistoryService> logger,
            FMSContext context,
            StorageHelper storage) {
            _logger = logger;
            _context = context;
        }

        public void Create(FmsEquipmentHistory data) {

            using (var transaction = _context.Database.BeginTransaction()) {
                var persist = _context.FmsEquipmentHistory.OrderByDescending(x => x.EquipmentHistoryId)
                                .Where(x => x.EquipmentId == data.EquipmentId && x.SiteId == data.SiteId).FirstOrDefault();
                if (persist == null) {
                    throw new ServiceException("정보를 찾을 수 없습니다.");
                }
                data.TotalStockCount = persist.TotalStockCount + data.StoredCount;
                data.CurrentStockCount = persist.CurrentStockCount + data.StoredCount;
                data.ReturnCount = 0;
                data.AddDate = DateTime.Now;
                data.UpdateDate = DateTime.Now;
                data.IsReturnApproval = false;
                _context.FmsEquipmentHistory.Add(data);
                _context.SaveChanges();

                if (!_context.SiteConfig.Single().UseEquipmentRent) {
                    var rentInfo = new FmsEquipmentRentInfo {
                        SiteId = data.SiteId,
                        RegisterUserId = persist.FmsEquipment.RegisterUserId,
                        RentUserId = persist.FmsEquipment.RegisterUserId,
                        RentDate = DateTime.Now,
                        EquipmentStateTypeId = 2,
                        Comment = "입고",
                        Title = "입고",
                    };
                    var rentHistory = new FmsEquipmentHistory {
                        EquipmentId = data.EquipmentId,
                        SiteId = data.SiteId,
                        TotalStockCount = data.TotalStockCount,
                        CurrentStockCount = 0,
                        RentCount = data.StoredCount,
                        CurrentRentCount = data.StoredCount,
                        ReturnCount = 0,
                        LossCount = 0,
                        StoredCount = 0,
                        EquipmentStateTypeId = 2,
                        IsReturned = false,
                        AddDate = DateTime.Now,
                        UpdateDate = DateTime.Now,
                        IsReturnApproval = false
                    };
                    rentInfo.FmsEquipmentHistory.Add(rentHistory);
                    _context.FmsEquipmentRentInfo.Add(rentInfo);
                    _context.SaveChanges();
                }
                transaction.Commit();
            }
        }

        public void Edit(int id, int siteId, FmsEquipmentHistory data) {

        }

        public IQueryable<FmsEquipmentHistory> GetAll() {
            var query = from p in _context.FmsEquipmentHistory
                        select p;
            return query;
        }

        public FmsEquipmentHistory Get(int id, int siteId) {
            var data = _context.FmsEquipmentHistory.Single(x => x.EquipmentHistoryId == id && x.SiteId == siteId);
            return data;
        }

        public IQueryable<FmsEquipmentHistory> Gets(int id, int siteId) {
            var data = _context.FmsEquipmentHistory.Where(x => x.EquipmentHistoryId == id && x.SiteId == siteId);
            return data;
        }

        public void Delete(int id, int siteId) {
            using (var transaction = _context.Database.BeginTransaction()) {
                var data = _context.FmsEquipmentHistory.First(x => x.EquipmentHistoryId == id && x.SiteId == siteId);
                var rentInfo = _context.FmsEquipmentRentInfo.First(x => x.SiteId == siteId && x.EquipmentRentId == data.EquipmentRentId);
                if (data.EquipmentStateTypeId != 2) {
                    //이미 승인된경우 삭제 안됨
                    if (data.IsReturnApproval)
                        throw new ServiceException("이미 승인된 이력입니다.");
                    foreach (var history in rentInfo.FmsEquipmentHistory.Where(x => x.EquipmentId == data.EquipmentId && x.EquipmentHistoryId > data.EquipmentHistoryId)) {
                        history.TotalStockCount += data.LossCount.GetValueOrDefault();
                        history.CurrentStockCount -= data.ReturnCount.GetValueOrDefault();
                        history.CurrentRentCount += data.LossCount.GetValueOrDefault() + data.ReturnCount.GetValueOrDefault();
                    }

                    rentInfo.FmsEquipmentHistory.Where(x => x.EquipmentId == data.EquipmentId && x.EquipmentHistoryId != data.EquipmentHistoryId)
                                                .OrderByDescending(x => x.EquipmentHistoryId).FirstOrDefault().IsReturned = false;

                    rentInfo.ReturnFixDate = null;
                    rentInfo.FmsEquipmentHistory.Remove(data);
                    rentInfo.EquipmentStateTypeId = 2;

                    _context.FmsEquipmentRentInfo.Update(rentInfo);
                    _context.SaveChanges();

                } else {
                    _context.FmsEquipmentRentInfo.Remove(rentInfo);
                    _context.SaveChanges();
                }
                transaction.Commit();
            }
        }

        public IQueryable<FmsEquipmentHistory> GetHistory() {
            var query = _context.FmsEquipmentHistory;
            return query;
        }

        public void ReturnApproval(int siteId, int id, string userId) {
            var persist = _context.FmsEquipmentHistory.First(x => x.SiteId == siteId && x.EquipmentHistoryId == id);
            if (persist.IsReturnApproval) throw new ServiceException("이미 승인된 이력입니다.");
            persist.IsReturnApproval = true;
            persist.ReturnApprovalDate = DateTime.Now;
            persist.ReturnApprovalUserId = userId;

            _context.FmsEquipmentHistory.Update(persist);
            _context.SaveChanges();
        }

    }
}