qcast-front/src/hooks/roofcover/useRoofAllocationSetting.js

525 lines
16 KiB
JavaScript

import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'
import { canvasState, currentAngleTypeSelector, currentMenuState, currentObjectState } from '@/store/canvasAtom'
import { useEffect, useRef, useState } from 'react'
import { useAxios } from '@/hooks/useAxios'
import { useSwal } from '@/hooks/useSwal'
import { usePolygon } from '@/hooks/usePolygon'
import {
correntObjectNoState,
addedRoofsState,
basicSettingState,
roofDisplaySelector,
roofMaterialsSelector,
selectedRoofMaterialSelector,
} from '@/store/settingAtom'
import { usePopup } from '@/hooks/usePopup'
import { POLYGON_TYPE } from '@/common/common'
import { v4 as uuidv4 } from 'uuid'
import ActualSizeSetting from '@/components/floor-plan/modal/roofAllocation/ActualSizeSetting'
import { useMessage } from '@/hooks/useMessage'
import useMenu from '@/hooks/common/useMenu'
import { useCanvasMenu } from '@/hooks/common/useCanvasMenu'
import { menuTypeState } from '@/store/menuAtom'
import { useRoofFn } from '@/hooks/common/useRoofFn'
import { ROOF_MATERIAL_LAYOUT } from '@/components/floor-plan/modal/placementShape/PlacementShapeSetting'
import { globalLocaleStore } from '@/store/localeAtom'
import { getChonByDegree, getDegreeByChon } from '@/util/canvas-util'
// 지붕면 할당
export function useRoofAllocationSetting(id) {
const canvas = useRecoilValue(canvasState)
const [correntObjectNo, setCorrentObjectNo] = useRecoilState(correntObjectNoState)
const roofDisplay = useRecoilValue(roofDisplaySelector)
const { drawDirectionArrow, addLengthText, splitPolygonWithLines, splitPolygonWithSeparate } = usePolygon()
const [popupId, setPopupId] = useState(uuidv4())
const { addPopup, closePopup, closeAll } = usePopup()
const currentObject = useRecoilValue(currentObjectState)
const { setMenuNumber } = useCanvasMenu()
const setMenuType = useSetRecoilState(menuTypeState)
const roofMaterials = useRecoilValue(roofMaterialsSelector)
const selectedRoofMaterial = useRecoilValue(selectedRoofMaterialSelector)
const [basicSetting, setBasicSetting] = useRecoilState(basicSettingState)
const [currentRoofMaterial, setCurrentRoofMaterial] = useState(roofMaterials[0]) // 팝업 내 기준 지붕재
const [roofList, setRoofList] = useRecoilState(addedRoofsState) // 배치면 초기설정에서 선택한 지붕재 배열
const [editingLines, setEditingLines] = useState([])
const [currentRoofList, setCurrentRoofList] = useState([])
const currentAngleType = useRecoilValue(currentAngleTypeSelector)
const globalLocaleState = useRecoilValue(globalLocaleStore)
const [basicInfo, setBasicInfo] = useState(null)
const { get, post } = useAxios(globalLocaleState)
const { getMessage } = useMessage()
const { swalFire } = useSwal()
const { setSurfaceShapePattern } = useRoofFn()
useEffect(() => {
setCurrentRoofList(roofList)
}, [])
useEffect(() => {
const roofBases = canvas.getObjects().filter((obj) => obj.name === POLYGON_TYPE.ROOF) // roofPolygon.innerLines
roofBases.forEach((roof) => {
roof.innerLines.forEach((line) => {
if (!line.attributes.actualSize || line.attributes?.actualSize === 0) {
line.set({
strokeWidth: 4,
stroke: 'black',
selectable: true,
})
}
if (editingLines.includes(line)) {
line.set({
strokeWidth: 2,
stroke: 'black',
selectable: true,
})
}
})
})
if (currentObject && currentObject.name && ['auxiliaryLine', 'ridge', 'hip'].includes(currentObject.name)) {
currentObject.set({
strokeWidth: 4,
stroke: '#EA10AC',
})
}
}, [currentObject])
useEffect(() => {
// canvas.getObjects().filter((obj) => obj.type === 'QLine')
const roofBases = canvas.getObjects().filter((obj) => obj.name === POLYGON_TYPE.ROOF)
if (roofBases.length === 0) {
swalFire({ text: '할당할 지붕이 없습니다.' })
closePopup(id)
}
fetchBasicSettings()
}, [])
// 지붕면 할당 조회 및 초기화
const fetchBasicSettings = async () => {
try {
await get({ url: `/api/canvas-management/canvas-basic-settings/by-object/${correntObjectNo}` }).then((res) => {
console.log('🚀 ~ useRoofAllocationSetting ~ fetchBasicSettings ~ res >>>>>>>>>>>>>>>>>>>>> :', res)
let roofsArray = {}
if (res.length > 0) {
roofsArray = res.map((item) => {
return {
roofApply: item.roofApply,
roofSeq: item.roofSeq,
roofMatlCd: item.roofMatlCd,
roofWidth: item.roofWidth,
roofHeight: item.roofHeight,
roofHajebichi: item.roofHajebichi,
roofGap: item.roofGap,
roofLayout: item.roofLayout,
roofPitch: item.roofPitch,
roofAngle: item.roofAngle,
}
})
} else {
roofsArray = [
{
roofApply: true,
roofSeq: 0,
roofMatlCd: 'ROOF_ID_WA_53A',
roofWidth: 265,
roofHeight: 235,
roofHajebichi: 0,
roofGap: 'HEI_455',
roofLayout: 'P',
roofPitch: 4,
roofAngle: 21.8,
},
]
}
console.log('fetchBasicSettings roofsArray', roofsArray)
console.log(roofsArray)
// 데이터 설정
const selectRoofs = []
for (let i = 0; i < roofsArray.length; i++) {
roofMaterials?.map((material) => {
if (material.roofMatlCd === roofsArray[i].roofMatlCd) {
selectRoofs.push({
...material,
selected: roofsArray[i].roofApply,
index: roofsArray[i].roofSeq,
id: roofsArray[i].roofMatlCd,
width: roofsArray[i].roofWidth,
length: roofsArray[i].roofHeight,
hajebichi: roofsArray[i].roofHajebichi,
raft: roofsArray[i].roofGap,
layout: roofsArray[i].roofLayout,
pitch: roofsArray[i].roofPitch,
angle: roofsArray[i].roofAngle,
})
}
})
}
// setCurrentRoofList(selectRoofs)
//setBasicSetting({ ...basicSetting, roofsData: roofsArray })
setBasicSetting({
...basicSetting,
roofSizeSet: res[0].roofSizeSet,
roofAngleSet: res[0].roofAngleSet,
roofsData: roofsArray,
selectedRoofMaterial: selectRoofs.find((roof) => roof.selected),
})
setBasicInfo({
roofSizeSet: '' + res[0].roofSizeSet,
roofAngleSet: '' + res[0].roofAngleSet,
})
})
} catch (error) {
console.error('Data fetching error:', error)
}
}
// 지붕면 할당 저장
const basicSettingSave = async () => {
try {
const patternData = {
objectNo: correntObjectNo,
roofSizeSet: Number(basicSetting.roofSizeSet),
roofAngleSet: basicSetting.roofAngleSet,
roofAllocationList: currentRoofList.map((item, index) => ({
roofApply: item.selected,
roofSeq: index,
roofMatlCd: item.roofMatlCd === null || item.roofMatlCd === undefined ? 'ROOF_ID_WA_53A' : item.roofMatlCd,
roofWidth: item.width === null || item.width === undefined ? 0 : Number(item.width),
roofHeight: item.length === null || item.length === undefined ? 0 : Number(item.length),
roofHajebichi: item.hajebichi === null || item.hajebichi === undefined ? 0 : Number(item.hajebichi),
roofGap: item.raft === null || item.raft === undefined ? 'HEI_455' : item.raft,
roofLayout: item.layout === null || item.layout === undefined ? 'P' : item.layout,
roofPitch: item.pitch === null || item.pitch === undefined ? 4 : Number(item.pitch),
roofAngle: item.angle === null || item.angle === undefined ? 21.8 : Number(item.angle),
})),
}
console.log('🚀 ~ basicSettingSave ~ patternData >>>>>>>>>>>>> :', patternData)
await post({ url: `/api/canvas-management/roof-allocation-settings`, data: patternData }).then((res) => {
console.log('roof-allocation-settings res ', res)
swalFire({ text: getMessage(res.returnMessage) })
})
//Recoil 설정
//setCanvasSetting({ ...basicSetting })
fetchBasicSettings()
} catch (error) {
swalFire({ text: error.message, icon: 'error' })
}
}
const onAddRoofMaterial = () => {
if (currentRoofList.length >= 4) {
swalFire({ type: 'alert', icon: 'error', text: getMessage('지붕재는 4개까지 선택 가능합니다.') })
return
}
setCurrentRoofList([
...currentRoofList,
{
...currentRoofMaterial,
selected: false,
id: currentRoofMaterial.roofMatlCd,
name: currentRoofMaterial.roofMatlNm,
index: currentRoofList.length,
},
])
}
const onDeleteRoofMaterial = (idx) => {
const isSelected = currentRoofList[idx].selected
const newRoofList = [...currentRoofList].filter((_, index) => index !== idx)
if (isSelected) {
newRoofList[0].selected = true
}
setCurrentRoofList(newRoofList)
}
// 선택한 지붕재로 할당
const handleSave = () => {
basicSettingSave()
// 모두 actualSize 있으면 바로 적용 없으면 actualSize 설정
if (checkInnerLines()) {
addPopup(popupId, 1, <ActualSizeSetting id={popupId} />)
} else {
apply()
}
}
// 지붕재 오른쪽 마우스 클릭 후 단일로 지붕재 변경 필요한 경우
const handleSaveContext = () => {
const newRoofList = currentRoofList.map((roof, idx) => {
return { ...roof, index: idx }
})
setBasicSetting((prev) => {
return {
...prev,
selectedRoofMaterial: newRoofList.find((roof) => roof.selected),
}
})
setRoofList(newRoofList)
const selectedRoofMaterial = newRoofList.find((roof) => roof.selected)
setSurfaceShapePattern(currentObject, roofDisplay.column, false, selectedRoofMaterial)
closeAll()
}
const handleAlloc = () => {
if (!checkInnerLines()) {
apply()
} else {
swalFire({
type: 'alert',
icon: 'error',
text: getMessage('실제치수를 입력해 주세요.'),
})
}
}
const checkInnerLines = () => {
const roofBases = canvas.getObjects().filter((obj) => obj.name === POLYGON_TYPE.ROOF) // roofPolygon.innerLines
let result = false
roofBases.forEach((roof) => {
if (roof.separatePolygon.length === 0) {
roof.innerLines.forEach((line) => {
if (!line.attributes.actualSize || line.attributes?.actualSize === 0) {
line.set({
strokeWidth: 4,
stroke: 'black',
selectable: true,
})
result = true
}
})
}
})
if (result) canvas?.renderAll()
return result
}
const apply = () => {
const roofBases = canvas.getObjects().filter((obj) => obj.name === POLYGON_TYPE.ROOF)
const wallLines = canvas.getObjects().filter((obj) => obj.name === POLYGON_TYPE.WALL)
roofBases.forEach((roofBase) => {
try {
if (roofBase.separatePolygon.length > 0) {
splitPolygonWithSeparate(roofBase.separatePolygon)
} else {
splitPolygonWithLines(roofBase)
}
} catch (e) {
return
}
roofBase.innerLines.forEach((line) => {
canvas.remove(line)
})
canvas.remove(roofBase)
})
wallLines.forEach((wallLine) => {
canvas.remove(wallLine)
})
const newRoofList = currentRoofList.map((roof, idx) => {
return { ...roof, index: idx, ...basicInfo }
})
console.log('basicInfo', newRoofList)
setBasicSetting((prev) => {
return {
...prev,
selectedRoofMaterial: newRoofList.find((roof) => roof.selected),
}
})
setRoofList(newRoofList)
const roofs = canvas.getObjects().filter((obj) => obj.name === 'roof')
roofs.forEach((roof) => {
if (roof.isFixed) return
roof.set({
isFixed: true,
})
setSurfaceShapePattern(
roof,
roofDisplay.column,
false,
currentRoofList.find((roof) => roof.selected),
)
drawDirectionArrow(roof)
})
const removeTargets = canvas.getObjects().filter((obj) => obj.name === 'outerLinePoint' || obj.name === 'outerLine')
removeTargets.forEach((obj) => {
canvas.remove(obj)
})
setEditingLines([])
closeAll()
setMenuNumber(3)
setMenuType('surface')
}
const setLineSize = (id, size) => {
const roofBases = canvas.getObjects().filter((obj) => obj.name === POLYGON_TYPE.ROOF)
roofBases.forEach((roof) => {
roof.innerLines.forEach((line) => {
if (id === line.id) {
setEditingLines([...editingLines.filter((editLine) => editLine.id !== line.id), line])
line.attributes.actualSize = size
line.set({
strokeWidth: 2,
stroke: 'black',
})
}
})
})
canvas?.renderAll()
}
// 지붕재 변경
const handleChangeRoofMaterial = (value, index) => {
const selectedIndex = roofMaterials.findIndex((roof) => roof.selected)
const selectedRoofMaterial = roofMaterials.find((roof) => roof.roofMatlCd === value.id)
const newRoofList = currentRoofList.map((roof, idx) => {
if (idx === index) {
return { ...selectedRoofMaterial }
}
return roof
})
setCurrentRoofList(newRoofList)
}
// 기본 지붕재 radio값 변경
const handleDefaultRoofMaterial = (index) => {
const newRoofList = currentRoofList.map((roof, idx) => {
return { ...roof, selected: idx === index }
})
setCurrentRoofList(newRoofList)
}
// 서까래 변경
const handleChangeRaft = (e, index) => {
const raftValue = e.clCode
const newRoofList = currentRoofList.map((roof, idx) => {
if (idx === index) {
return { ...roof, raft: raftValue }
}
return roof
})
setCurrentRoofList(newRoofList)
}
const handleChangeLayout = (layoutValue, index) => {
const newRoofList = currentRoofList.map((roof, idx) => {
if (idx === index) {
return { ...roof, layout: layoutValue }
}
return roof
})
setCurrentRoofList(newRoofList)
}
const handleChangeInput = (e, type, index) => {
const value = e.target.value
if (type === 'pitch') {
// type이 pitch인 경우 소수점 1자리까지만 입력 가능
const reg = /^[0-9]+(\.[0-9]{0,1})?$/
if (!reg.test(value)) {
e.target.value = value.substring(0, value.length - 1)
const newRoofList = currentRoofList.map((roof, idx) => {
if (idx === index) {
return {
...roof,
[type]: currentAngleType === 'slope' ? value.substring(0, value.length - 1) : getChonByDegree(value.substring(0, value.length - 1)),
}
}
return roof
})
setCurrentRoofList(newRoofList)
return
} else {
const newRoofList = currentRoofList.map((roof, idx) => {
if (idx === index) {
return {
...roof,
[type]: currentAngleType === 'slope' ? value : getChonByDegree(value),
}
}
return roof
})
setCurrentRoofList(newRoofList)
}
return
}
const newRoofList = currentRoofList.map((roof, idx) => {
if (idx === index) {
return { ...roof, [type]: value }
}
return roof
})
setCurrentRoofList(newRoofList)
}
const handleChangePitch = (e, index) => {
const value = e.target.value
const newRoofList = currentRoofList.map((roof, idx) => {
if (idx === index) {
const result =
currentAngleType === 'slope' ? { pitch: value, angle: getDegreeByChon(value) } : { pitch: getChonByDegree(value), angle: value }
return { ...roof, ...result }
}
return roof
})
setCurrentRoofList(newRoofList)
}
return {
handleSave,
onAddRoofMaterial,
onDeleteRoofMaterial,
handleAlloc,
setLineSize,
roofMaterials,
selectedRoofMaterial,
basicSetting,
setBasicSetting,
currentRoofMaterial,
setCurrentRoofMaterial,
handleDefaultRoofMaterial,
handleChangeRoofMaterial,
handleChangeRaft,
handleChangeLayout,
handleSaveContext,
currentRoofList,
handleChangeInput,
handleChangePitch,
}
}