summaryrefslogtreecommitdiff
path: root/components/vendor-info/pq-simple-dialog.tsx
blob: fbff2a1c3912deaca2d1c5705576c955dc8c0bb6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
"use client"

import { useState, useEffect } from "react"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Download, FileText, ChevronDown, ChevronUp, Search } from "lucide-react"
import { Input } from "@/components/ui/input"
import { toast } from "sonner"
import { getPQProjectsByVendorId, ProjectPQ, getPQDataByVendorId, PQGroupData } from "@/lib/pq/service"
// downloadFile은 동적으로 import

interface PQSimpleDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  vendorId: string
}

interface PQItemData {
  groupName: string
  code: string
  checkPoint: string
  description: string
  answer: string | null
  inputFormat: string
  fileName?: string | null
  filePath?: string | null
}

export function PQSimpleDialog({
  open,
  onOpenChange,
  vendorId,
}: PQSimpleDialogProps) {
  const [projects, setProjects] = useState<ProjectPQ[]>([])
  const [selectedProject, setSelectedProject] = useState<ProjectPQ | null>(null)
  const [pqData, setPqData] = useState<PQGroupData[]>([])
  const [loading, setLoading] = useState(false)
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set())
  const [searchTerm, setSearchTerm] = useState("")

  // vendorId를 숫자로 변환
  const numericVendorId = parseInt(vendorId)

  useEffect(() => {
    if (open && !isNaN(numericVendorId)) {
      loadProjects()
    }
  }, [open, numericVendorId])

  const loadProjects = async () => {
    try {
      setLoading(true)
      const projectList = await getPQProjectsByVendorId(numericVendorId)
      setProjects(projectList)
      
      if (projectList.length > 0) {
        setSelectedProject(projectList[0])
        await loadPQData(projectList[0].projectId)
      }
    } catch (error) {
      console.error("프로젝트 목록 로드 실패:", error)
      toast.error("PQ 프로젝트 목록을 불러오는데 실패했습니다.")
    } finally {
      setLoading(false)
    }
  }

  const loadPQData = async (projectId: number | null) => {
    if (projectId === null) return
    
    try {
      setLoading(true)
      const data = await getPQDataByVendorId(numericVendorId, projectId)
      setPqData(data)
    } catch (error) {
      console.error("PQ 데이터 로드 실패:", error)
      toast.error("PQ 데이터를 불러오는데 실패했습니다.")
    } finally {
      setLoading(false)
    }
  }

  const handleProjectChange = async (project: ProjectPQ) => {
    setSelectedProject(project)
    await loadPQData(project.projectId)
  }

  const handleFileDownload = async (filePath: string, fileName: string) => {
    try {
      // 동적으로 downloadFile 함수 import
      const { downloadFile } = await import('@/lib/file-download')
      
      const result = await downloadFile(filePath, fileName)
      if (result.success) {
        toast.success(`${fileName} 파일이 다운로드되었습니다.`)
      } else {
        toast.error(result.error || "파일 다운로드에 실패했습니다.")
      }
    } catch (error) {
      console.error("파일 다운로드 오류:", error)
      toast.error("파일 다운로드에 실패했습니다.")
    }
  }

  // 코드 순서로 정렬하는 함수 (1-1-1, 1-1-2, 1-2-1 순서)
  const sortByCode = (items: any[]) => {
    return [...items].sort((a, b) => {
      const parseCode = (code: string) => {
        return code.split('-').map(part => parseInt(part, 10))
      }
      
      const aCode = parseCode(a.code)
      const bCode = parseCode(b.code)
      
      for (let i = 0; i < Math.max(aCode.length, bCode.length); i++) {
        const aPart = aCode[i] || 0
        const bPart = bCode[i] || 0
        if (aPart !== bPart) {
          return aPart - bPart
        }
      }
      return 0
    })
  }

  // 검색 필터링 함수
  const filterItems = (items: any[], searchTerm: string) => {
    if (!searchTerm.trim()) return items
    
    const search = searchTerm.toLowerCase()
    return items.filter(item => 
      item.checkPoint?.toLowerCase().includes(search) ||
      item.description?.toLowerCase().includes(search) ||
      item.code?.toLowerCase().includes(search)
    )
  }

  // 그룹별로 정렬 및 필터링된 데이터 계산
  const processedPQData = pqData.map(group => ({
    ...group,
    items: filterItems(sortByCode(group.items), searchTerm)
  })).filter(group => group.items.length > 0) // 검색 결과가 없는 그룹은 제외

  const toggleGroup = (groupName: string) => {
    setExpandedGroups(prev => {
      const newSet = new Set(prev)
      if (newSet.has(groupName)) {
        newSet.delete(groupName)
      } else {
        newSet.add(groupName)
      }
      return newSet
    })
  }

  const renderPQContent = (groupData: PQGroupData) => {
    const isExpanded = expandedGroups.has(groupData.groupName)
    const itemCount = groupData.items.length
    
    return (
      <Card key={groupData.groupName} className="mb-4">
        <CardHeader 
          className="cursor-pointer hover:bg-muted/50 transition-colors"
          onClick={() => toggleGroup(groupData.groupName)}
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <CardTitle className="text-base font-medium">
                {groupData.groupName}
              </CardTitle>
              <Badge variant="secondary" className="text-xs">
                {itemCount}개 항목
              </Badge>
            </div>
            {isExpanded ? (
              <ChevronUp className="w-4 h-4 text-muted-foreground" />
            ) : (
              <ChevronDown className="w-4 h-4 text-muted-foreground" />
            )}
          </div>
        </CardHeader>
        
        {isExpanded && (
          <CardContent className="pt-0">
            <div className="space-y-3">
              {groupData.items.map((item, index) => (
                <div 
                  key={`${groupData.groupName}-${index}`}
                  className="border rounded-lg p-4 hover:bg-muted/30 transition-colors"
                >
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <div className="flex items-center gap-2">
                        <Badge variant="outline" className="font-mono text-xs">
                          {item.code}
                        </Badge>
                        <Badge variant="secondary" className="text-xs">
                          {item.inputFormat}
                        </Badge>
                      </div>
                      <h4 className="font-medium text-sm">
                        {item.checkPoint}
                      </h4>
                      {item.description && (
                        <p className="text-sm text-muted-foreground">
                          {item.description}
                        </p>
                      )}
                    </div>
                    
                    <div className="space-y-2">
                      <div>
                        <label className="text-xs font-medium text-muted-foreground">답변</label>
                        <p className="text-sm mt-1 p-2 bg-muted/50 rounded border min-h-[2.5rem]">
                          {item.answer || "답변 없음"}
                        </p>
                      </div>
                      
                      {item.attachments && item.attachments.length > 0 && (
                        <div>
                          <label className="text-xs font-medium text-muted-foreground">첨부파일</label>
                          <div className="mt-1 space-y-1">
                            {item.attachments.map((attachment, idx) => (
                              <Button
                                key={idx}
                                variant="outline"
                                size="sm"
                                onClick={() => handleFileDownload(attachment.filePath, attachment.fileName)}
                                className="h-8 w-full justify-start text-xs"
                              >
                                <FileText className="w-3 h-3 mr-2" />
                                <span className="truncate flex-1 text-left">
                                  {attachment.fileName}
                                </span>
                                <Download className="w-3 h-3 ml-2" />
                              </Button>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        )}
      </Card>
    )
  }

  if (projects.length === 0 && !loading) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>PQ 조회</DialogTitle>
          </DialogHeader>
          <div className="text-center py-8">
            <p className="text-muted-foreground">제출된 PQ가 없습니다.</p>
          </div>
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>PQ 조회</DialogTitle>
        </DialogHeader>
        
        {loading ? (
          <div className="text-center py-8">
            <p className="text-muted-foreground">로딩 중...</p>
          </div>
        ) : selectedProject ? (
          <div className="space-y-4">
            {/* 프로젝트 선택 */}
            {projects.length > 1 && (
              <div className="space-y-2">
                <label className="text-sm font-medium">프로젝트 선택</label>
                <Select
                  value={selectedProject.id.toString()}
                  onValueChange={(value) => {
                    const project = projects.find(p => p.id.toString() === value)
                    if (project) handleProjectChange(project)
                  }}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="프로젝트를 선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {projects.map((project) => (
                      <SelectItem key={project.id} value={project.id.toString()}>
                        <div className="flex flex-col items-start">
                          <span className="font-medium">{project.projectCode}</span>
                          <span className="text-xs text-muted-foreground">
                            {project.projectName}
                          </span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
            
            {/* 프로젝트 정보 카드 */}
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <CardTitle className="text-lg">{selectedProject.projectName}</CardTitle>
                    <Badge 
                      variant={selectedProject.status === 'APPROVED' ? 'default' : 'secondary'}
                      className="text-xs"
                    >
                      {selectedProject.status}
                    </Badge>
                  </div>
                </div>
                <div className="text-sm text-muted-foreground">
                  <span className="font-medium">프로젝트 코드:</span> {selectedProject.projectCode} • 
                  <span className="font-medium">제출일:</span> {selectedProject.submittedAt ? new Date(selectedProject.submittedAt).toLocaleDateString('ko-KR') : '-'}
                </div>
              </CardHeader>
            </Card>
            
            {/* 검색 및 PQ 그룹 데이터 */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-semibold">PQ 항목</h3>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setExpandedGroups(new Set(processedPQData.map(g => g.groupName)))}
                  >
                    모두 펼치기
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setExpandedGroups(new Set())}
                  >
                    모두 접기
                  </Button>
                </div>
              </div>
              
              {/* 검색 박스 */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
                <Input
                  placeholder="항목 검색 (체크포인트, 세부내용, 코드)"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
                {searchTerm && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setSearchTerm("")}
                    className="absolute right-2 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0"
                  >
                    ×
                  </Button>
                )}
              </div>

              {/* 검색 결과 카운트 */}
              {searchTerm && (
                <div className="text-sm text-muted-foreground">
                  검색 결과: {processedPQData.reduce((total, group) => total + group.items.length, 0)}개 항목 
                  ({processedPQData.length}개 그룹)
                </div>
              )}

              {/* PQ 그룹 목록 */}
              {processedPQData.length > 0 ? (
                processedPQData.map((groupData) => renderPQContent(groupData))
              ) : (
                <div className="text-center py-8">
                  <p className="text-muted-foreground">
                    {searchTerm ? "검색 결과가 없습니다." : "PQ 데이터가 없습니다."}
                  </p>
                </div>
              )}
            </div>
          </div>
        ) : null}
      </DialogContent>
    </Dialog>
  )
}