using System;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using FCOMMON;
using Project.Web.Model;

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

        /// <summary>
        /// 급한 할일 목록 조회
        /// </summary>
        public string GetUrgentTodos()
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인되지 않은 상태입니다." });
                }

                var sql = @"SELECT * FROM EETGW_Todo
                    WHERE gcode = @gcode AND uid = @uid
                    and isnull(status,'0') not in ('2','3','5')
                    ORDER BY flag DESC, seqno DESC, expire ASC, wdate ASC";

                var todos = DBM.Query<TodoModel>(sql, new { gcode = info.Login.gcode, uid = info.Login.no });

                return JsonConvert.SerializeObject(new { Success = true, Data = todos }, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    DateFormatString = "yyyy-MM-dd HH:mm:ss"
                });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "급한 Todo 목록을 가져오는 중 오류가 발생했습니다: " + ex.Message });
            }
        }

        /// <summary>
        /// 할일 상세 조회
        /// </summary>
        public string GetTodo(int id)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인되지 않은 상태입니다." });
                }

                if (id <= 0)
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "유효하지 않은 Todo ID입니다." });
                }

                var sql = "SELECT * FROM EETGW_Todo WHERE idx = @idx AND gcode = @gcode AND uid = @uid";
                var todo = DBM.QuerySingleOrDefault<TodoModel>(sql, new { idx = id, gcode = info.Login.gcode, uid = info.Login.no });

                if (todo == null)
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "할일을 찾을 수 없습니다." });
                }

                return JsonConvert.SerializeObject(new { Success = true, Data = todo }, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    DateFormatString = "yyyy-MM-dd HH:mm:ss"
                });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "할일 조회 중 오류가 발생했습니다: " + ex.Message });
            }
        }


        /// <summary>
        /// 할일 추가
        /// </summary>
        public string CreateTodo(string title, string remark, string expire, int seqno, bool flag, string request, string status)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인되지 않은 상태입니다." });
                }

                if (string.IsNullOrEmpty(remark))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "할일 내용은 필수입니다." });
                }

                DateTime? expireDate = null;
                if (!string.IsNullOrEmpty(expire))
                {
                    if (DateTime.TryParse(expire, out DateTime parsed))
                        expireDate = parsed;
                }

                DateTime? okdateValue = null;
                if (status == "5")
                {
                    okdateValue = DateTime.Now;
                }

                var sql = @"
                    INSERT INTO EETGW_Todo (gcode, uid, title, remark, flag, expire, seqno, request, status, okdate, wuid, wdate)
                    VALUES (@gcode, @uid, @title, @remark, @flag, @expire, @seqno, @request, @status, @okdate, @wuid, @wdate);
                    SELECT SCOPE_IDENTITY();";

                var newId = DBM.QuerySingle<int>(sql, new
                {
                    gcode = info.Login.gcode,
                    uid = info.Login.no,
                    title = title,
                    remark = remark,
                    flag = flag,
                    expire = expireDate,
                    seqno = seqno,
                    request = request,
                    status = string.IsNullOrEmpty(status) ? "0" : status,
                    okdate = okdateValue,
                    wuid = info.Login.no,
                    wdate = DateTime.Now
                });

                return JsonConvert.SerializeObject(new { Success = true, Message = "할일이 추가되었습니다.", Data = new { idx = newId } });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "할일 추가 중 오류가 발생했습니다: " + ex.Message });
            }
        }

        #endregion

        #region Todo Extended API

        /// <summary>
        /// 할일 전체 목록 조회
        /// </summary>
        public string Todo_GetTodos()
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인되지 않은 상태입니다." });
                }

                var sql = @"SELECT * FROM EETGW_Todo
                           WHERE gcode = @gcode AND uid = @uid
                           ORDER BY flag DESC, seqno DESC, expire ASC, wdate ASC";

                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", info.Login.no);

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

                return JsonConvert.SerializeObject(new { Success = true, Data = dt }, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DateFormatString = "yyyy-MM-dd HH:mm:ss" });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 할일 수정
        /// </summary>
        public string Todo_UpdateTodo(int idx, string title, string remark, string expire, int seqno, bool flag, string request, string status)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인되지 않은 상태입니다." });
                }

                DateTime? expireDate = null;
                if (!string.IsNullOrEmpty(expire))
                {
                    if (DateTime.TryParse(expire, out DateTime parsed))
                        expireDate = parsed;
                }

                DateTime? okdateValue = null;
                if (status == "5")
                {
                    okdateValue = DateTime.Now;
                }

                var sql = @"UPDATE EETGW_Todo SET
                           title = @title, remark = @remark, expire = @expire, seqno = @seqno,
                           flag = @flag, request = @request, status = @status, okdate = @okdate,
                           wuid = @wuid, wdate = GETDATE()
                           WHERE idx = @idx AND gcode = @gcode AND uid = @uid";

                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var cmd = new SqlCommand(sql, cn);
                cmd.Parameters.AddWithValue("@idx", idx);
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                cmd.Parameters.AddWithValue("@uid", info.Login.no);
                cmd.Parameters.AddWithValue("@title", title ?? "");
                cmd.Parameters.AddWithValue("@remark", remark ?? "");
                cmd.Parameters.AddWithValue("@expire", expireDate.HasValue ? (object)expireDate.Value : DBNull.Value);
                cmd.Parameters.AddWithValue("@seqno", seqno);
                cmd.Parameters.AddWithValue("@flag", flag);
                cmd.Parameters.AddWithValue("@request", request ?? "");
                cmd.Parameters.AddWithValue("@status", string.IsNullOrEmpty(status) ? "0" : status);
                cmd.Parameters.AddWithValue("@okdate", okdateValue.HasValue ? (object)okdateValue.Value : DBNull.Value);
                cmd.Parameters.AddWithValue("@wuid", info.Login.no);

                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 Todo_DeleteTodo(int id)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인되지 않은 상태입니다." });
                }

                var sql = "DELETE FROM EETGW_Todo WHERE idx = @idx AND gcode = @gcode AND uid = @uid";

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

                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
    }
}
