using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using FCOMMON;

namespace Project.Web
{
    public partial class MachineBridge
    {
        #region UserAuth API (사용자 권한)

        /// <summary>
        /// 사용자 권한 접근 가능 여부 확인 (Level 5 이상 또는 account 권한 5 이상)
        /// </summary>
        public string UserAuth_CanAccess()
        {
            try
            {
                int curLevel = Math.Max(info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
                bool canAccess = curLevel >= 5;

                return JsonConvert.SerializeObject(new
                {
                    Success = true,
                    CanAccess = canAccess,
                    Level = curLevel,
                    Message = canAccess ? "" : "(관리자/계정담당자) 전용 메뉴 입니다"
                });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 사용자 권한 목록 조회
        /// </summary>
        public string UserAuth_GetList()
        {
            try
            {
                var sql = @"SELECT idx, [user], gcode, account, purchase, purchaseEB, holyday,
                           project, jobreport, scheapp, equipment, otconfirm, holyreq, kuntae
                           FROM Auth WITH (nolock)
                           WHERE gcode = @gcode
                           ORDER BY [user]";

                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                using (var cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                    using (var da = new SqlDataAdapter(cmd))
                    {
                        var dt = new DataTable();
                        da.Fill(dt);
                        return JsonConvert.SerializeObject(new { Success = true, Data = dt });
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 사용자 권한 저장 (추가/수정)
        /// </summary>
        public string UserAuth_Save(int idx, string user, int account, int purchase, int purchaseEB,
            int holyday, int project, int jobreport, int scheapp, int equipment, int otconfirm, int holyreq, int kuntae)
        {
            try
            {
                var cs = Properties.Settings.Default.gwcs;

                if (idx == 0)
                {
                    // 신규 추가
                    // 먼저 중복 확인
                    using (var cn = new SqlConnection(cs))
                    {
                        var checkSql = "SELECT COUNT(*) FROM Auth WHERE gcode = @gcode AND [user] = @user";
                        using (var cmd = new SqlCommand(checkSql, cn))
                        {
                            cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                            cmd.Parameters.AddWithValue("@user", user ?? "");
                            cn.Open();
                            var count = (int)cmd.ExecuteScalar();
                            if (count > 0)
                            {
                                return JsonConvert.SerializeObject(new { Success = false, Message = "이미 등록된 사용자입니다." });
                            }
                        }
                    }

                    var sql = @"INSERT INTO Auth (gcode, [user], account, purchase, purchaseEB, holyday,
                               project, jobreport, scheapp, equipment, otconfirm, holyreq, kuntae)
                               VALUES (@gcode, @user, @account, @purchase, @purchaseEB, @holyday,
                               @project, @jobreport, @scheapp, @equipment, @otconfirm, @holyreq, @kuntae);
                               SELECT SCOPE_IDENTITY();";

                    using (var cn = new SqlConnection(cs))
                    using (var cmd = new SqlCommand(sql, cn))
                    {
                        cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                        cmd.Parameters.AddWithValue("@user", user ?? "");
                        cmd.Parameters.AddWithValue("@account", account);
                        cmd.Parameters.AddWithValue("@purchase", purchase);
                        cmd.Parameters.AddWithValue("@purchaseEB", purchaseEB);
                        cmd.Parameters.AddWithValue("@holyday", holyday);
                        cmd.Parameters.AddWithValue("@project", project);
                        cmd.Parameters.AddWithValue("@jobreport", jobreport);
                        cmd.Parameters.AddWithValue("@scheapp", scheapp);
                        cmd.Parameters.AddWithValue("@equipment", equipment);
                        cmd.Parameters.AddWithValue("@otconfirm", otconfirm);
                        cmd.Parameters.AddWithValue("@holyreq", holyreq);
                        cmd.Parameters.AddWithValue("@kuntae", kuntae);

                        cn.Open();
                        var newId = Convert.ToInt32(cmd.ExecuteScalar());
                        return JsonConvert.SerializeObject(new { Success = true, Message = "저장되었습니다.", Data = new { idx = newId } });
                    }
                }
                else
                {
                    // 수정
                    var sql = @"UPDATE Auth SET
                               [user] = @user, account = @account, purchase = @purchase, purchaseEB = @purchaseEB,
                               holyday = @holyday, project = @project, jobreport = @jobreport, scheapp = @scheapp,
                               equipment = @equipment, otconfirm = @otconfirm, holyreq = @holyreq, kuntae = @kuntae
                               WHERE idx = @idx AND gcode = @gcode";

                    using (var cn = new SqlConnection(cs))
                    using (var cmd = new SqlCommand(sql, cn))
                    {
                        cmd.Parameters.AddWithValue("@idx", idx);
                        cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                        cmd.Parameters.AddWithValue("@user", user ?? "");
                        cmd.Parameters.AddWithValue("@account", account);
                        cmd.Parameters.AddWithValue("@purchase", purchase);
                        cmd.Parameters.AddWithValue("@purchaseEB", purchaseEB);
                        cmd.Parameters.AddWithValue("@holyday", holyday);
                        cmd.Parameters.AddWithValue("@project", project);
                        cmd.Parameters.AddWithValue("@jobreport", jobreport);
                        cmd.Parameters.AddWithValue("@scheapp", scheapp);
                        cmd.Parameters.AddWithValue("@equipment", equipment);
                        cmd.Parameters.AddWithValue("@otconfirm", otconfirm);
                        cmd.Parameters.AddWithValue("@holyreq", holyreq);
                        cmd.Parameters.AddWithValue("@kuntae", kuntae);

                        cn.Open();
                        var result = cmd.ExecuteNonQuery();
                        return JsonConvert.SerializeObject(new { Success = result > 0, Message = result > 0 ? "수정되었습니다." : "수정에 실패했습니다." });
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 사용자 권한 삭제
        /// </summary>
        public string UserAuth_Delete(int idx)
        {
            try
            {
                var sql = "DELETE FROM Auth WHERE idx = @idx AND gcode = @gcode";

                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                using (var cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.AddWithValue("@idx", idx);
                    cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);

                    cn.Open();
                    var result = cmd.ExecuteNonQuery();
                    return JsonConvert.SerializeObject(new { Success = result > 0, Message = result > 0 ? "삭제되었습니다." : "삭제에 실패했습니다." });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 권한 항목 정보 반환 (프론트엔드 표시용)
        /// </summary>
        public string UserAuth_GetFields()
        {
            var fields = new[]
            {
                new { field = "user", label = "사용자 ID", description = "권한을 설정할 사용자 ID" },
                new { field = "account", label = "계정", description = "계정 관리 권한" },
                new { field = "purchase", label = "구매", description = "구매 관리 권한" },
                new { field = "purchaseEB", label = "구매(전자실)", description = "전자실 구매 권한" },
                new { field = "holyday", label = "출근부", description = "출근부 관리 권한" },
                new { field = "project", label = "프로젝트", description = "프로젝트 관리 권한" },
                new { field = "jobreport", label = "업무일지", description = "업무일지 관리 권한" },
                new { field = "scheapp", label = "스케쥴", description = "스케쥴 관리 권한" },
                new { field = "equipment", label = "장비목록", description = "장비 목록 관리 권한" },
                new { field = "otconfirm", label = "OT승인", description = "초과근무 승인 권한" },
                new { field = "holyreq", label = "휴가요청", description = "휴가 요청 관리 권한" },
                new { field = "kuntae", label = "근태", description = "근태 관리 권한" },
            };

            return JsonConvert.SerializeObject(new { Success = true, Data = fields });
        }

        /// <summary>
        /// 범용 권한 체크 API
        /// authType: purchase, holyday, project, jobreport, savecost, equipment, otconfirm, kuntae, holyreq, account, purchaseEB
        /// requiredLevel: 필요한 최소 레벨 (기본값 5)
        /// </summary>
        public string CheckAuth(string authType, int requiredLevel = 5)
        {
            try
            {
                // 사용자 기본 레벨
                int userLevel = info.Login.level;

                // authType에 해당하는 권한 레벨 조회
                int authLevel = 0;
                if (!string.IsNullOrEmpty(authType))
                {
                    if (Enum.TryParse<DBM.eAuthType>(authType, true, out var eType))
                    {
                        authLevel = DBM.getAuth(eType);
                    }
                }

                // 둘 중 높은 값 사용
                int effectiveLevel = Math.Max(userLevel, authLevel);
                bool canAccess = effectiveLevel >= requiredLevel;

                return JsonConvert.SerializeObject(new
                {
                    Success = true,
                    CanAccess = canAccess,
                    UserLevel = userLevel,
                    AuthLevel = authLevel,
                    EffectiveLevel = effectiveLevel,
                    RequiredLevel = requiredLevel,
                    AuthType = authType,
                    Message = canAccess ? "" : $"이 기능은 레벨 {requiredLevel} 이상 권한이 필요합니다."
                });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 현재 로그인한 사용자의 전체 권한 정보 조회
        /// </summary>
        public string GetMyAuth()
        {
            try
            {
                var sql = @"SELECT idx, [user], account, purchase, purchaseEB, holyday,
                           project, jobreport, scheapp, equipment, otconfirm, holyreq, kuntae
                           FROM Auth WITH (nolock)
                           WHERE gcode = @gcode AND [user] = @user";

                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                using (var cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                    cmd.Parameters.AddWithValue("@user", info.Login.no);
                    cn.Open();
                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            return JsonConvert.SerializeObject(new
                            {
                                Success = true,
                                Data = new
                                {
                                    UserLevel = info.Login.level,
                                    account = reader["account"] != DBNull.Value ? (int)reader["account"] : 0,
                                    purchase = reader["purchase"] != DBNull.Value ? (int)reader["purchase"] : 0,
                                    purchaseEB = reader["purchaseEB"] != DBNull.Value ? (int)reader["purchaseEB"] : 0,
                                    holyday = reader["holyday"] != DBNull.Value ? (int)reader["holyday"] : 0,
                                    project = reader["project"] != DBNull.Value ? (int)reader["project"] : 0,
                                    jobreport = reader["jobreport"] != DBNull.Value ? (int)reader["jobreport"] : 0,
                                    scheapp = reader["scheapp"] != DBNull.Value ? (int)reader["scheapp"] : 0,
                                    equipment = reader["equipment"] != DBNull.Value ? (int)reader["equipment"] : 0,
                                    otconfirm = reader["otconfirm"] != DBNull.Value ? (int)reader["otconfirm"] : 0,
                                    holyreq = reader["holyreq"] != DBNull.Value ? (int)reader["holyreq"] : 0,
                                    kuntae = reader["kuntae"] != DBNull.Value ? (int)reader["kuntae"] : 0,
                                }
                            });
                        }
                        else
                        {
                            // Auth 테이블에 없는 경우 기본값 반환
                            return JsonConvert.SerializeObject(new
                            {
                                Success = true,
                                Data = new
                                {
                                    UserLevel = info.Login.level,
                                    account = 0,
                                    purchase = 0,
                                    purchaseEB = 0,
                                    holyday = 0,
                                    project = 0,
                                    jobreport = 0,
                                    scheapp = 0,
                                    equipment = 0,
                                    otconfirm = 0,
                                    holyreq = 0,
                                    kuntae = 0,
                                }
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        #endregion
    }
}
