using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using FCOMMON;

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

        /// <summary>
        /// 메모장 목록 조회
        /// </summary>
        public string Note_GetList(string startDate, string endDate, string uid = "")
        {
            try
            {
                // 로그인 체크
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var connStr = Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    var cmd = new SqlCommand();
                    cmd.Connection = conn;

                    // 권한 체크: 레벨5 미만이면 자기 것만 보거나 공유된 것만 조회
                    int curLevel = Math.Max(info.Login.level, DBM.getAuth(DBM.eAuthType.jobreport));
                    
                    if (curLevel >= 5)
                    {
                        // 관리자: 모든 메모 조회 가능
                        if (string.IsNullOrEmpty(uid))
                        {
                            cmd.CommandText = @"
                                SELECT idx, gcode, pdate, title, uid, share, wuid, wdate, guid, 
                                       ISNULL(viewcount, 0) as viewcount, viewdate,
                                       '' as description, '' as description2
                                FROM EETGW_Note WITH (nolock)
                                WHERE gcode = @gcode AND pdate BETWEEN @startDate AND @endDate
                                ORDER BY ISNULL(viewdate, '1900-01-01') DESC, ISNULL(viewcount, 0) DESC, pdate DESC";
                        }
                        else
                        {
                            cmd.CommandText = @"
                                SELECT idx, gcode, pdate, title, uid, share, wuid, wdate, guid,
                                       ISNULL(viewcount, 0) as viewcount, viewdate,
                                       '' as description, '' as description2
                                FROM EETGW_Note WITH (nolock)
                                WHERE gcode = @gcode AND pdate BETWEEN @startDate AND @endDate AND uid = @uid
                                ORDER BY ISNULL(viewdate, '1900-01-01') DESC, ISNULL(viewcount, 0) DESC, pdate DESC";
                            cmd.Parameters.Add("@uid", SqlDbType.VarChar).Value = uid;
                        }
                    }
                    else
                    {
                        // 일반 사용자: 자신이 작성했거나 공유된 메모만 조회
                        cmd.CommandText = @"
                            SELECT idx, gcode, pdate, title, uid, share, wuid, wdate, guid,
                                   ISNULL(viewcount, 0) as viewcount, viewdate,
                                   '' as description, '' as description2
                            FROM EETGW_Note WITH (nolock)
                            WHERE (gcode = @gcode AND pdate BETWEEN @startDate AND @endDate AND uid = @currentUid) 
                               OR (gcode = @gcode AND pdate BETWEEN @startDate AND @endDate AND ISNULL(share, 0) = 1)
                            ORDER BY ISNULL(viewdate, '1900-01-01') DESC, ISNULL(viewcount, 0) DESC, pdate DESC";
                        cmd.Parameters.Add("@currentUid", SqlDbType.VarChar).Value = info.Login.no;
                    }

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@startDate", SqlDbType.VarChar).Value = startDate;
                    cmd.Parameters.Add("@endDate", SqlDbType.VarChar).Value = endDate;

                    var list = new List<object>();
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            list.Add(new
                            {
                                idx = reader["idx"],
                                gcode = reader["gcode"],
                                pdate = reader["pdate"],
                                title = reader["title"],
                                uid = reader["uid"],
                                share = reader["share"],
                                wuid = reader["wuid"],
                                wdate = reader["wdate"],
                                guid = reader["guid"],
                                viewcount = reader["viewcount"],
                                viewdate = reader["viewdate"] != DBNull.Value ? reader["viewdate"] : null,
                                description = reader["description"],
                                description2 = reader["description2"]
                            });
                        }
                    }

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

        /// <summary>
        /// 메모장 상세 조회
        /// </summary>
        public string Note_GetDetail(int idx)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var cs = Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(cs))
                {
                    conn.Open();
                    
                    // 조회수 증가 및 조회일 업데이트
                    var updateCmd = new SqlCommand(@"
                        UPDATE EETGW_Note 
                        SET viewcount = ISNULL(viewcount, 0) + 1, viewdate = GETDATE()
                        WHERE gcode = @gcode AND idx = @idx", conn);
                    updateCmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    updateCmd.Parameters.Add("@idx", SqlDbType.Int).Value = idx;
                    updateCmd.ExecuteNonQuery();
                    
                    var cmd = new SqlCommand(@"
                        SELECT idx, gcode, pdate, title, uid, description, description2, share, wuid, wdate, guid,
                               ISNULL(viewcount, 0) as viewcount, viewdate
                        FROM EETGW_Note WITH (nolock)
                        WHERE gcode = @gcode AND idx = @idx", conn);
                    
                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@idx", SqlDbType.Int).Value = idx;

                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            var item = new
                            {
                                idx = reader["idx"],
                                gcode = reader["gcode"],
                                pdate = reader["pdate"],
                                title = reader["title"],
                                uid = reader["uid"],
                                description = reader["description"],
                                description2 = reader["description2"],
                                share = reader["share"],
                                wuid = reader["wuid"],
                                wdate = reader["wdate"],
                                guid = reader["guid"],
                                viewcount = reader["viewcount"],
                                viewdate = reader["viewdate"] != DBNull.Value ? reader["viewdate"] : null
                            };
                            return JsonConvert.SerializeObject(new { Success = true, Data = item });
                        }
                        else
                        {
                            return JsonConvert.SerializeObject(new { Success = false, Message = "데이터를 찾을 수 없습니다." });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 메모장 추가
        /// </summary>
        public string Note_Add(string pdate, string title, string uid, string description, string description2, bool share, string guid)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                // GUID가 비어있으면 생성
                if (string.IsNullOrEmpty(guid))
                {
                    guid = Guid.NewGuid().ToString();
                }

                var cs = Properties.Settings.Default.gwcs;
                using (var conn = new SqlConnection(cs))
                {
                    conn.Open();
                    var cmd = new SqlCommand(@"
                        INSERT INTO EETGW_Note (gcode, pdate, title, uid, description, description2, share, wuid, wdate, guid)
                        VALUES (@gcode, @pdate, @title, @uid, @description, @description2, @share, @wuid, @wdate, @guid);
                        SELECT CAST(SCOPE_IDENTITY() AS INT);", conn);

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@pdate", SqlDbType.VarChar).Value = pdate;
                    cmd.Parameters.Add("@title", SqlDbType.NVarChar).Value = title;
                    cmd.Parameters.Add("@uid", SqlDbType.VarChar).Value = uid;
                    cmd.Parameters.Add("@description", SqlDbType.NVarChar).Value = description ?? "";
                    cmd.Parameters.Add("@description2", SqlDbType.NText).Value = description2 ?? "";
                    cmd.Parameters.Add("@share", SqlDbType.Bit).Value = share;
                    cmd.Parameters.Add("@wuid", SqlDbType.VarChar).Value = info.Login.no;
                    cmd.Parameters.Add("@wdate", SqlDbType.DateTime).Value = DateTime.Now;
                    cmd.Parameters.Add("@guid", SqlDbType.VarChar).Value = guid;

                    var newIdx = cmd.ExecuteScalar();
                    return JsonConvert.SerializeObject(new { Success = true, Idx = newIdx });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 메모장 수정
        /// </summary>
        public string Note_Edit(int idx, string pdate, string title, string uid, string description, string description2, bool share, string guid)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var connStr = Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();

                    // 권한 체크: 자신의 메모이거나 관리자인 경우만 수정 가능
                    int curLevel = Math.Max(info.Login.level, DBM.getAuth(DBM.eAuthType.jobreport));
                    
                    var checkCmd = new SqlCommand(@"
                        SELECT uid FROM EETGW_Note WHERE gcode = @gcode AND idx = @idx", conn);
                    checkCmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    checkCmd.Parameters.Add("@idx", SqlDbType.Int).Value = idx;
                    
                    var originalUid = checkCmd.ExecuteScalar()?.ToString();
                    if (originalUid != info.Login.no && curLevel < 5)
                    {
                        return JsonConvert.SerializeObject(new { Success = false, Message = "타인의 자료는 수정할 수 없습니다." });
                    }

                    var cmd = new SqlCommand(@"
                        UPDATE EETGW_Note 
                        SET pdate = @pdate, title = @title, uid = @uid, 
                            description = @description, description2 = @description2, 
                            share = @share, guid = @guid, wuid = @wuid, wdate = @wdate
                        WHERE gcode = @gcode AND idx = @idx", conn);

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@idx", SqlDbType.Int).Value = idx;
                    cmd.Parameters.Add("@pdate", SqlDbType.VarChar).Value = pdate;
                    cmd.Parameters.Add("@title", SqlDbType.NVarChar).Value = title;
                    cmd.Parameters.Add("@uid", SqlDbType.VarChar).Value = uid;
                    cmd.Parameters.Add("@description", SqlDbType.NVarChar).Value = description ?? "";
                    cmd.Parameters.Add("@description2", SqlDbType.NText).Value = description2 ?? "";
                    cmd.Parameters.Add("@share", SqlDbType.Bit).Value = share;
                    cmd.Parameters.Add("@guid", SqlDbType.VarChar).Value = guid;
                    cmd.Parameters.Add("@wuid", SqlDbType.VarChar).Value = info.Login.no;
                    cmd.Parameters.Add("@wdate", SqlDbType.DateTime).Value = DateTime.Now;

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

        /// <summary>
        /// 멤모장 삭제
        /// </summary>
        public string Note_Delete(int idx)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var connStr = Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();

                    // 권한 체크: 자신의 메모이거나 관리자인 경우만 삭제 가능
                    int curLevel = Math.Max(info.Login.level, DBM.getAuth(DBM.eAuthType.jobreport));
                    
                    var checkCmd = new SqlCommand(@"
                        SELECT uid FROM EETGW_Note WHERE gcode = @gcode AND idx = @idx", conn);
                    checkCmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    checkCmd.Parameters.Add("@idx", SqlDbType.Int).Value = idx;
                    
                    var originalUid = checkCmd.ExecuteScalar()?.ToString();
                    if (originalUid != info.Login.no && curLevel < 5)
                    {
                        return JsonConvert.SerializeObject(new { Success = false, Message = "타인의 자료는 삭제할 수 없습니다." });
                    }

                    var cmd = new SqlCommand(@"
                        DELETE FROM EETGW_Note 
                        WHERE gcode = @gcode AND idx = @idx", conn);

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@idx", SqlDbType.Int).Value = idx;

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

        #endregion
    }
}
