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.Transactions;

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

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

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

        public IQueryable<FmsContract> Get(int siteId, int contractId) {
            var data = _context.FmsContract.Where(x => x.ContractId == contractId && x.SiteId == siteId);
            return data;
        }

        public void Create(FmsContract data) {
            //data.IsUse = true;
            using (var trans = new TransactionScope()) {
                if (data.CmFile != null && data.CmFile.IsUpload) {
                    var category = _context.CmFileCategory.First(x => x.Name == "contract");

                    data.CmFile.SiteId = data.SiteId;
                    data.CmFile.FileCategory = category;
                    data.CmFile.CreatedDate = DateTime.Now;
                } else {
                    data.CmFile = null;
                }

                _context.FmsContract.Add(data);
                _context.SaveChanges();

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

        public void Edit(int siteId, int contractId, FmsContract data) {

            using (var trans = new TransactionScope()) {

                if (data.CmFile != null && data.CmFile.IsUpload) {
                    var category = _context.CmFileCategory.First(x => x.Name == "contract");

                    data.CmFile.SiteId = data.SiteId;
                    data.CmFile.FileCategory = category;
                    data.CmFile.CreatedDate = DateTime.Now;
                    data.CmFile.Name = data.CmFile.Name;
                }

                var persist = _context.FmsContract
                                .Where(x => x.ContractId == contractId && x.SiteId == siteId).FirstOrDefault();
                if (persist == null) {
                    throw new ServiceException("정보를 찾을 수 없습니다.");
                }



                persist.SiteId = data.SiteId;
                persist.ContractId = data.ContractId;
                persist.Name = data.Name;
                persist.PartnerTypeId = data.PartnerTypeId;
                persist.PartnerId = data.PartnerId;
                persist.ContractDate = data.ContractDate;
                persist.StartDate = data.StartDate;
                persist.EndDate = data.EndDate;
                persist.OwnerShipName = data.OwnerShipName;
                persist.OwnerShipPhoneNo = data.OwnerShipPhoneNo;
                persist.CommitmentMan = data.CommitmentMan;
                persist.Comment = data.Comment;
                persist.ContractClassId = data.ContractClassId;
                persist.ContractTypeId = data.ContractTypeId;
                persist.ContractMethodId = data.ContractMethodId;
                persist.PaymentTypeId = data.PaymentTypeId;

                persist.ContractAmountText = data.ContractAmountText;
                persist.ContractExeGuaranteeRate = data.ContractExeGuaranteeRate;
                persist.DefectGuaranteeRate = data.DefectGuaranteeRate;
                persist.DefectGuaranteePeriodText = data.DefectGuaranteePeriodText;

                //persist.FileId = data.FileId;
                if (data.CmFile != null && data.CmFile.IsUpload) {
                    persist.CmFile = data.CmFile;
                }
                if (data.CmFile != null && data.CmFile.IsDelete) {
                    persist.CmFile = null;
                    persist.FileId = null;
                }
                _context.FmsContract.Update(persist);
                _context.SaveChanges();

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

                trans.Complete();
            }
        }

        public void Delete(int siteId, int contractId) {
            var data = _context.FmsContract.First(x => x.ContractId == contractId && x.SiteId == siteId);
            //data.IsUse = false;

            using (var trans = new TransactionScope()) {

                _context.FmsContract.Remove(data);
                _context.SaveChanges();

                trans.Complete();
            }
        }
        // public void AddCount(int siteId, int contractId) {
        //     var persist = _context.FmsContract
        //                     .Where(x => x.contractId == contractId && x.SiteId == siteId).FirstOrDefault();
        //     if (persist == null) {
        //         throw new ServiceException("정보를 찾을 수 없습니다.");
        //     }

        //     persist.ReadCount += 1;
        //
        //     _context.FmsContract.Update(persist);
        //     _context.SaveChanges();
        // }
    }
}