using System;
using System.IO;
using System.Linq;
using FMSAdmin.Data;
using FMSAdmin.Entities;
using FMSAdmin.Helpers;
using FMSAdmin.Models;
using FMSAdmin.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using OfficeOpenXml;

namespace FMSAdmin.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/[controller]")]
    public class SiteConfigController : Controller {
        private readonly ILogger<SiteConfigController> _logger;
        private readonly FMSContext _context;
        private readonly StorageHelper _storageHelper;

        public SiteConfigController(
            ILogger<SiteConfigController> logger,
            StorageHelper storageHelper,
            FMSContext context
        ) {
            _logger = logger;
            _storageHelper = storageHelper;
            _context = context;
        }

        /// <summary>
        /// 세팅 저장
        /// </summary>
        [HttpPost("[action]")]
        public IActionResult SaveModule(SiteConfig data) {
            var persist = _context.SiteConfig.Single();
            persist.UseWorkAutoOrder = data.UseWorkAutoOrder;
            //1실행계획 관리 숨김
            //web /facility/ExecutionSchedule
            //app /Facility/ExecutionSchedule
            _SetMenuVisible(SitemapType.본사, "/facility/ExecutionSchedule", !data.UseWorkAutoOrder);
            _SetMenuVisible(SitemapType.현장, "/facility/ExecutionSchedule", !data.UseWorkAutoOrder);
            _SetMenuVisible(SitemapType.모바일, "/Facility/ExecutionSchedule", !data.UseWorkAutoOrder);


            _SetMenuVisible(SitemapType.본사, "/facility/ExecutionScheduleCalendar", !data.UseWorkAutoOrder);
            _SetMenuVisible(SitemapType.현장, "/facility/ExecutionScheduleCalendar", !data.UseWorkAutoOrder);
            persist.UseWorkAutoResult = data.UseWorkAutoResult;
            //1작업대기 관리 숨김
            //web /facility/WorkExecution
            //app /Facility/WorkWait
            _SetMenuVisible(SitemapType.본사, "/facility/WorkExecution", !data.UseWorkAutoResult);
            _SetMenuVisible(SitemapType.현장, "/facility/WorkExecution", !data.UseWorkAutoResult);
            _SetMenuVisible(SitemapType.모바일, "/Facility/WorkWait", !data.UseWorkAutoResult);
            persist.UseMaterialBuyAutoApproval = data.UseMaterialBuyAutoApproval;
            //1구매 신청 승인 숨김
            //web /material/MaterialPurchaseRequestApproval
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/material/MaterialPurchaseRequestApproval", !data.UseMaterialBuyAutoApproval);
            _SetMenuVisible(SitemapType.현장, "/material/MaterialPurchaseRequestApproval", !data.UseMaterialBuyAutoApproval);
            persist.UseMaterialStoredAutoApproval = data.UseMaterialStoredAutoApproval;
            //1입고 정보 승인 숨김
            //web /material/MaterialStoredApproval
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/material/MaterialStoredApproval", !data.UseMaterialStoredAutoApproval);
            _SetMenuVisible(SitemapType.현장, "/material/MaterialStoredApproval", !data.UseMaterialStoredAutoApproval);
            persist.UseMaterialAdjustmentAutoApproval = data.UseMaterialAdjustmentAutoApproval;
            //1자재 정산 승인 숨김
            //web /material/MaterialReleaseApproval
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/material/MaterialReleaseApproval", !data.UseMaterialAdjustmentAutoApproval);
            _SetMenuVisible(SitemapType.현장, "/material/MaterialReleaseApproval", !data.UseMaterialAdjustmentAutoApproval);
            persist.UseMaterialMonlthlyStock = data.UseMaterialMonlthlyStock;
            //1월별 재고량 보임
            //web /material/MaterialMonthlyStock
            //app /Material/MaterialMonthlyStock
            _SetMenuVisible(SitemapType.본사, "/material/MaterialMonthlyStock", data.UseMaterialMonlthlyStock);
            _SetMenuVisible(SitemapType.현장, "/material/MaterialMonthlyStock", data.UseMaterialMonlthlyStock);
            _SetMenuVisible(SitemapType.모바일, "/material/MaterialMonthlyStock", data.UseMaterialMonlthlyStock);
            persist.UseMaterialType = data.UseMaterialType;
            //1자재구분코드관리 보임
            //web /material/MaterialCodeType
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/material/MaterialCodeType", data.UseMaterialType);
            _SetMenuVisible(SitemapType.현장, "/material/MaterialCodeType", data.UseMaterialType);
            persist.UseMaterialReasonableStockCount = data.UseMaterialReasonableStockCount;
            persist.UseMaterialShortStock = data.UseMaterialShortStock;
            //1과부족재고 보임
            //web /material/MaterialShortStock
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/material/MaterialShortStock", data.UseMaterialShortStock);
            _SetMenuVisible(SitemapType.현장, "/material/MaterialShortStock", data.UseMaterialShortStock);
            persist.UseEquipmentRent = data.UseEquipmentRent;
            //1공기구대여 보임
            //web /equipment/Rent
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/equipment/Rent", data.UseEquipmentRent);
            _SetMenuVisible(SitemapType.현장, "/equipment/Rent", data.UseEquipmentRent);
            persist.UseEquipmentCurrent = data.UseEquipmentCurrent;
            //1공기구사용현황 보임
            //web /equipment/StatusInfo
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/equipment/StatusInfo", data.UseEquipmentCurrent);
            _SetMenuVisible(SitemapType.현장, "/equipment/StatusInfo", data.UseEquipmentCurrent);
            persist.UsePartnerCode = data.UsePartnerCode;
            //0근무형태관리코드 숨김
            //web /contract/PartnerManagement
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/contract/ContractClass", data.UsePartnerCode);
            _SetMenuVisible(SitemapType.현장, "/contract/ContractClass", data.UsePartnerCode);
            persist.UseServicePartner = data.UseServicePartner;
            //0용역업체관리 숨김
            //web /contract/ServicePartner
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/contract/ServicePartner", data.UseServicePartner);
            _SetMenuVisible(SitemapType.현장, "/contract/ServicePartner", data.UseServicePartner);
            _context.SaveChanges();
            persist.UseMaterialPurchaseOrder = data.UseMaterialPurchaseOrder;
            //0자재발주등록 숨김
            //web /contract/MaterialPurchaseOrder
            //app 없음
            _SetMenuVisible(SitemapType.본사, "/material/MaterialPurchaseOrder", !data.UseMaterialPurchaseOrder);
            _SetMenuVisible(SitemapType.현장, "/material/MaterialPurchaseOrder", !data.UseMaterialPurchaseOrder);
            _context.SaveChanges();

            //작업진행 사용여부 - 0:작업진행/작업완료 숨김, 1:작업완료(신규) 숨김
            //web 작업진행:/facility/CurrentWork, 작업완료:/facility/WorkApproval:, 작업완료(신규):/facility/WorkComplete
            //app 작업진행:/Facility/WorkProcess, 작업완료:/Facility/WorkComplete, 작업완료(신규):/facility/WorkProcessAndComplete
            persist.UseWorkProcess = data.UseWorkProcess;
            _SetMenuVisible(SitemapType.본사, "/facility/CurrentWork", data.UseWorkProcess);
            _SetMenuVisible(SitemapType.현장, "/facility/CurrentWork", data.UseWorkProcess);
            _SetMenuVisible(SitemapType.모바일, "/Facility/WorkProcess", data.UseWorkProcess);
            _SetMenuVisible(SitemapType.본사, "/facility/WorkApproval", data.UseWorkProcess);
            _SetMenuVisible(SitemapType.현장, "/facility/WorkApproval", data.UseWorkProcess);
            _SetMenuVisible(SitemapType.모바일, "/Facility/WorkComplete", data.UseWorkProcess);
            _SetMenuVisible(SitemapType.본사, "/facility/WorkComplete", !data.UseWorkProcess);
            _SetMenuVisible(SitemapType.현장, "/facility/WorkComplete", !data.UseWorkProcess);
            _SetMenuVisible(SitemapType.모바일, "/Facility/WorkProcessAndComplete", !data.UseWorkProcess);
            _context.SaveChanges();

            return Ok(persist);
        }

        /// <summary>
        /// 이미지 저장
        /// </summary>
        [HttpPost("[action]")]
        public IActionResult SaveLogo(SiteConfig data) {
            if (!string.IsNullOrEmpty(data.WebLoginLogo)) {
                _storageHelper.Move(data.WebLoginLogo, "/static/login_logo.png");
            }
            if (!string.IsNullOrEmpty(data.WebLoginBackground)) {
                _storageHelper.Move(data.WebLoginBackground, "/static/login_bg.jpg");
            }
            if (!string.IsNullOrEmpty(data.WebLoginFMSLogo)) {
                _storageHelper.Move(data.WebLoginFMSLogo, "/static/login_fms_logo.png");
            }
            if (!string.IsNullOrEmpty(data.WebMainLogo)) {
                _storageHelper.Move(data.WebMainLogo, "/static/logo.png");
            }
            if (!string.IsNullOrEmpty(data.WebCopyrightLogo)) {
                _storageHelper.Move(data.WebCopyrightLogo, "/static/copyright.png");
            }
            if (!string.IsNullOrEmpty(data.AppLoginLogo)) {
                _storageHelper.Move(data.AppLoginLogo, "/static/app_login_logo.png");
            }
            if (!string.IsNullOrEmpty(data.AppMainLogo)) {
                _storageHelper.Move(data.AppMainLogo, "/static/app_logo.png");
            }

            return Ok(data);
        }

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet]
        public IActionResult Get() {
            var config = _context.SiteConfig.Single();
            return Ok(config);
        }

        /// <summary>
        /// 숨김처리
        /// </summary>
        private void _SetMenuVisible(SitemapType type, string path, bool visible) {
            var menu = (from x in _context.Sitemap
                        where x.Type == type && x.Path.ToLower() == path.ToLower()
                        select x).FirstOrDefault();

            if (menu != null) {
                _logger.LogInformation("menu.Name: " + menu.Name);
                _logger.LogInformation("menu.Path: " + menu.Path);
                _logger.LogInformation("menu.Hidden: " + !visible);
                menu.Hidden = !visible;
                _logger.LogInformation("menu.Hidden: " + menu.Hidden);
            }
        }
    }
}