399 lines
13 KiB
JavaScript
399 lines
13 KiB
JavaScript
import { useEffect, useState } from 'react'
|
|
import { useRecoilState } from 'recoil'
|
|
import { v4 as uuidv4, validate as isValidUUID } from 'uuid'
|
|
import { canvasState, currentCanvasPlanState, initCanvasPlansState, plansState, modifiedPlansState, modifiedPlanFlagState } from '@/store/canvasAtom'
|
|
import { useAxios } from '@/hooks/useAxios'
|
|
import { useMessage } from '@/hooks/useMessage'
|
|
import { useSwal } from '@/hooks/useSwal'
|
|
import { SAVE_KEY } from '@/common/common'
|
|
|
|
export function usePlan() {
|
|
const [planNum, setPlanNum] = useState(0)
|
|
const [selectedPlan, setSelectedPlan] = useState(null)
|
|
const [currentCanvasStatus, setCurrentCanvasStatus] = useState(null)
|
|
|
|
const [canvas, setCanvas] = useRecoilState(canvasState)
|
|
const [currentCanvasPlan, setCurrentCanvasPlan] = useRecoilState(currentCanvasPlanState)
|
|
const [initCanvasPlans, setInitCanvasPlans] = useRecoilState(initCanvasPlansState) // DB에 저장된 plan
|
|
const [plans, setPlans] = useRecoilState(plansState) // 전체 plan (DB에 저장된 plan + 저장 안된 새로운 plan)
|
|
const [modifiedPlans, setModifiedPlans] = useRecoilState(modifiedPlansState) // 변경된 canvas plan
|
|
const [modifiedPlanFlag, setModifiedPlanFlag] = useRecoilState(modifiedPlanFlagState) // 캔버스 실시간 오브젝트 이벤트 감지 flag
|
|
|
|
const { swalFire } = useSwal()
|
|
const { getMessage } = useMessage()
|
|
const { get, promisePost, promisePut, promiseDel } = useAxios()
|
|
|
|
/**
|
|
* 마우스 포인터의 가이드라인을 제거합니다.
|
|
*/
|
|
const removeMouseLines = () => {
|
|
if (canvas?._objects.length > 0) {
|
|
const mouseLines = canvas?._objects.filter((obj) => obj.name === 'mouseLine')
|
|
mouseLines.forEach((item) => canvas?.remove(item))
|
|
}
|
|
canvas?.renderAll()
|
|
}
|
|
|
|
const addCanvas = () => {
|
|
const objs = canvas?.toJSON(SAVE_KEY)
|
|
|
|
const str = JSON.stringify(objs)
|
|
|
|
// canvas?.clear()
|
|
return str
|
|
|
|
// setTimeout(() => {
|
|
// // 역직렬화하여 캔버스에 객체를 다시 추가합니다.
|
|
// canvas?.loadFromJSON(JSON.parse(str), function () {
|
|
// // 모든 객체가 로드되고 캔버스에 추가된 후 호출됩니다.
|
|
// console.log(canvas?.getObjects().filter((obj) => obj.name === 'roof'))
|
|
// canvas?.renderAll() // 캔버스를 다시 그립니다.
|
|
// })
|
|
// }, 1000)
|
|
}
|
|
|
|
/**
|
|
* 현재 캔버스에 그려진 데이터를 추출
|
|
*/
|
|
const currentCanvasData = (mode = '') => {
|
|
removeMouseLines()
|
|
canvas.discardActiveObject()
|
|
|
|
if (mode === 'save') {
|
|
const groups = canvas.getObjects().filter((obj) => obj.type === 'group')
|
|
|
|
if (groups.length > 0) {
|
|
groups.forEach((group) => {
|
|
canvas?.remove(group)
|
|
canvas?.renderAll()
|
|
const restore = group._restoreObjectsState() //그룹 좌표 복구
|
|
|
|
//그룹시 좌표가 틀어지는 이슈
|
|
restore._objects.forEach((obj) => {
|
|
obj.set({
|
|
...obj,
|
|
groupYn: true,
|
|
groupName: group.name,
|
|
groupId: group.id,
|
|
})
|
|
|
|
//디렉션이 있는 경우에만
|
|
if (group.lineDirection) obj.set({ lineDirection: group.lineDirection })
|
|
//부모객체가 있으면 (면형상 위에 도머등..)
|
|
if (group.parentId) obj.set({ parentId: group.parentId })
|
|
|
|
canvas?.add(obj)
|
|
obj.setCoords()
|
|
canvas?.renderAll()
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
return addCanvas()
|
|
}
|
|
|
|
/**
|
|
* 캔버스에서 발생하는 실시간 오브젝트 이벤트를 감지하여 수정 여부를 확인 후 관리
|
|
*/
|
|
const checkCanvasObjectEvent = (planId) => {
|
|
setCurrentCanvasStatus(currentCanvasData())
|
|
if (!modifiedPlans.some((modifiedPlan) => modifiedPlan === planId) && checkModifiedCanvasPlan(planId)) {
|
|
setModifiedPlans((prev) => [...prev, planId])
|
|
setModifiedPlanFlag(false)
|
|
}
|
|
}
|
|
useEffect(() => {
|
|
if (currentCanvasStatus) {
|
|
setCurrentCanvasPlan((prev) => ({ ...prev, canvasStatus: currentCanvasStatus }))
|
|
}
|
|
}, [currentCanvasStatus])
|
|
/**
|
|
* 현재 캔버스 상태와 DB에 저장된 캔버스 상태를 비교하여 수정 여부를 판단
|
|
*/
|
|
const checkModifiedCanvasPlan = (planId) => {
|
|
const canvasStatus = currentCanvasData()
|
|
if (isValidUUID(planId)) {
|
|
// 새로운 캔버스
|
|
return JSON.parse(canvasStatus).objects.length > 0
|
|
} else {
|
|
// 저장된 캔버스
|
|
// 각각 object들의 uuid 목록을 추출하여 비교
|
|
const canvasObjsUuids = getObjectUuids(JSON.parse(canvasStatus).objects)
|
|
const initPlanData = initCanvasPlans.find((plan) => plan.id === planId)
|
|
const dbObjsUuids = getObjectUuids(JSON.parse(initPlanData.canvasStatus).objects)
|
|
return canvasObjsUuids.length !== dbObjsUuids.length || !canvasObjsUuids.every((uuid, index) => uuid === dbObjsUuids[index])
|
|
}
|
|
}
|
|
const getObjectUuids = (objects) => {
|
|
return objects
|
|
.filter((obj) => obj.hasOwnProperty('uuid'))
|
|
.map((obj) => obj.uuid)
|
|
.sort()
|
|
}
|
|
|
|
const resetModifiedPlans = () => {
|
|
setModifiedPlans([])
|
|
setModifiedPlanFlag(false)
|
|
}
|
|
|
|
/**
|
|
* 캔버스에 저장되지 않은 변경사항이 있을때 저장 여부를 확인 후 저장
|
|
*/
|
|
const checkUnsavedCanvasPlan = async (userId) => {
|
|
swalFire({
|
|
text: `저장 안된 ${currentCanvasPlan.name} PLAN을 저장하시겠습니까? `,
|
|
type: 'confirm',
|
|
confirmFn: async () => {
|
|
initCanvasPlans.some((plan) => plan.id === currentCanvasPlan.id)
|
|
? await putCanvasStatus(currentCanvasPlan.canvasStatus)
|
|
: await postCanvasStatus(userId, currentCanvasPlan.canvasStatus)
|
|
},
|
|
})
|
|
resetModifiedPlans()
|
|
}
|
|
|
|
/**
|
|
* DB에 저장된 데이터를 canvas에서 사용할 수 있도록 포맷화
|
|
*/
|
|
const dbToCanvasFormat = (cs) => {
|
|
return cs.replace(/##/g, '"').replace(/∠/g, '∠').replace(/°/g, '°')
|
|
}
|
|
|
|
/**
|
|
* canvas의 데이터를 DB에 저장할 수 있도록 포맷화
|
|
*/
|
|
const canvasToDbFormat = (cs) => {
|
|
return cs.replace(/"/g, '##')
|
|
}
|
|
|
|
/**
|
|
* 페이지 내 캔버스를 저장
|
|
*/
|
|
const saveCanvas = async (userId) => {
|
|
const canvasStatus = currentCanvasData('save')
|
|
initCanvasPlans.some((plan) => plan.id === currentCanvasPlan.id)
|
|
? await putCanvasStatus(canvasStatus)
|
|
: await postCanvasStatus(userId, canvasStatus)
|
|
}
|
|
|
|
/**
|
|
* objectNo에 해당하는 canvas 목록을 조회
|
|
*/
|
|
const getCanvasByObjectNo = async (userId, objectNo) => {
|
|
return get({ url: `/api/canvas-management/canvas-statuses/by-object/${objectNo}/${userId}` }).then((res) =>
|
|
res.map((item) => ({
|
|
id: item.id,
|
|
name: item.objectNo + '-' + item.id, // tab button에 표출될 이름 (임시)
|
|
userId: item.userId,
|
|
canvasStatus: dbToCanvasFormat(item.canvasStatus),
|
|
isCurrent: false,
|
|
bgImageName: item.bgImageName,
|
|
mapPositionAddress: item.mapPositionAddress,
|
|
})),
|
|
)
|
|
}
|
|
|
|
/**
|
|
* canvas 데이터를 추가
|
|
*/
|
|
const postCanvasStatus = async (userId, canvasStatus) => {
|
|
const planData = {
|
|
userId: userId,
|
|
imageName: 'image_name', // api 필수항목이여서 임시로 넣음, 이후 삭제 필요
|
|
objectNo: currentCanvasPlan.objectNo,
|
|
canvasStatus: canvasToDbFormat(canvasStatus),
|
|
}
|
|
await promisePost({ url: '/api/canvas-management/canvas-statuses', data: planData })
|
|
.then((res) => {
|
|
setInitCanvasPlans((initCanvasPlans) => [...initCanvasPlans, { id: res.data, canvasStatus: canvasStatus }])
|
|
setPlans((plans) =>
|
|
plans.map((plan) =>
|
|
plan.id === currentCanvasPlan.id
|
|
? {
|
|
...plan,
|
|
id: res.data,
|
|
name: currentCanvasPlan.objectNo + '-' + res.data,
|
|
canvasStatus: canvasStatus,
|
|
}
|
|
: plan,
|
|
),
|
|
)
|
|
setModifiedPlans((modifiedPlans) => modifiedPlans.filter((planId) => planId !== currentCanvasPlan.id))
|
|
})
|
|
.catch((error) => {
|
|
swalFire({ text: error.message, icon: 'error' })
|
|
})
|
|
}
|
|
|
|
/**
|
|
* id에 해당하는 canvas 데이터를 수정
|
|
*/
|
|
const putCanvasStatus = async (canvasStatus) => {
|
|
const planData = {
|
|
id: currentCanvasPlan.id,
|
|
canvasStatus: canvasToDbFormat(canvasStatus),
|
|
}
|
|
await promisePut({ url: '/api/canvas-management/canvas-statuses', data: planData })
|
|
.then((res) => {
|
|
setInitCanvasPlans((initCanvasPlans) =>
|
|
initCanvasPlans.map((plan) => (plan.id === currentCanvasPlan.id ? { ...plan, canvasStatus: canvasStatus } : plan)),
|
|
)
|
|
setPlans((plans) => plans.map((plan) => (plan.id === currentCanvasPlan.id ? { ...plan, canvasStatus: canvasStatus } : plan)))
|
|
setModifiedPlans((modifiedPlans) => modifiedPlans.filter((planId) => planId !== currentCanvasPlan.id))
|
|
})
|
|
.catch((error) => {
|
|
swalFire({ text: error.message, icon: 'error' })
|
|
})
|
|
}
|
|
|
|
/**
|
|
* id에 해당하는 canvas 데이터를 삭제
|
|
*/
|
|
const delCanvasById = (id) => {
|
|
return promiseDel({ url: `/api/canvas-management/canvas-statuses/by-id/${id}` })
|
|
}
|
|
|
|
/**
|
|
* objectNo에 해당하는 canvas 데이터들을 삭제
|
|
*/
|
|
const delCanvasByObjectNo = (objectNo) => {
|
|
return promiseDel({ url: `/api/canvas-management/canvas-statuses/by-object/${objectNo}` })
|
|
}
|
|
|
|
/**
|
|
* plan 이동
|
|
* 현재 plan의 작업상태를 확인, 저장 후 이동
|
|
*/
|
|
const handleCurrentPlan = async (userId, newCurrentId) => {
|
|
if (!currentCanvasPlan || currentCanvasPlan.id !== newCurrentId) {
|
|
if (currentCanvasPlan?.id && modifiedPlans.some((modifiedPlan) => modifiedPlan === currentCanvasPlan.id)) {
|
|
// swalFire({
|
|
// text: `${currentCanvasPlan.name} ` + getMessage('plan.message.confirm.save'),
|
|
// type: 'confirm',
|
|
// confirmFn: async () => {
|
|
// await saveCanvas(userId)
|
|
// updateCurrentPlan(newCurrentId)
|
|
// },
|
|
// denyFn: () => {
|
|
// updateCurrentPlan(newCurrentId)
|
|
// },
|
|
// })
|
|
await saveCanvas(userId)
|
|
}
|
|
updateCurrentPlan(newCurrentId)
|
|
}
|
|
}
|
|
const updateCurrentPlan = (newCurrentId) => {
|
|
setPlans((plans) =>
|
|
plans.map((plan) => {
|
|
return { ...plan, isCurrent: plan.id === newCurrentId }
|
|
}),
|
|
)
|
|
}
|
|
useEffect(() => {
|
|
setCurrentCanvasPlan(plans.find((plan) => plan.isCurrent) || null)
|
|
setSelectedPlan(plans.find((plan) => plan.isCurrent))
|
|
}, [plans])
|
|
|
|
/**
|
|
* 새로운 plan 생성
|
|
* 현재 plan의 데이터가 있을 경우 복제 여부를 확인
|
|
*/
|
|
const handleAddPlan = (userId, objectNo) => {
|
|
JSON.parse(currentCanvasData()).objects.length > 0
|
|
? swalFire({
|
|
text: `${currentCanvasPlan.name} ` + getMessage('plan.message.confirm.copy'),
|
|
type: 'confirm',
|
|
confirmFn: () => {
|
|
addPlan(userId, objectNo, currentCanvasData())
|
|
},
|
|
denyFn: () => {
|
|
addPlan(userId, objectNo, '')
|
|
},
|
|
})
|
|
: addPlan(userId, objectNo, '')
|
|
}
|
|
const addPlan = (userId, objectNo, canvasStatus) => {
|
|
const id = uuidv4()
|
|
const newPlan = {
|
|
id: id,
|
|
name: `Plan ${planNum + 1}`,
|
|
objectNo: objectNo,
|
|
userId: userId,
|
|
canvasStatus: canvasStatus,
|
|
}
|
|
setPlans([...plans, newPlan])
|
|
handleCurrentPlan(userId, id)
|
|
setPlanNum(planNum + 1)
|
|
}
|
|
|
|
/**
|
|
* plan 삭제
|
|
*/
|
|
const handleDeletePlan = (e, id) => {
|
|
e.stopPropagation() // 이벤트 버블링 방지
|
|
|
|
if (initCanvasPlans.some((plan) => plan.id === id)) {
|
|
delCanvasById(id)
|
|
.then((res) => {
|
|
setInitCanvasPlans((initCanvasPlans) => initCanvasPlans.filter((plan) => plan.id !== id))
|
|
setPlans((plans) => plans.filter((plan) => plan.id !== id))
|
|
setModifiedPlans((modifiedPlans) => modifiedPlans.filter((planId) => planId !== currentCanvasPlan.id))
|
|
swalFire({ text: getMessage('plan.message.delete') })
|
|
})
|
|
.catch((error) => {
|
|
swalFire({ text: error.message, icon: 'error' })
|
|
})
|
|
} else {
|
|
setPlans((plans) => plans.filter((plan) => plan.id !== id))
|
|
setModifiedPlans((modifiedPlans) => modifiedPlans.filter((planId) => planId !== currentCanvasPlan.id))
|
|
swalFire({ text: getMessage('plan.message.delete') })
|
|
}
|
|
|
|
// 삭제 후 last 데이터에 포커싱
|
|
const lastPlan = plans.filter((plan) => plan.id !== id).at(-1)
|
|
if (!lastPlan) {
|
|
setPlanNum(0)
|
|
setCurrentCanvasPlan(null)
|
|
} else if (id !== lastPlan.id) {
|
|
updateCurrentPlan(lastPlan.id)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* plan 조회
|
|
*/
|
|
const loadCanvasPlanData = (userId, objectNo) => {
|
|
getCanvasByObjectNo(userId, objectNo).then((res) => {
|
|
// console.log('canvas 목록 ', res)
|
|
if (res.length > 0) {
|
|
setInitCanvasPlans(res)
|
|
setPlans(res)
|
|
updateCurrentPlan(res.at(-1).id) // last 데이터에 포커싱
|
|
setPlanNum(res.length)
|
|
} else {
|
|
addPlan(userId, objectNo)
|
|
}
|
|
})
|
|
}
|
|
|
|
return {
|
|
canvas,
|
|
plans,
|
|
selectedPlan,
|
|
currentCanvasPlan,
|
|
modifiedPlans,
|
|
modifiedPlanFlag,
|
|
setModifiedPlanFlag,
|
|
checkCanvasObjectEvent,
|
|
checkUnsavedCanvasPlan,
|
|
resetModifiedPlans,
|
|
saveCanvas,
|
|
handleCurrentPlan,
|
|
handleAddPlan,
|
|
handleDeletePlan,
|
|
loadCanvasPlanData,
|
|
}
|
|
}
|