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

namespace Project.Web
{
    public partial class MachineBridge
    {
        #region UserList API

        /// <summary>
        /// 현재 사용자 권한 레벨 조회 (로그인 레벨 + account 권한 중 높은 값)
        /// </summary>
        public string UserList_GetCurrentLevel()
        {
            try
            {
                int curLevel = Math.Max(info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
                return JsonConvert.SerializeObject(new
                {
                    Success = true,
                    Data = new
                    {
                        Level = curLevel,
                        CurrentUserId = info.Login.no,
                        CanEdit = curLevel >= 5
                    }
                });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "권한 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 부서 목록 조회
        /// </summary>
        public string UserList_GetDepts()
        {
            try
            {
                var sql = "SELECT DISTINCT dept FROM UserGroup WITH (NOLOCK) WHERE gcode = @gcode AND ISNULL(dept,'') <> '' ORDER BY dept";

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

                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cmd.Dispose();
                cn.Dispose();

                var result = new System.Collections.Generic.List<string>();
                foreach (DataRow dr in dt.Rows)
                {
                    result.Add(dr["dept"]?.ToString() ?? "");
                }

                return JsonConvert.SerializeObject(new { Success = true, Data = result });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "부서 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 사용자 목록 조회
        /// </summary>
        public string UserList_GetList(string process)
        {
            try
            {
                if (string.IsNullOrEmpty(process) || process == "%") process = "%";
                else process = "%" + process + "%";

                var gcode = info.Login.gcode;
                System.Diagnostics.Debug.WriteLine($"[UserList_GetList] gcode={gcode}, process={process}");

                var sql = @"SELECT gcode, dept, level, name, nameE, grade, email, tel, indate, outdate, hp,
                    memo, processs, id, state, useJobReport, useUserState, exceptHoly
                FROM vGroupUser WITH (NOLOCK)
                WHERE gcode = @gcode
                AND ISNULL(processs,'') LIKE @process
                ORDER BY useUserState DESC, useJobReport DESC, name";

                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var cmd = new SqlCommand(sql, cn);
                cmd.Parameters.AddWithValue("@gcode", gcode);
                cmd.Parameters.AddWithValue("@process", process);

                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);

                System.Diagnostics.Debug.WriteLine($"[UserList_GetList] 결과 행 수: {dt.Rows.Count}");

                da.Dispose();
                cmd.Dispose();
                cn.Dispose();

                return JsonConvert.SerializeObject(dt, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "사용자 목록 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 사용자 상세 정보 조회
        /// </summary>
        public string UserList_GetUser(string userId)
        {
            try
            {
                var sql = @"SELECT
                    u.id,
                    u.name,
                    u.nameE,
                    u.grade,
                    u.email,
                    u.tel,
                    u.indate,
                    u.outdate,
                    u.hp,
                    u.processs,
                    u.state,
                    u.memo,
                    gu.level,
                    gu.useUserState,
                    gu.useJobReport,
                    gu.exceptHoly,
                    gu.dept,
                    gu.gcode
                FROM EETGW_GroupUser gu WITH (NOLOCK)
                INNER JOIN Users u WITH (NOLOCK) ON gu.uid = u.id
                WHERE gu.gcode = @gcode AND gu.uid = @uid";

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

                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cmd.Dispose();
                cn.Dispose();

                if (dt.Rows.Count > 0)
                {
                    return JsonConvert.SerializeObject(new { Success = true, Data = dt.Rows[0] },
                        new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
                }
                else
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "사용자를 찾을 수 없습니다." });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "사용자 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 사용자 전체 정보 저장 (Users + GroupUser)
        /// </summary>
        public string UserList_SaveUserFull(string jsonData)
        {
            try
            {
                var userData = JsonConvert.DeserializeObject<UserListFullData>(jsonData);
                if (userData == null)
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "잘못된 데이터 형식입니다." });
                }

                // 권한 체크
                int curLevel = Math.Max(info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
                bool isSelf = info.Login.no == userData.id;

                // 본인이 아니고 권한이 없으면 거부
                if (!isSelf && curLevel < 5)
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "타인의 계정은 편집할 수 없습니다." });
                }

                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                {
                    cn.Open();

                    // Users 테이블 업데이트
                    var sqlUser = @"UPDATE Users SET
                        name = @name,
                        nameE = @nameE,
                        grade = @grade,
                        email = @email,
                        tel = @tel,
                        hp = @hp,
                        indate = @indate,
                        outdate = @outdate,
                        memo = @memo,
                        processs = @processs,
                        state = @state
                    WHERE id = @id";

                    using (var cmdUser = new SqlCommand(sqlUser, cn))
                    {
                        cmdUser.Parameters.AddWithValue("@id", userData.id);
                        cmdUser.Parameters.AddWithValue("@name", userData.name ?? "");
                        cmdUser.Parameters.AddWithValue("@nameE", userData.nameE ?? "");
                        cmdUser.Parameters.AddWithValue("@grade", userData.grade ?? "");
                        cmdUser.Parameters.AddWithValue("@email", userData.email ?? "");
                        cmdUser.Parameters.AddWithValue("@tel", userData.tel ?? "");
                        cmdUser.Parameters.AddWithValue("@hp", userData.hp ?? "");
                        cmdUser.Parameters.AddWithValue("@indate", userData.indate ?? "");
                        cmdUser.Parameters.AddWithValue("@outdate", userData.outdate ?? "");
                        cmdUser.Parameters.AddWithValue("@memo", userData.memo ?? "");
                        cmdUser.Parameters.AddWithValue("@processs", userData.processs ?? "");
                        cmdUser.Parameters.AddWithValue("@state", userData.state ?? "");
                        cmdUser.ExecuteNonQuery();
                    }

                    // EETGW_GroupUser 테이블 업데이트 (관리자만)
                    if (curLevel >= 5)
                    {
                        var sqlGroup = @"UPDATE EETGW_GroupUser SET
                            level = @level,
                            useUserState = @useUserState,
                            useJobReport = @useJobReport,
                            exceptHoly = @exceptHoly
                        WHERE gcode = @gcode AND uid = @uid";

                        using (var cmdGroup = new SqlCommand(sqlGroup, cn))
                        {
                            cmdGroup.Parameters.AddWithValue("@gcode", info.Login.gcode);
                            cmdGroup.Parameters.AddWithValue("@uid", userData.id);
                            cmdGroup.Parameters.AddWithValue("@level", userData.level);
                            cmdGroup.Parameters.AddWithValue("@useUserState", userData.useUserState);
                            cmdGroup.Parameters.AddWithValue("@useJobReport", userData.useJobReport);
                            cmdGroup.Parameters.AddWithValue("@exceptHoly", userData.exceptHoly);
                            cmdGroup.ExecuteNonQuery();
                        }
                    }
                }

                return JsonConvert.SerializeObject(new { Success = true, Message = "저장되었습니다." });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "저장 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 사용자 저장 (그룹 설정만)
        /// </summary>
        public string UserList_SaveGroupUser(string userId, string dept, int level, bool useUserState, bool useJobReport, bool exceptHoly)
        {
            try
            {
                // 권한 체크
                int curLevel = Math.Max(info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
                if (curLevel < 5)
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "사용자 관리 권한이 없습니다." });
                }

                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);

                var sql = @"UPDATE EETGW_GroupUser SET
                    dept = @dept,
                    level = @level,
                    useUserState = @useUserState,
                    useJobReport = @useJobReport,
                    exceptHoly = @exceptHoly
                WHERE gcode = @gcode AND uid = @uid";

                var cmd = new SqlCommand(sql, cn);
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                cmd.Parameters.AddWithValue("@uid", userId);
                cmd.Parameters.AddWithValue("@dept", dept ?? "");
                cmd.Parameters.AddWithValue("@level", level);
                cmd.Parameters.AddWithValue("@useUserState", useUserState);
                cmd.Parameters.AddWithValue("@useJobReport", useJobReport);
                cmd.Parameters.AddWithValue("@exceptHoly", exceptHoly);

                cn.Open();
                var result = cmd.ExecuteNonQuery();
                cn.Close();

                cmd.Dispose();
                cn.Dispose();

                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 UserList_DeleteGroupUser(string userId)
        {
            try
            {
                // 권한 체크
                int curLevel = Math.Max(info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
                if (curLevel < 5)
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "계정 관리자만 사용할 수 있습니다." });
                }

                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var sql = "DELETE FROM EETGW_GroupUser WHERE gcode = @gcode AND uid = @uid";
                var cmd = new SqlCommand(sql, cn);

                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                cmd.Parameters.AddWithValue("@uid", userId);

                cn.Open();
                var result = cmd.ExecuteNonQuery();
                cn.Close();

                cmd.Dispose();
                cn.Dispose();

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

        #endregion
    }

    /// <summary>
    /// 사용자 전체 정보 데이터 클래스
    /// </summary>
    public class UserListFullData
    {
        public string id { get; set; }
        public string name { get; set; }
        public string nameE { get; set; }
        public string grade { get; set; }
        public string email { get; set; }
        public string tel { get; set; }
        public string hp { get; set; }
        public string indate { get; set; }
        public string outdate { get; set; }
        public string memo { get; set; }
        public string processs { get; set; }
        public string state { get; set; }
        public int level { get; set; }
        public bool useUserState { get; set; }
        public bool useJobReport { get; set; }
        public bool exceptHoly { get; set; }
    }
}
