347 lines
10 KiB
JavaScript
347 lines
10 KiB
JavaScript
import { useEffect, useState } from 'react'
|
|
import { useRecoilState } from 'recoil'
|
|
import { canvasState, currentCanvasPlanState, initCanvasPlansState, plansState } from '@/store/canvasAtom'
|
|
import { useAxios } from '@/hooks/useAxios'
|
|
import { useMessage } from '@/hooks/useMessage'
|
|
import { useSwal } from '@/hooks/useSwal'
|
|
|
|
export function usePlan() {
|
|
const [planNum, setPlanNum] = useState(0)
|
|
|
|
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 { 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([
|
|
'selectable',
|
|
'name',
|
|
'parentId',
|
|
'id',
|
|
'length',
|
|
'idx',
|
|
'direction',
|
|
'lines',
|
|
'points',
|
|
'lockMovementX',
|
|
'lockMovementY',
|
|
'lockRotation',
|
|
'lockScalingX',
|
|
'lockScalingY',
|
|
'opacity',
|
|
'cells',
|
|
'maxX',
|
|
'maxY',
|
|
'minX',
|
|
'minY',
|
|
'x',
|
|
'y',
|
|
'x1',
|
|
'x2',
|
|
'y1',
|
|
'y2',
|
|
'attributes',
|
|
'stickeyPoint',
|
|
'text',
|
|
])
|
|
|
|
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 = () => {
|
|
removeMouseLines()
|
|
return addCanvas()
|
|
}
|
|
|
|
/**
|
|
* 실시간 캔버스 상태와 DB에 저장된 캔버스 상태를 비교하여 수정 여부를 판단
|
|
*/
|
|
const checkModifiedCanvasPlan = () => {
|
|
const canvasStatus = currentCanvasData()
|
|
const initPlanData = initCanvasPlans.find((plan) => plan.id === currentCanvasPlan.id)
|
|
|
|
if (!initPlanData) {
|
|
// 새로운 캔버스
|
|
return JSON.parse(canvasStatus).objects.length > 0
|
|
} else {
|
|
// 저장된 캔버스
|
|
// 각각 object들의 id 목록을 추출하여 비교
|
|
const canvasObjsIds = getObjectIds(JSON.parse(canvasStatus).objects)
|
|
const dbObjsIds = getObjectIds(JSON.parse(initPlanData.canvasStatus).objects)
|
|
return canvasObjsIds.length !== dbObjsIds.length || !canvasObjsIds.every((id, index) => id === dbObjsIds[index])
|
|
}
|
|
}
|
|
const getObjectIds = (objects) => {
|
|
return objects
|
|
.filter((obj) => obj.hasOwnProperty('id'))
|
|
.map((obj) => obj.id)
|
|
.sort()
|
|
}
|
|
|
|
/**
|
|
* DB에 저장된 데이터를 canvas에서 사용할 수 있도록 포맷화
|
|
*/
|
|
const dbToCanvasFormat = (cs) => {
|
|
return cs.replace(/##/g, '"')
|
|
}
|
|
|
|
/**
|
|
* canvas의 데이터를 DB에 저장할 수 있도록 포맷화
|
|
*/
|
|
const canvasToDbFormat = (cs) => {
|
|
return cs.replace(/"/g, '##')
|
|
}
|
|
|
|
/**
|
|
* 페이지 내 캔버스를 저장하는 함수
|
|
*
|
|
* 1. 신규 저장 : POST
|
|
* param(body) : userId, objectNo, canvasStatus
|
|
* 2. 수정 저장 : PUT
|
|
* param(body) : id, canvasStatus
|
|
*/
|
|
const saveCanvas = async (userId) => {
|
|
const canvasStatus = currentCanvasData()
|
|
initCanvasPlans.some((plan) => plan.id === currentCanvasPlan.id)
|
|
? await putCanvasStatus(canvasStatus)
|
|
: await postCanvasStatus(userId, canvasStatus)
|
|
}
|
|
|
|
/**
|
|
* objectNo에 해당하는 canvas 목록을 조회
|
|
*/
|
|
const getCanvasByObjectNo = async (userId, objectNo) => {
|
|
// console.log(`[GET] objectNo: ${objectNo} / userId: ${userId}`)
|
|
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,
|
|
})),
|
|
)
|
|
}
|
|
|
|
/**
|
|
* 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) => {
|
|
swalFire({ text: getMessage('common.message.save') })
|
|
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,
|
|
),
|
|
)
|
|
})
|
|
.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) => {
|
|
swalFire({ text: getMessage('common.message.save') })
|
|
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)))
|
|
})
|
|
.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 = (userId, newCurrentId) => {
|
|
if (!currentCanvasPlan || currentCanvasPlan.id !== newCurrentId) {
|
|
if (currentCanvasPlan?.id && checkModifiedCanvasPlan()) {
|
|
swalFire({
|
|
html: getMessage('common.message.confirm.save') + `</br>${currentCanvasPlan.name}`,
|
|
type: 'confirm',
|
|
confirmFn: async () => {
|
|
await saveCanvas(userId)
|
|
updateCurrentPlan(newCurrentId)
|
|
},
|
|
denyFn: () => {
|
|
updateCurrentPlan(newCurrentId)
|
|
},
|
|
})
|
|
} else {
|
|
updateCurrentPlan(newCurrentId)
|
|
}
|
|
}
|
|
}
|
|
const updateCurrentPlan = (newCurrentId) => {
|
|
setPlans((plans) =>
|
|
plans.map((plan) => {
|
|
return { ...plan, isCurrent: plan.id === newCurrentId }
|
|
}),
|
|
)
|
|
}
|
|
useEffect(() => {
|
|
setCurrentCanvasPlan(plans.find((plan) => plan.isCurrent) || null)
|
|
}, [plans])
|
|
|
|
/**
|
|
* 새로운 plan 생성
|
|
* 현재 plan의 데이터가 있을 경우 복제 여부를 확인
|
|
*/
|
|
const handleAddPlan = (userId, objectNo) => {
|
|
JSON.parse(currentCanvasData()).objects.length > 0
|
|
? swalFire({
|
|
html: `${currentCanvasPlan.name} PLAN을 복사하시겠습니까?`,
|
|
type: 'confirm',
|
|
confirmFn: () => {
|
|
addPlan(userId, objectNo, currentCanvasData())
|
|
},
|
|
denyFn: () => {
|
|
addPlan(userId, objectNo)
|
|
},
|
|
})
|
|
: addPlan(userId, objectNo)
|
|
}
|
|
const addPlan = (userId, objectNo, canvasStatus = '') => {
|
|
const newPlan = {
|
|
id: planNum,
|
|
name: `Plan ${planNum + 1}`,
|
|
objectNo: objectNo,
|
|
userId: userId,
|
|
canvasStatus: canvasStatus,
|
|
}
|
|
setPlans([...plans, newPlan])
|
|
handleCurrentPlan(userId, planNum)
|
|
setPlanNum(planNum + 1)
|
|
}
|
|
|
|
/**
|
|
* plan 삭제
|
|
*/
|
|
const handleDeletePlan = (e, id) => {
|
|
e.stopPropagation() // 이벤트 버블링 방지
|
|
|
|
if (initCanvasPlans.some((plan) => plan.id === id)) {
|
|
delCanvasById(id)
|
|
.then((res) => {
|
|
swalFire({ text: getMessage('common.message.delete') })
|
|
setInitCanvasPlans((initCanvasPlans) => initCanvasPlans.filter((plan) => plan.id !== id))
|
|
setPlans((plans) => plans.filter((plan) => plan.id !== id))
|
|
})
|
|
.catch((error) => {
|
|
swalFire({ text: error.message, icon: 'error' })
|
|
})
|
|
} else {
|
|
setPlans((plans) => plans.filter((plan) => plan.id !== id))
|
|
swalFire({ text: getMessage('common.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,
|
|
saveCanvas,
|
|
handleCurrentPlan,
|
|
handleAddPlan,
|
|
handleDeletePlan,
|
|
loadCanvasPlanData,
|
|
}
|
|
}
|