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

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

        /// <summary>
        /// 업체정보 목록 조회
        /// </summary>
        public string Customs_GetList(string searchKey = "")
        {
            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;

                    // 검색 조건이 있으면 필터링
                    if (string.IsNullOrEmpty(searchKey))
                    {
                        cmd.CommandText = @"
                            SELECT idx, grp, name, owner, ownertel, address, tel, fax, email, memo, 
                                   wuid, wdate, uptae, staff, stafftel, name2, gcode
                            FROM Customs WITH (nolock)
                            WHERE gcode = @gcode
                            ORDER BY name";
                    }
                    else
                    {
                        // 여러 필드에서 검색 (fCustoms.cs의 btFind_Click 로직 참고)
                        cmd.CommandText = @"
                            SELECT idx, grp, name, owner, ownertel, address, tel, fax, email, memo, 
                                   wuid, wdate, uptae, staff, stafftel, name2, gcode
                            FROM Customs WITH (nolock)
                            WHERE gcode = @gcode 
                              AND (stafftel LIKE @search 
                                   OR grp LIKE @search 
                                   OR name2 LIKE @search 
                                   OR name LIKE @search 
                                   OR owner LIKE @search 
                                   OR address LIKE @search 
                                   OR tel LIKE @search 
                                   OR email LIKE @search 
                                   OR memo LIKE @search 
                                   OR staff LIKE @search)
                            ORDER BY name";
                        cmd.Parameters.Add("@search", SqlDbType.NVarChar).Value = "%" + searchKey.Replace("'", "''") + "%";
                    }

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

                    var list = new List<object>();
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            list.Add(new
                            {
                                idx = reader["idx"],
                                grp = reader["grp"] != DBNull.Value ? reader["grp"] : "",
                                name = reader["name"] != DBNull.Value ? reader["name"] : "",
                                owner = reader["owner"] != DBNull.Value ? reader["owner"] : "",
                                ownertel = reader["ownertel"] != DBNull.Value ? reader["ownertel"] : "",
                                address = reader["address"] != DBNull.Value ? reader["address"] : "",
                                tel = reader["tel"] != DBNull.Value ? reader["tel"] : "",
                                fax = reader["fax"] != DBNull.Value ? reader["fax"] : "",
                                email = reader["email"] != DBNull.Value ? reader["email"] : "",
                                memo = reader["memo"] != DBNull.Value ? reader["memo"] : "",
                                wuid = reader["wuid"],
                                wdate = reader["wdate"],
                                uptae = reader["uptae"] != DBNull.Value ? reader["uptae"] : "",
                                staff = reader["staff"] != DBNull.Value ? reader["staff"] : "",
                                stafftel = reader["stafftel"] != DBNull.Value ? reader["stafftel"] : "",
                                name2 = reader["name2"] != DBNull.Value ? reader["name2"] : "",
                                gcode = reader["gcode"]
                            });
                        }
                    }

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

        /// <summary>
        /// 업체정보 상세 조회
        /// </summary>
        public string Customs_GetDetail(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();
                    var cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandText = @"
                        SELECT idx, grp, name, owner, ownertel, address, tel, fax, email, memo, 
                               wuid, wdate, uptae, staff, stafftel, name2, gcode
                        FROM Customs WITH (nolock)
                        WHERE idx = @idx AND gcode = @gcode";

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

                    object result = null;
                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            result = new
                            {
                                idx = reader["idx"],
                                grp = reader["grp"] != DBNull.Value ? reader["grp"] : "",
                                name = reader["name"] != DBNull.Value ? reader["name"] : "",
                                owner = reader["owner"] != DBNull.Value ? reader["owner"] : "",
                                ownertel = reader["ownertel"] != DBNull.Value ? reader["ownertel"] : "",
                                address = reader["address"] != DBNull.Value ? reader["address"] : "",
                                tel = reader["tel"] != DBNull.Value ? reader["tel"] : "",
                                fax = reader["fax"] != DBNull.Value ? reader["fax"] : "",
                                email = reader["email"] != DBNull.Value ? reader["email"] : "",
                                memo = reader["memo"] != DBNull.Value ? reader["memo"] : "",
                                wuid = reader["wuid"],
                                wdate = reader["wdate"],
                                uptae = reader["uptae"] != DBNull.Value ? reader["uptae"] : "",
                                staff = reader["staff"] != DBNull.Value ? reader["staff"] : "",
                                stafftel = reader["stafftel"] != DBNull.Value ? reader["stafftel"] : "",
                                name2 = reader["name2"] != DBNull.Value ? reader["name2"] : "",
                                gcode = reader["gcode"]
                            };
                        }
                    }

                    if (result == null)
                    {
                        return JsonConvert.SerializeObject(new { Success = false, Message = "해당 업체 정보를 찾을 수 없습니다.", Data = (object)null });
                    }

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

        #endregion
    }
}
