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

namespace Project.Web
{
    public partial class MachineBridge
    {
        #region UserGroup API (그룹정보/권한설정)

        /// <summary>
        /// 그룹 목록 조회
        /// </summary>
        public string UserGroup_GetList()
        {
            try
            {
                var sql = @"SELECT dept, gcode, path_kj, permission, advpurchase, advkisul,
                                   managerinfo, devinfo, usemail
                           FROM UserGroup WITH (nolock)
                           WHERE gcode = @gcode
                           ORDER BY dept";

                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 UserGroup_Add(string dept, string path_kj, int permission,
            bool advpurchase, bool advkisul, string managerinfo, string devinfo, bool usemail)
        {
            try
            {
                // 중복 체크
                var checkSql = "SELECT COUNT(*) FROM UserGroup WHERE gcode = @gcode AND dept = @dept";
                var cs = Properties.Settings.Default.gwcs;

                using (var cn = new SqlConnection(cs))
                {
                    cn.Open();
                    using (var checkCmd = new SqlCommand(checkSql, cn))
                    {
                        checkCmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                        checkCmd.Parameters.AddWithValue("@dept", dept);
                        var count = (int)checkCmd.ExecuteScalar();
                        if (count > 0)
                        {
                            return JsonConvert.SerializeObject(new { Success = false, Message = "이미 존재하는 부서명입니다." });
                        }
                    }

                    var sql = @"INSERT INTO UserGroup (dept, gcode, path_kj, permission, advpurchase, advkisul, managerinfo, devinfo, usemail)
                               VALUES (@dept, @gcode, @path_kj, @permission, @advpurchase, @advkisul, @managerinfo, @devinfo, @usemail)";

                    using (var cmd = new SqlCommand(sql, cn))
                    {
                        cmd.Parameters.AddWithValue("@dept", dept ?? "");
                        cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                        cmd.Parameters.AddWithValue("@path_kj", path_kj ?? "");
                        cmd.Parameters.AddWithValue("@permission", permission);
                        cmd.Parameters.AddWithValue("@advpurchase", advpurchase);
                        cmd.Parameters.AddWithValue("@advkisul", advkisul);
                        cmd.Parameters.AddWithValue("@managerinfo", managerinfo ?? "");
                        cmd.Parameters.AddWithValue("@devinfo", devinfo ?? "");
                        cmd.Parameters.AddWithValue("@usemail", usemail);
                        cmd.ExecuteNonQuery();
                        return JsonConvert.SerializeObject(new { Success = true, Message = "등록되었습니다." });
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 그룹 정보 수정
        /// </summary>
        public string UserGroup_Edit(string originalDept, string dept, string path_kj, int permission,
            bool advpurchase, bool advkisul, string managerinfo, string devinfo, bool usemail)
        {
            try
            {
                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                {
                    cn.Open();

                    // 부서명이 변경되었을 경우 중복 체크
                    if (originalDept != dept)
                    {
                        var checkSql = "SELECT COUNT(*) FROM UserGroup WHERE gcode = @gcode AND dept = @dept";
                        using (var checkCmd = new SqlCommand(checkSql, cn))
                        {
                            checkCmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                            checkCmd.Parameters.AddWithValue("@dept", dept);
                            var count = (int)checkCmd.ExecuteScalar();
                            if (count > 0)
                            {
                                return JsonConvert.SerializeObject(new { Success = false, Message = "이미 존재하는 부서명입니다." });
                            }
                        }
                    }

                    var sql = @"UPDATE UserGroup SET
                                   dept = @dept, path_kj = @path_kj, permission = @permission,
                                   advpurchase = @advpurchase, advkisul = @advkisul,
                                   managerinfo = @managerinfo, devinfo = @devinfo, usemail = @usemail
                               WHERE gcode = @gcode AND dept = @originalDept";

                    using (var cmd = new SqlCommand(sql, cn))
                    {
                        cmd.Parameters.AddWithValue("@originalDept", originalDept);
                        cmd.Parameters.AddWithValue("@dept", dept ?? "");
                        cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                        cmd.Parameters.AddWithValue("@path_kj", path_kj ?? "");
                        cmd.Parameters.AddWithValue("@permission", permission);
                        cmd.Parameters.AddWithValue("@advpurchase", advpurchase);
                        cmd.Parameters.AddWithValue("@advkisul", advkisul);
                        cmd.Parameters.AddWithValue("@managerinfo", managerinfo ?? "");
                        cmd.Parameters.AddWithValue("@devinfo", devinfo ?? "");
                        cmd.Parameters.AddWithValue("@usemail", usemail);
                        cmd.ExecuteNonQuery();
                        return JsonConvert.SerializeObject(new { Success = true, Message = "수정되었습니다." });
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 그룹 삭제
        /// </summary>
        public string UserGroup_Delete(string dept)
        {
            try
            {
                // 해당 그룹에 소속된 사용자가 있는지 확인
                var checkSql = "SELECT COUNT(*) FROM GroupUser WHERE gcode = @gcode AND dept = @dept";
                var cs = Properties.Settings.Default.gwcs;

                using (var cn = new SqlConnection(cs))
                {
                    cn.Open();

                    using (var checkCmd = new SqlCommand(checkSql, cn))
                    {
                        checkCmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                        checkCmd.Parameters.AddWithValue("@dept", dept);
                        var count = (int)checkCmd.ExecuteScalar();
                        if (count > 0)
                        {
                            return JsonConvert.SerializeObject(new { Success = false, Message = $"해당 그룹에 {count}명의 사용자가 소속되어 있어 삭제할 수 없습니다." });
                        }
                    }

                    var sql = "DELETE FROM UserGroup WHERE gcode = @gcode AND dept = @dept";
                    using (var cmd = new SqlCommand(sql, cn))
                    {
                        cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                        cmd.Parameters.AddWithValue("@dept", dept);
                        cmd.ExecuteNonQuery();
                        return JsonConvert.SerializeObject(new { Success = true, Message = "삭제되었습니다." });
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 권한 정보 목록 (프론트엔드용)
        /// </summary>
        public string UserGroup_GetPermissionInfo()
        {
            try
            {
                var permissions = new[]
                {
                    new { index = 0, name = "menu_purchase", label = "구매신청", description = "구매신청 메뉴 표시" },
                    new { index = 1, name = "menu_project", label = "프로젝트", description = "프로젝트 메뉴 표시" },
                    new { index = 2, name = "menu_history", label = "업무일지", description = "업무일지 메뉴 표시" },
                    new { index = 3, name = "menu_jago", label = "품목재고", description = "품목재고 메뉴 표시" },
                    new { index = 4, name = "menu_equipment", label = "장비목록", description = "장비목록 메뉴 표시" },
                    new { index = 5, name = "menu_workday", label = "근태관리", description = "근태관리 메뉴 표시" },
                    new { index = 6, name = "purchase_adv", label = "(구매)상세입력", description = "구매신청 상세입력 권한" },
                    new { index = 7, name = "menu_docu", label = "문서", description = "문서 메뉴 표시" },
                    new { index = 8, name = "menu_logdata", label = "운영기록", description = "운영기록 메뉴 표시" },
                    new { index = 9, name = "jobreport_kisul", label = "업무일지-기술료", description = "업무일지 기술료 보기 권한" },
                    new { index = 10, name = "jobreport_editblock", label = "업무일지-편집제한", description = "업무일지 편집 제한" },
                };

                return JsonConvert.SerializeObject(new { Success = true, Data = permissions });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        #endregion
    }
}
