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

namespace Project.Web
{
    public partial class MachineBridge
    {
        /// <summary>
        /// 프로젝트별 파트리스트 조회
        /// </summary>
        public string PartList_GetList(int projectIdx)
        {
            try
            {
                var connStr = Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();


                    var cmd = new SqlCommand(@"
                        SELECT 
                            idx, no, Project, ItemGroup, ItemModel, ItemUnit, ItemName,
                            ItemSid, ItemSupply, ItemSupplyidx, ItemManu, Item,
                            option1, qty, qtyn, price, amt, remark, qtybuy
                        FROM ProjectsPart
                        WHERE Project = @ProjectIdx
                        ORDER BY ItemGroup, option1, no, ItemName
                    ", conn);

                    cmd.Parameters.Add("@ProjectIdx", SqlDbType.Int).Value = projectIdx;

                    var list = new List<object>();
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            list.Add(new
                            {
                                idx = reader.GetInt32(0),
                                no = reader.IsDBNull(1) ? 0 : reader.GetInt32(1),
                                Project = reader.GetInt32(2),
                                itemgroup = reader.IsDBNull(3) ? "" : reader.GetString(3),
                                itemmodel = reader.IsDBNull(4) ? "" : reader.GetString(4),
                                itemunit = reader.IsDBNull(5) ? "" : reader.GetString(5),
                                itemname = reader.IsDBNull(6) ? "" : reader.GetString(6),
                                itemsid = reader.IsDBNull(7) ? "" : reader.GetString(7),
                                itemsupply = reader.IsDBNull(8) ? "" : reader.GetString(8),
                                itemsupplyidx = reader.IsDBNull(9) ? 0 : reader.GetInt32(9),
                                itemmanu = reader.IsDBNull(10) ? "" : reader.GetString(10),
                                item = reader.IsDBNull(11) ? "" : reader.GetInt32(11).ToString(),
                                option1 = reader.IsDBNull(12) ? "" : reader.GetString(12),
                                qty = reader.IsDBNull(13) ? 0 : reader.GetInt32(13),
                                qtyn = reader.IsDBNull(14) ? 0 : reader.GetInt32(14),
                                price = reader.IsDBNull(15) ? 0.0 : (double)reader.GetDecimal(15),
                                amt = reader.IsDBNull(16) ? 0.0 : (double)reader.GetDecimal(16),
                                remark = reader.IsDBNull(17) ? "" : reader.GetString(17),
                                qtybuy = reader.IsDBNull(18) ? 0 : reader.GetInt32(18)
                            });
                        }
                    }                        var result = new
                        {
                            Success = true,
                            Data = list
                    };
                    return JsonConvert.SerializeObject(result);
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new
                {
                    Success = false,
                    Message = "파트리스트 조회 실패: " + ex.Message
                });
            }
        }

        /// <summary>
        /// 파트리스트 항목 저장 (추가/수정)
        /// </summary>
        public string PartList_Save(
            int idx,
            int projectIdx,
            string itemgroup,
            string itemname,
            string item,
            string itemmodel,
            string itemscale,
            string itemunit,
            double qty,
            double price,
            string itemsupply,
            int itemsupplyidx,
            string itemmanu,
            string itemsid,
            string option1,
            string remark,
            int no,
            double qtybuy)
        {
            try
            {
                var connStr = Properties.Settings.Default.CS;
                using (var con = new SqlConnection(connStr))
                    {
                        con.Open();

                        if (idx == 0 || idx == -1) // 새로 추가
                        {
                            using (var cmd = new SqlCommand(@"
                                INSERT INTO ProjectsPart (
                                    Project, ItemGroup, ItemName, Item, ItemModel, 
                                    ItemUnit, Qty, Price, ItemSupply, 
                                    ItemSupplyIdx, ItemManu, ItemSid, option1, 
                                    remark, no, qtybuy, wuid, wdate
                                ) VALUES (
                                    @Project, @ItemGroup, @ItemName, @Item, @ItemModel, 
                                    @ItemUnit, @Qty, @Price, @ItemSupply, 
                                    @ItemSupplyIdx, @ItemManu, @ItemSid, @option1, 
                                    @remark, @no, @qtybuy, @wuid, @wdate
                                )
                            ", con))
                            {
                                cmd.Parameters.AddWithValue("@Project", projectIdx);
                                cmd.Parameters.AddWithValue("@ItemGroup", itemgroup ?? "");
                                cmd.Parameters.AddWithValue("@ItemName", itemname ?? "");
                                cmd.Parameters.AddWithValue("@Item", item ?? "");
                                cmd.Parameters.AddWithValue("@ItemModel", itemmodel ?? "");
                                cmd.Parameters.AddWithValue("@ItemUnit", itemunit ?? "");
                                cmd.Parameters.AddWithValue("@Qty", qty);
                                cmd.Parameters.AddWithValue("@Price", price);
                                cmd.Parameters.AddWithValue("@ItemSupply", itemsupply ?? "");
                                cmd.Parameters.AddWithValue("@ItemSupplyIdx", itemsupplyidx);
                                cmd.Parameters.AddWithValue("@ItemManu", itemmanu ?? "");
                                cmd.Parameters.AddWithValue("@ItemSid", itemsid ?? "");
                                cmd.Parameters.AddWithValue("@option1", option1 ?? "");
                                cmd.Parameters.AddWithValue("@remark", remark ?? "");
                                cmd.Parameters.AddWithValue("@no", no);
                                cmd.Parameters.AddWithValue("@qtybuy", qtybuy);
                                cmd.Parameters.AddWithValue("@wuid", info.Login.no);
                                cmd.Parameters.AddWithValue("@wdate", DateTime.Now);

                                cmd.ExecuteNonQuery();
                            }
                        }
                        else // 수정
                        {
                            using (var cmd = new SqlCommand(@"
                                UPDATE ProjectsPart SET
                                    ItemGroup = @ItemGroup,
                                    ItemName = @ItemName,
                                    Item = @Item,
                                    ItemModel = @ItemModel,
                                    ItemUnit = @ItemUnit,
                                    Qty = @Qty,
                                    Price = @Price,
                                    ItemSupply = @ItemSupply,
                                    ItemSupplyIdx = @ItemSupplyIdx,
                                    ItemManu = @ItemManu,
                                    ItemSid = @ItemSid,
                                    option1 = @option1,
                                    remark = @remark,
                                    no = @no,
                                    qtybuy = @qtybuy
                                WHERE idx = @idx
                            ", con))
                            {
                                cmd.Parameters.AddWithValue("@idx", idx);
                                cmd.Parameters.AddWithValue("@ItemGroup", itemgroup ?? "");
                                cmd.Parameters.AddWithValue("@ItemName", itemname ?? "");
                                cmd.Parameters.AddWithValue("@Item", item ?? "");
                                cmd.Parameters.AddWithValue("@ItemModel", itemmodel ?? "");
                                cmd.Parameters.AddWithValue("@ItemUnit", itemunit ?? "");
                                cmd.Parameters.AddWithValue("@Qty", qty);
                                cmd.Parameters.AddWithValue("@Price", price);
                                cmd.Parameters.AddWithValue("@ItemSupply", itemsupply ?? "");
                                cmd.Parameters.AddWithValue("@ItemSupplyIdx", itemsupplyidx);
                                cmd.Parameters.AddWithValue("@ItemManu", itemmanu ?? "");
                                cmd.Parameters.AddWithValue("@ItemSid", itemsid ?? "");
                                cmd.Parameters.AddWithValue("@option1", option1 ?? "");
                                cmd.Parameters.AddWithValue("@remark", remark ?? "");
                                cmd.Parameters.AddWithValue("@no", no);
                                cmd.Parameters.AddWithValue("@qtybuy", qtybuy);

                                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 PartList_Delete(int idx)
        {
            try
            {
                var connStr = Properties.Settings.Default.CS;
                using (var con = new SqlConnection(connStr))
                {
                    con.Open();

                    var cmd = new SqlCommand(@"
                        DELETE FROM ProjectsPart WHERE idx = @idx
                    ", con);

                    cmd.Parameters.Add("@idx", SqlDbType.Int).Value = idx;
                    cmd.ExecuteNonQuery();

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