
using FMSAdmin.Data;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using FMSAdmin.Entities;
using System;
using FMSAdmin.Helpers;

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

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

        /// <summary>
        /// 셀렉트
        /// </summary>
        [HttpGet]
        [Route("[action]")]
        public IActionResult Select(string siteId, string entity, string id, string name, string fields, string sort = "name", string where = null, bool useCheck = false, bool businessAuth = false) {
            if (string.IsNullOrEmpty(entity)) {
                return BadRequest("누락된 정보가 있습니다.");
            }
            if (string.IsNullOrEmpty(id)) {
                if (entity.StartsWith("Cm")) {
                    id = entity.Substring(2) + "Id";
                } else if (entity.StartsWith("Bems")) {
                    id = entity.Substring(4) + "Id";
                } else if (entity.StartsWith("Fms")) {
                    id = entity.Substring(3) + "Id";
                }
            }
            if (string.IsNullOrEmpty(name)) {
                name = "Name";
            }

            CmUser user = null;
            if (entity == "CmBusinessField" && businessAuth) {
                user = _context.CmUser.FirstOrDefault(x => x.UserId == User.Identity.Name);
            }

            // fields 로 넘어온 추가 필드 처리
            var additionalFields = (fields ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries);
            var additionalFieldsSelect = "";
            if (!string.IsNullOrEmpty(fields)) {
                additionalFieldsSelect = "," + fields;
            }

            // Entity 검증 일단 SKIP

            IList<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            using (var command = _context.Database.GetDbConnection().CreateCommand()) {
                string wheresql = "";
                IList<string> conds = new List<string>();
                if (!string.IsNullOrEmpty(siteId)) {
                    conds.Add($"SiteId = {siteId}");
                }
                if (useCheck) {
                    conds.Add("IsUse = 1");
                }
                if (entity == "CmBusinessField" && businessAuth && user != null && user.BusinessFieldId != null) {
                    // User 의 BusinessFieldId 와 공통 만 조회되도록 변경
                    var commonBusinessField = _context.CmBusinessField.FirstOrDefault(
                        x => x.Name == "공통"
                    );
                    if (commonBusinessField != null) {
                        conds.Add($"BusinessFieldId IN ({commonBusinessField.BusinessFieldId},{user.BusinessFieldId})");
                    } else {
                        conds.Add($"BusinessFieldId IN ({user.BusinessFieldId})");
                    }
                }
                if (!string.IsNullOrEmpty(where)) {
                    conds.Add(where);
                }
                if (conds.Count > 0) {
                    wheresql = $"WHERE {string.Join(" AND ", conds)}";
                }
                string ordersql = "";
                if (entity == "CmSite") {
                    ordersql = $"ORDER BY SortOrderNo";

                } else {
                    if (sort == "name") {
                        ordersql = $"ORDER BY {name}";
                    } else if (sort == "id") {
                        ordersql = $"ORDER BY {id}";
                    }
                }
                string sql = $"SELECT {id},{name}{additionalFieldsSelect} FROM {entity} {wheresql} {ordersql}";
                //_logger.LogInformation(sql);
                command.CommandText = sql;
                _context.Database.OpenConnection();
                using (var reader = command.ExecuteReader()) {
                    if (reader.HasRows) {
                        while (reader.Read()) {
                            var row = new Dictionary<string, object>();
                            row["Id"] = reader.GetValue(id);
                            row["Name"] = reader.GetValue(name);
                            // fields 로 넘어온 추가 필드의 값을 전달
                            if (additionalFields != null && additionalFields.Length > 0) {
                                foreach (var field in additionalFields) {
                                    row[field] = reader.GetValue(field);
                                }
                            }
                            list.Add(row);
                        }
                    }
                }
            }
            return Ok(list);
        }

    }
}