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 System.Transactions;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using FMSAdmin.Models;

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

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

        public void Save(FmsFacilityCodeClass data) {
            using (var trans = new TransactionScope()) {
                var persist = _context.FmsFacilityCodeClass
                                .Where(x => x.FacilityClassId == data.FacilityClassId).FirstOrDefault();


                if (persist == null) {
                    //var check = _context.FmsFacilityCodeClass.Where(x => (x.Name == data.Name || x.Abbreviation == data.Abbreviation) && x.Depth == data.Depth && x.SiteId == data.SiteId).Count();
                    var check = _context.FmsFacilityCodeClass.Where(x => x.Name == data.Name && x.ParentFacilityClassId == data.ParentFacilityClassId && x.Depth == data.Depth).Count();
                    if (check > 0) {
                        throw new ServiceException("이미 동일한 정보가 정보가 존재합니다..");
                    }

                    _context.FmsFacilityCodeClass.Add(data);
                    _context.SaveChanges();
                } else {
                    if (!persist.Name.Equals(data.Name)) {
                        var check = _context.FmsFacilityCodeClass.Where(x => x.Name == data.Name && x.ParentFacilityClassId == data.ParentFacilityClassId && x.Depth == data.Depth).Count();
                        if (check > 0) {
                            throw new ServiceException("이미 동일한 정보가 정보가 존재합니다..");
                        }
                    }
                    persist.ParentFacilityClassId = data.ParentFacilityClassId;
                    persist.Name = data.Name;
                    //persist.Abbreviation = data.Abbreviation;
                    persist.IsUse = data.IsUse;
                    //
                    _context.SaveChanges();
                }
                trans.Complete();
            }
        }

        public int checkName(int siteId, int? parentFacilityClassId, string name, bool isExcel = false) {
            var check = _context.FmsFacilityCodeClass.Where(x => x.Name == name && x.ParentFacilityClassId == parentFacilityClassId).Count();
            if (!isExcel && check > 0) {
                throw new ServiceException("동일 정보가 존재합니다.");
            }
            return check;
        }


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

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

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

                transaction.Commit();
            }
        }

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

        public IQueryable<FmsFacilityCodeClass> Get(int id) {
            var data = _context.FmsFacilityCodeClass.Where(x => x.FacilityClassId == id);
            return data;
        }

        public void Delete(int id) {
            var childCnt = _context.FmsFacilityCodeClass.Where(x => x.ParentFacilityClassId == id).Count();

            var firstCnt = _context.CmFacility.Where(x => x.FirstClassId == id).Count();
            var secondCnt = _context.CmFacility.Where(x => x.SecondClassId == id).Count();
            var thirdCnt = _context.CmFacility.Where(x => x.ThirdClassId == id).Count();

            if (firstCnt + secondCnt + thirdCnt > 0) throw new ServiceException("이미 다른 화면에서 사용중이므로 삭제할 수 없습니다.");

            if (childCnt > 0) throw new ServiceException("하위 분류코드를 삭제해주세요.");

            using (var trans = new TransactionScope()) {
                var data = _context.FmsFacilityCodeClass.First(x => x.FacilityClassId == id);

                //data.IsUse = false;
                _context.FmsFacilityCodeClass.Remove(data);
                _context.SaveChanges();
                trans.Complete();
            }
        }
    }
}