using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

using FMSAdmin.Data;
using FMSAdmin.Helpers;
using FMSAdmin.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using FMSAdmin.Models;

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

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

        public IQueryable<FmsMaterial> GetAll() {
            var query = _context.FmsMaterial;
            return query;
        }

        public void ImportExcel(IList<MaterialBaseStock> list, string userId) {
            using (var transaction = _context.Database.BeginTransaction()) {
                var groupList = list.GroupBy(x => new { x.SiteId, x.BusinessFieldId, x.Warehouse.WarehouseId }).Select(x => new { x.Key.SiteId, x.Key.BusinessFieldId, x.Key.WarehouseId }).ToList();
                foreach (var item in groupList) {
                    var listItem = list.Where(x => x.SiteId == item.SiteId && x.BusinessFieldId == item.BusinessFieldId && x.Warehouse.WarehouseId == item.WarehouseId).ToList();

                    //구매신청
                    var requestItem = new FmsMaterialPurchaseRequest {
                        SiteId = item.SiteId,
                        BusinessFieldId = item.BusinessFieldId,
                        PurchaseTypeId = 4,     //기타
                        RequestDate = DateTime.Now,
                        RequestUserId = userId,
                        PurchaseHopeDate = DateTime.Now,
                        Title = "기초재고등록",
                        Reason = "기초재고등록",
                        ProgressId = 5,
                        ApprovalDate = DateTime.Now,
                        ApprovalUserId = userId,
                        BSameOrder = true
                    };
                    foreach (var req in listItem) {
                        requestItem.FmsMaterialPurchaseRequestMaterial.Add(new FmsMaterialPurchaseRequestMaterial() {
                            SiteId = req.SiteId,
                            BusinessFieldId = req.BusinessFieldId,
                            MaterialId = req.Material.MaterialId,
                            MaterialCount = req.StockCount
                        });
                    }
                    _context.FmsMaterialPurchaseRequest.Add(requestItem);
                    _context.SaveChanges();

                    //발주
                    var orderItem = new FmsMaterialPurchaseOrder {
                        SiteId = item.SiteId,
                        BusinessFieldId = item.BusinessFieldId,
                        PurchaseRequestId = requestItem.PurchaseRequestId,
                        OrderDate = DateTime.Now,
                        OrderUserId = userId,
                        Title = "기초재고등록",
                        StoredDueDate = DateTime.Now
                    };
                    foreach (var req in listItem) {
                        orderItem.FmsMaterialPurchaseOrderMaterial.Add(new FmsMaterialPurchaseOrderMaterial() {
                            SiteId = req.SiteId,
                            BusinessFieldId = req.BusinessFieldId,
                            MaterialId = req.Material.MaterialId,
                            MaterialCount = req.StockCount,
                            UnitCost = Util.ToInt(req.Material.FinalPrice)
                        });
                    }
                    _context.FmsMaterialPurchaseOrder.Add(orderItem);
                    _context.SaveChanges();

                    foreach (var req in listItem) {
                        //입고
                        var storedItem = new FmsMaterialStored {
                            SiteId = item.SiteId,
                            BusinessFieldId = item.BusinessFieldId,
                            StoredDate = DateTime.Now,
                            PurchaseOrderId = orderItem.PurchaseOrderId,
                            WarehouseId = req.Warehouse.WarehouseId,
                            MaterialId = req.Material.MaterialId,
                            StoredCount = req.StockCount,
                            RemainStoredCount = req.StockCount,
                            UnitCost = Util.ToInt(req.Material.FinalPrice),
                            StoredUserId = userId,
                            ApprovalDate = DateTime.Now,
                            ApprovalUserId = userId,
                            IsApproval = true,
                        };

                        //해당 material 의 최신 입고 정보
                        var lastStoredItem = _context.FmsMaterialStored.Where(x => x.SiteId == storedItem.SiteId && x.MaterialId == storedItem.MaterialId).OrderByDescending(x => x.MaterialStoredId).FirstOrDefault();
                        //재고정보 업데이트
                        if (lastStoredItem != null) {
                            storedItem.StockCount += (lastStoredItem.StockCount + req.StockCount);
                        } else {
                            storedItem.StockCount = req.StockCount;
                        }

                        _context.FmsMaterialStored.Add(storedItem);
                        _context.SaveChanges();
                    }
                }

                transaction.Commit();
            }
        }
    }
}