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 MaterialCodeClassService {
        private readonly ILogger<MaterialCodeClassService> _logger;
        private readonly FMSContext _context;

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

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

        public IQueryable<FmsMaterialCodeClass> Gets(int id, int depth) {
            var data = _context.FmsMaterialCodeClass.Where(x => x.MaterialClassId == id/* && x.SiteId == siteId*/ && x.Depth == depth);
            return data;
        }

        public void Create(FmsMaterialCodeClass data) {
            var persist2 = _context.FmsMaterialCodeClass
            .Where(x => /*x.SiteId == data.SiteId && */x.Name == data.Name && x.Depth == data.Depth && x.ParentMaterialClassId == (data.Depth == 0 ? x.ParentMaterialClassId : data.ParentMaterialClassId)).FirstOrDefault();
            if (persist2 != null) {
                throw new ServiceException("이미 동일한 정보가 존재합니다.");
            }

            using (var transaction = _context.Database.BeginTransaction()) {
                if (data.Depth == 0) {
                    data.ParentMaterialClassId = null;
                }
                _context.FmsMaterialCodeClass.Add(data);
                _context.SaveChanges();

                transaction.Commit();
            }
        }

        public void Edit(int id, FmsMaterialCodeClass data) {
            var persist = _context.FmsMaterialCodeClass
                            .Where(x => x.MaterialClassId == id/* && x.SiteId == siteId*/).FirstOrDefault();
            if (persist == null) {
                throw new ServiceException("정보를 찾을 수 없습니다.");
            }

            var persist2 = _context.FmsMaterialCodeClass
            .Where(x => x.MaterialClassId != data.MaterialClassId/* && x.SiteId == data.SiteId*/ && x.Name == data.Name && x.Depth == data.Depth && x.ParentMaterialClassId == data.ParentMaterialClassId).FirstOrDefault();
            if (persist2 != null) {
                throw new ServiceException("이미 동일한 정보가 존재합니다.");
            }

            using (var transaction = _context.Database.BeginTransaction()) {
                //persist.SiteId = data.SiteId;
                persist.MaterialClassId = data.MaterialClassId;
                persist.ParentMaterialClassId = data.ParentMaterialClassId;
                persist.Depth = data.Depth;
                persist.Name = data.Name;
                //persist.Abbreviation = data.Abbreviation;
                persist.IsUse = data.IsUse;
                _context.FmsMaterialCodeClass.Update(persist);
                _context.SaveChanges();

                transaction.Commit();
            }
        }

        public void Delete(int id, int depth) {
            var materialCnt = 0;
            if (depth == 0) {
                materialCnt = _context.FmsMaterial.Where(x => x.FirstClassId == id).Count();
            } else if (depth == 1) {
                materialCnt = _context.FmsMaterial.Where(x => x.SecondClassId == id).Count();
            } else {
                materialCnt = _context.FmsMaterial.Where(x => x.ThirdClassId == id).Count();
            }
            if (materialCnt > 0) throw new ServiceException("이미 다른 화면에서 사용중이므로 삭제할 수 없습니다.");

            var childCnt = _context.FmsMaterialCodeClass.Where(x => x.ParentMaterialClassId == id).Count();
            if (childCnt > 0) throw new ServiceException("하위 분류코드를 삭제해주세요.");

            using (var transaction = _context.Database.BeginTransaction()) {
                var data = _context.FmsMaterialCodeClass.First(x => x.MaterialClassId == id/* && x.SiteId == siteId*/);
                // //하위 분류 삭제
                // if (depth == 0) {
                //     var data2 = _context.FmsMaterialCodeClass
                //         .Where(x => x.SiteId == siteId && x.ParentMaterialClassId == id && x.Depth == 1).ToList();
                //     foreach (var item in data2) {
                //         var data3 = _context.FmsMaterialCodeClass
                //             .Where(x => x.SiteId == siteId && x.ParentMaterialClassId == item.MaterialClassId && x.Depth == 2).ToList();
                //         _context.FmsMaterialCodeClass.RemoveRange(data3);
                //     }
                //     _context.FmsMaterialCodeClass.RemoveRange(data2);
                // } else if (depth == 1) {
                //     var data3 = _context.FmsMaterialCodeClass
                //         .Where(x => x.SiteId == siteId && x.ParentMaterialClassId == id && x.Depth == 2).ToList();
                //     _context.FmsMaterialCodeClass.RemoveRange(data3);
                // }
                _context.FmsMaterialCodeClass.Remove(data);
                _context.SaveChanges();

                transaction.Commit();
            }
        }

        public void ImportExcel(IList<FmsMaterialCodeClass> list) {
            using (var transaction = _context.Database.BeginTransaction()) {
                //대분류 등록
                var query = list.Where(x => x.Depth == 0).ToList();
                if (query.Count > 0) {
                    _context.FmsMaterialCodeClass.AddRange(query);
                    _context.SaveChanges();
                }

                //중분류 등록
                var query2 = list.Where(x => x.Depth == 1).ToList();
                foreach (var item in query2) {
                    if (item.ParentMaterialClassId == null || item.ParentMaterialClassId == 0) {
                        item.ParentMaterialClassId = list.Where(x => x.Depth == 0 /*&& x.SiteId == item.SiteId */&& x.Name == item.FmsMaterialCodeClass2.Name).Select(x => x.MaterialClassId).FirstOrDefault();
                    }
                    if (item.ParentMaterialClassId == null || item.ParentMaterialClassId == 0) {
                        throw new ServiceException("해당 분류명칭에 상위분류가 없습니다." + item.FmsMaterialCodeClass2.Abbreviation);
                    }
                    item.FmsMaterialCodeClass2 = null;
                    _context.FmsMaterialCodeClass.Add(item);
                    _context.SaveChanges();
                }

                //소분류 등록
                var query3 = list.Where(x => x.Depth == 2).ToList();
                foreach (var item in query3) {
                    if (item.ParentMaterialClassId == null || item.ParentMaterialClassId == 0) {
                        item.ParentMaterialClassId = list.Where(x => x.Depth == 1 /*&& x.SiteId == item.SiteId */&& x.Name == item.FmsMaterialCodeClass2.Name).Select(x => x.MaterialClassId).FirstOrDefault();
                    }
                    if (item.ParentMaterialClassId == null || item.ParentMaterialClassId == 0) {
                        throw new ServiceException("해당 분류명칭에 상위분류가 없습니다." + item.FmsMaterialCodeClass2.Abbreviation);
                    }
                    item.FmsMaterialCodeClass2 = null;
                    _context.FmsMaterialCodeClass.Add(item);
                    _context.SaveChanges();
                }

                transaction.Commit();
            }
        }
    }
}