qcast-front/src/hooks/common/useRefFiles.js

284 lines
8.8 KiB
JavaScript

import { useEffect, useRef, useState } from 'react'
import { useRecoilState, useSetRecoilState } from 'recoil'
import { useSwal } from '@/hooks/useSwal'
import { useAxios } from '../useAxios'
import { currentCanvasPlanState } from '@/store/canvasAtom'
import { useCanvas } from '@/hooks/useCanvas'
import { deleteBackGroundImage, setBackGroundImage } from '@/lib/imageActions'
import { settingModalFirstOptionsState } from '@/store/settingAtom'
import { popSpinnerState } from '@/store/popupAtom'
/**
* 배경 이미지 관리
* 도면에 배경이미지를 로딩하는 기능을 제공
*
* 이미지 -> 캔버스 배경에 이미지 로드
* 주소 -> 구글 맵에서 주소 검색 후 이미지로 다운로드 받아서 캔버스 배경에 이미지 로드
* .dwg -> api를 통해서 .png로 변환 후 캔버스 배경에 이미지 로드
*
* setCurrentBgImage 에 이미지를 세팅하면 도면에 배경으로 로딩된다.
* 다만 S3 Response에 aws 고유 주소가 나오는데 여기서는 cloudfront 사용을 위해서 NEXT_PUBLIC_AWS_S3_BASE_URL 도메인을 사용한다.
* @returns {object}
*/
export function useRefFiles() {
const converterUrl = process.env.NEXT_PUBLIC_CONVERTER_API_URL
const [refImage, setRefImage] = useState(null)
const [refFileMethod, setRefFileMethod] = useState('1')
const [mapPositionAddress, setMapPositionAddress] = useState('')
const [currentBgImage, setCurrentBgImage] = useState(null)
const queryRef = useRef(null)
const [currentCanvasPlan, setCurrentCanvasPlan] = useRecoilState(currentCanvasPlanState)
const [settingModalFirstOptions, setSettingModalFirstOptions] = useRecoilState(settingModalFirstOptionsState)
const { handleBackImageLoadToCanvas } = useCanvas()
const { swalFire } = useSwal()
const { get, post, del } = useAxios()
const setPopSpinnerStore = useSetRecoilState(popSpinnerState)
useEffect(() => {
if (refFileMethod === '1') {
setMapPositionAddress('')
} else {
setRefImage(null)
}
}, [refFileMethod])
/**
* 최초 input type="file" 에 대한 이벤트
* 파일 불러오기 버튼 컨트롤
* @param {*} file
*/
const handleRefFile = (file) => {
console.log('handleRefFile', file)
console.log('refImage', refImage)
if (refImage) {
swalFire({
text: '파일을 변경하시겠습니까?',
type: 'confirm',
confirmFn: () => {
refFileSetting(file)
},
})
} else {
refFileSetting(file)
}
}
/**
* 허용하는 파일인지 체크한다
* @param {File} file
*/
const refFileSetting = (file) => {
console.log('🚀 ~ refFileSetting ~ file:', file)
if (file.name.split('.').pop() === 'dwg') {
handleUploadConvertRefFile(file)
} else {
if (file && ['image/png', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/gif'].includes(file.type)) {
handleUploadImageRefFile(file)
} else {
swalFire({
text: '이미지가 아닙니다.',
type: 'alert',
icon: 'error',
})
}
}
}
/**
* 이미지 파일 삭제
*/
const handleFileDelete = async () => {
swalFire({
text: '삭제하시겠습니까?',
type: 'confirm',
confirmFn: async () => {
setPopSpinnerStore(true)
console.log('🚀 ~ handleFileDelete ~ handleFileDelete:', refImage)
console.log('🚀 ~ handleFileDelete ~ currentCanvasPlan.bgImageName:', currentCanvasPlan.bgImageName)
await del({ url: `${process.env.NEXT_PUBLIC_API_HOST_URL}/api/image/upload?fileName=${currentCanvasPlan.bgImageName}` })
setCurrentBgImage(null)
await deleteBackGroundImage({
objectId: currentCanvasPlan.id,
planNo: currentCanvasPlan.planNo,
})
setPopSpinnerStore(false)
},
})
}
/**
* 주소 맵 이미지 삭제
*/
const handleAddressDelete = async () => {
swalFire({
text: '삭제하시겠습니까?',
type: 'confirm',
confirmFn: async () => {
console.log('🚀 ~ handleAddressDelete ~ handleAddressDelete:', refImage)
console.log('🚀 ~ handleAddressDelete ~ currentCanvasPlan.bgImageName:', currentCanvasPlan.bgImageName)
await del({ url: `${process.env.NEXT_PUBLIC_API_HOST_URL}/api/image/map?fileName=${currentCanvasPlan.bgImageName}` })
setMapPositionAddress('')
setCurrentBgImage(null)
await deleteBackGroundImage({
objectId: currentCanvasPlan.id,
planNo: currentCanvasPlan.planNo,
})
},
})
}
/**
* 주소로 구글 맵 이미지 다운로드하여 캔버스 배경으로 로드
*/
const handleMapImageDown = async () => {
console.log('🚀 ~ handleMapImageDown ~ handleMapImageDown:')
if (queryRef.current.value === '' || queryRef.current.value === null) {
return
}
const newOption1 = settingModalFirstOptions.option1.map((option) => ({
...option,
selected: option.column === 'imageDisplay' ? true : option.selected,
}))
setSettingModalFirstOptions((prev) => ({
...prev,
option1: newOption1,
}))
const res = await get({
url: `${process.env.NEXT_PUBLIC_API_HOST_URL}/api/image/map?q=${queryRef.current.value}&fileNm=${currentCanvasPlan.id}&zoom=20`,
})
console.log('🚀 ~ handleMapImageDown ~ res:', res)
setCurrentBgImage(`${process.env.NEXT_PUBLIC_AWS_S3_BASE_URL}/${res.fileName}`)
await setBackGroundImage({
objectId: currentCanvasPlan.id,
planNo: currentCanvasPlan.planNo,
// imagePath: `${process.env.NEXT_PUBLIC_HOST_URL}${res.filePath}`,
imagePath: `${res.filePath}`,
})
}
/**
* 배경 이미지 로드를 위한 세팅
*/
useEffect(() => {
// if (!currentBgImage) {
// return
// }
console.log('🚀 ~ useEffect ~ currentBgImage:', currentBgImage)
if (currentBgImage) {
handleBackImageLoadToCanvas(currentBgImage)
setCurrentCanvasPlan((prev) => ({
...prev,
// bgImageName: refImage?.name ?? null,
bgImageName: currentBgImage.split('/').pop(),
mapPositionAddress: queryRef.current.value,
}))
} else {
setRefImage(null)
setCurrentCanvasPlan((prev) => ({
...prev,
bgImageName: null,
mapPositionAddress: null,
}))
}
}, [currentBgImage])
/**
* 이미지 파일 업로드
* @param {*} file
*/
const handleUploadImageRefFile = async (file) => {
setPopSpinnerStore(true)
const newOption1 = settingModalFirstOptions.option1.map((option) => ({
...option,
selected: option.column === 'imageDisplay' ? true : option.selected,
}))
setSettingModalFirstOptions((prev) => ({
...prev,
option1: newOption1,
}))
const formData = new FormData()
formData.append('file', file)
const res = await post({
url: `${process.env.NEXT_PUBLIC_API_HOST_URL}/api/image/upload`,
data: formData,
})
console.log('🚀 ~ handleUploadImageRefFile ~ res:', res)
setCurrentBgImage(`${process.env.NEXT_PUBLIC_AWS_S3_BASE_URL}/${res.fileName}`)
setRefImage(file)
const params = {
objectId: currentCanvasPlan.id,
planNo: currentCanvasPlan.planNo,
// imagePath: `${process.env.NEXT_PUBLIC_HOST_URL}${res.filePath}`,
imagePath: `${res.filePath}`,
}
console.log('🚀 ~ handleUploadImageRefFile ~ params:', params)
await setBackGroundImage(params)
setPopSpinnerStore(false)
}
/**
* RefFile이 캐드 도면 파일일 경우 변환하여 이미지로 저장
* @param {*} file
*/
const handleUploadConvertRefFile = async (file) => {
const formData = new FormData()
formData.append('file', file)
/** 캐드 도면 파일 변환 */
const res = await post({ url: converterUrl, data: formData })
console.log('🚀 ~ handleUploadConvertRefFile ~ res:', res)
/** 캐드 도면 파일 업로드 */
const result = await post({
url: `${process.env.NEXT_PUBLIC_API_HOST_URL}/api/image/cad`,
data: res,
})
console.log('🚀 ~ handleUploadConvertRefFile ~ result:', result)
setCurrentBgImage(`${process.env.NEXT_PUBLIC_AWS_S3_BASE_URL}/${res.fileName}`)
setRefImage(file)
const params = {
objectId: currentCanvasPlan.id,
planNo: currentCanvasPlan.planNo,
// imagePath: `${process.env.NEXT_PUBLIC_HOST_URL}${res.filePath}`,
imagePath: `${result.filePath}`,
}
console.log('🚀 ~ handleUploadImageRefFile ~ params:', params)
await setBackGroundImage(params)
}
/**
* 라디오 버튼 컨트롤
* @param {*} e
*/
const handleRefFileMethod = (e) => {
setRefFileMethod(e.target.value)
}
return {
refImage,
queryRef,
setRefImage,
handleRefFile,
refFileMethod,
setRefFileMethod,
mapPositionAddress,
setMapPositionAddress,
handleRefFileMethod,
handleFileDelete,
handleAddressDelete,
handleMapImageDown,
}
}