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;
using System.Collections;
using System.Transactions;
using LinqKit;

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

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


        public int checkName(FmsMaterial data, bool isExcel = false) {
            var check = _context.FmsMaterial.Where(x => x.SiteId == data.SiteId && x.BusinessFieldId == data.BusinessFieldId && x.Name == data.Name && x.Standard == data.Standard).Count();
            if (!isExcel && check > 0) {
                throw new ServiceException("동일 정보가 존재합니다. [업무분야-자재명-규격]");
            }
            return check;
        }

        public int checkRfid(FmsMaterial data, bool isExcel = false) {
            var check = _context.FmsMaterial.Where(x => x.Rfid == data.Rfid && x.SiteId == data.SiteId).Count();
            if (!isExcel && check > 0) {
                throw new ServiceException("QR코드값이 중복되었습니다.");
            }
            return check;
        }

        public void Create(FmsMaterial data) {
            using (var trans = new TransactionScope()) {
                checkName(data);
                //현대해상 자재qr코드 숨김처리 
                //if (!Util.IsNullOrEmpty(data.Rfid)) checkRfid(data);

                if (data.CmFile != null && data.CmFile.IsUpload) {
                    data.CmFile.SiteId = data.SiteId;
                    var category = _context.CmFileCategory.First(x => x.Name == "material");
                    data.CmFile.FileCategory = category;
                    data.CmFile.CreatedDate = DateTime.Now;
                } else {
                    data.CmFile = null;
                }
                // if (!_context.SiteConfig.Single().UseMaterialType) {
                //     var materialTypeId = _context.FmsMaterialCodeType/*.Where(x => x.SiteId == data.SiteId)*/.Select(x => x.MaterialTypeId).FirstOrDefault();
                //     data.MaterialTypeId = materialTypeId;
                // }
                _context.FmsMaterial.Add(data);
                _context.SaveChanges();

                if (data.CmFile != null && data.CmFile.IsUpload) {
                    // 카피
                    _storage.CopyEntity(data.CmFile.Path, data.CmFile);
                }

                trans.Complete();
            }
        }

        public void Edit(int id, int siteId, FmsMaterial data) {
            using (var trans = new TransactionScope()) {
                if (data.CmFile != null && data.CmFile.IsUpload) {
                    data.CmFile.SiteId = data.SiteId;
                    var category = _context.CmFileCategory.First(x => x.Name == "material");
                    data.CmFile.FileCategory = category;
                    data.CmFile.CreatedDate = DateTime.Now;
                }

                var persist = _context.FmsMaterial
                                .Where(x => x.MaterialId == id && x.SiteId == siteId).FirstOrDefault();
                if (persist == null) {
                    throw new ServiceException("정보를 찾을 수 없습니다.");
                }
                if (!persist.BusinessFieldId.Equals(data.BusinessFieldId)) {
                    checkName(data);
                }
                if (!persist.Name.Equals(data.Name)) {
                    checkName(data);
                }
                if (!Util.IsNullOrEmpty(data.Standard)) {
                    if (!persist.Standard.Equals(data.Standard))
                        checkName(data);
                }
                //현대해상 자재qr코드 숨김처리 
                // if (!Util.IsNullOrEmpty(data.Rfid)) {
                //     if (!persist.Rfid.Equals(data.Rfid)) checkRfid(data);
                // }

                persist.SiteId = data.SiteId;
                persist.BusinessFieldId = data.BusinessFieldId;
                persist.Name = data.Name;
                if (_context.SiteConfig.Single().UseMaterialType) {
                    persist.MaterialTypeId = data.MaterialTypeId;
                }
                persist.Standard = data.Standard;
                persist.FirstClassId = data.FirstClassId;
                persist.SecondClassId = data.SecondClassId;
                persist.ThirdClassId = data.ThirdClassId;
                persist.MaterialCode = data.MaterialCode;
                persist.Unit = data.Unit;
                persist.DurableYears = data.DurableYears;
                //현대해상 자재qr코드 숨김처리 
                //persist.Rfid = data.Rfid;
                persist.Manufacturer = data.Manufacturer;
                persist.FinalPrice = data.FinalPrice;
                persist.ReasonableStockCount = data.ReasonableStockCount;
                persist.IsDiscontinued = data.IsDiscontinued;
                persist.IsUse = data.IsUse;
                persist.Note = data.Note;

                if (data.CmFile != null && data.CmFile.IsUpload) {
                    persist.CmFile = data.CmFile;
                }
                _context.FmsMaterial.Update(persist);
                _context.SaveChanges();

                if (data.CmFile != null && data.CmFile.IsUpload) {
                    // 카피
                    _storage.CopyEntity(data.CmFile.Path, persist.CmFile);
                    if (persist.CmFile != null) {
                        // 파일 삭제시 진짜 DB삭제?
                    }
                }

                trans.Complete();
            }
        }

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

        public IQueryable<MaterialStock> Stock() {
            var query = from x in _context.FmsMaterial.AsExpandable()
                        select new MaterialStock {
                            Material = x,
                            StockCount = FmsMaterial.GetStockCount.Invoke(x),
                            StockAmount = FmsMaterial.GetStockAmount.Invoke(x),
                        };
            return query;
        }


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

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

        public void Delete(int id, int siteId) {
            var data = _context.FmsMaterial.First(x => x.MaterialId == id && x.SiteId == siteId);
            _context.FmsMaterial.Remove(data);
            _context.SaveChanges();
        }

        public void ImportExcel(IList<FmsMaterial> list) {
            using (var transaction = _context.Database.BeginTransaction()) {
                // foreach (var data in list) {
                //     // 데이터 가공
                //     if (!_context.SiteConfig.Single().UseMaterialType) {
                //         var materialTypeId = _context.FmsMaterialCodeType/*.Where(x => x.SiteId == data.SiteId)*/.Select(x => x.MaterialTypeId).FirstOrDefault();
                //         data.MaterialTypeId = materialTypeId;
                //     }
                // }
                _context.FmsMaterial.AddRange(list);
                _context.SaveChanges();

                transaction.Commit();
            }
        }
    }
}