From b12a06766e32e3c76544b1d12bec91653e1fe9db Mon Sep 17 00:00:00 2001
From: 0-Zz-ang <s1998319@gmail.com>
Date: Mon, 25 Aug 2025 09:23:30 +0900
Subject: docu-list-rule페이지 수정
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../table/document-class-options-detail-sheet.tsx  | 69 ++++++++++++++++++++--
 1 file changed, 65 insertions(+), 4 deletions(-)

(limited to 'lib/docu-list-rule/document-class/table/document-class-options-detail-sheet.tsx')

diff --git a/lib/docu-list-rule/document-class/table/document-class-options-detail-sheet.tsx b/lib/docu-list-rule/document-class/table/document-class-options-detail-sheet.tsx
index 50e79d89..07384dd6 100644
--- a/lib/docu-list-rule/document-class/table/document-class-options-detail-sheet.tsx
+++ b/lib/docu-list-rule/document-class/table/document-class-options-detail-sheet.tsx
@@ -4,17 +4,21 @@ import * as React from "react"
 import { useReactTable, getCoreRowModel, getSortedRowModel, getFilteredRowModel, getPaginationRowModel } from "@tanstack/react-table"
 import { DataTableDetail } from "@/components/data-table/data-table-detail"
 import { DataTableAdvancedToolbarDetail } from "@/components/data-table/data-table-advanced-toolbar-detail"
+import { DragDropTable } from "@/lib/docu-list-rule/number-type-configs/table/drag-drop-table"
 import type { DataTableAdvancedFilterField, DataTableRowAction } from "@/types/table"
 import {
   Sheet,
   SheetContent,
 } from "@/components/ui/sheet"
-import { getDocumentClassSubOptions } from "@/lib/docu-list-rule/document-class/service"
+import { getDocumentClassSubOptions, updateDocumentClassOption } from "@/lib/docu-list-rule/document-class/service"
 import { getColumns } from "@/lib/docu-list-rule/document-class/table/document-class-options-table-columns"
 import { DocumentClassOptionEditSheet } from "@/lib/docu-list-rule/document-class/table/document-class-option-edit-sheet"
 import { DeleteDocumentClassOptionDialog } from "@/lib/docu-list-rule/document-class/table/delete-document-class-option-dialog"
 import { DocumentClassOptionsTableToolbarActions } from "@/lib/docu-list-rule/document-class/table/document-class-options-table-toolbar"
 import { documentClasses, documentClassOptions } from "@/db/schema/docu-list-rule"
+import { DragEndEvent } from '@dnd-kit/core'
+import { arrayMove } from '@dnd-kit/sortable'
+import { toast } from "sonner"
 
 type DocumentClassOption = typeof documentClassOptions.$inferSelect
 
@@ -65,6 +69,7 @@ export function DocumentClassOptionsDetailSheet({
       const result = await getDocumentClassSubOptions(documentClass.id, {
         page: 1,
         perPage: 10,
+        sort: [{ id: "sdq", desc: false }],
       })
       if (result.success && result.data) {
         setRawData({
@@ -94,7 +99,7 @@ export function DocumentClassOptionsDetailSheet({
     getFilteredRowModel: getFilteredRowModel(),
     getPaginationRowModel: getPaginationRowModel(),
     initialState: {
-      sorting: [{ id: "optionCode", desc: false }],
+      sorting: [{ id: "sdq", desc: false }],
       pagination: {
         pageSize: 10,
       },
@@ -102,6 +107,58 @@ export function DocumentClassOptionsDetailSheet({
     getRowId: (originalRow) => String(originalRow.id),
   })
 
+  // 드래그 종료 핸들러
+  const handleDragEnd = React.useCallback(async (event: DragEndEvent) => {
+    const { active, over } = event
+    console.log("Drag end event:", { active, over })
+
+    if (active.id !== over?.id) {
+      const oldIndex = rawData.data.findIndex((item) => String(item.id) === active.id)
+      const newIndex = rawData.data.findIndex((item) => String(item.id) === over?.id)
+      console.log("Indices:", { oldIndex, newIndex })
+
+      if (oldIndex !== -1 && newIndex !== -1) {
+        const reorderedData = arrayMove(rawData.data, oldIndex, newIndex)
+        
+        // 새로운 순서로 sdq 값 업데이트
+        const updatedOptions = reorderedData.map((item, index) => ({
+          ...item,
+          sdq: index + 1
+        }))
+
+        // 로컬 상태 먼저 업데이트
+        setRawData(prev => ({ ...prev, data: updatedOptions }))
+
+        // 서버에 순서 업데이트 (Combo Box Settings와 같은 방식)
+        try {
+          // 모든 항목을 임시 값으로 먼저 업데이트
+          for (let i = 0; i < updatedOptions.length; i++) {
+            const option = updatedOptions[i]
+            await updateDocumentClassOption({
+              id: option.id,
+              sdq: -(i + 1), // 임시 음수 값
+            })
+          }
+          
+          // 최종 순서로 업데이트
+          for (const option of updatedOptions) {
+            await updateDocumentClassOption({
+              id: option.id,
+              sdq: option.sdq,
+            })
+          }
+          
+          toast.success("순서가 성공적으로 변경되었습니다.")
+        } catch (error) {
+          console.error("Error updating order:", error)
+          toast.error("순서 변경 중 오류가 발생했습니다.")
+          // 에러 시 원래 데이터로 복원
+          await refreshData()
+        }
+      }
+    }
+  }, [rawData.data, refreshData])
+
   if (!documentClass) return null
 
   return (
@@ -122,12 +179,16 @@ export function DocumentClassOptionsDetailSheet({
           onSuccess={refreshData}
         />
 
-        <DataTableDetail table={table}>
+        <DragDropTable
+          table={table}
+          data={rawData.data}
+          onDragEnd={handleDragEnd}
+        >
           <DataTableAdvancedToolbarDetail
             table={table}
             filterFields={advancedFilterFields}
           />
-        </DataTableDetail>
+        </DragDropTable>
 
         <DeleteDocumentClassOptionDialog
           open={rowAction?.type === "delete"}
-- 
cgit v1.2.3

