import { SurveyDetailRequest } from '@/types/Survey' import { useEffect, useState } from 'react' export const supplementary_facilities = [ { id: 1, name: 'エコキュート' }, //에코큐트 { id: 2, name: 'エネパーム' }, //에네팜 { id: 3, name: '蓄電池システム' }, //축전지시스템 { id: 4, name: '太陽光発電' }, //태양광발전 ] export const roof_material = [ { id: 1, name: 'スレート' }, //슬레이트 { id: 2, name: 'アスファルトシングル' }, //아스팔트 싱글 { id: 3, name: '瓦' }, //기와 { id: 4, name: '金属屋根' }, //금속지붕 ] export default function MultiCheckbox({ column, setDetailInfoData, detailInfoData, }: { column: string setDetailInfoData: (data: any) => void detailInfoData: SurveyDetailRequest }) { const selectList = column === 'supplementary_facilities' ? supplementary_facilities : roof_material const [isOtherChecked, setIsOtherChecked] = useState(false) const [otherValue, setOtherValue] = useState('') const makeNumArr = (value: string) => { return value .split(',') .map((v) => v.trim()) .filter((v) => v.length > 0) } useEffect(() => { if (detailInfoData[`${column}_etc` as keyof SurveyDetailRequest]) { setIsOtherChecked(true) setOtherValue(detailInfoData[`${column}_etc` as keyof SurveyDetailRequest] as string) } }, [detailInfoData]) const handleCheckbox = (dataIndex: number) => { const value = makeNumArr(String(detailInfoData[column as keyof SurveyDetailRequest] ?? '')) let newValue: string[] if (value.includes(String(dataIndex))) { // 체크 해제 newValue = value.filter((v) => v !== String(dataIndex)) } else { // 체크 if (column === 'roof_material') { // 기타가 체크되어 있는지 확인 const isOtherSelected = isOtherChecked // 현재 선택된 항목 수 + 기타 선택 여부 const totalSelected = value.length + (isOtherSelected ? 1 : 0) if (totalSelected >= 2) { alert('屋根材は最大2個まで選択可能です。') return } } newValue = [...value, String(dataIndex)] } setDetailInfoData({ ...detailInfoData, [column]: newValue.join(', '), }) } const handleOtherCheckbox = () => { if (column === 'roof_material') { const value = makeNumArr(String(detailInfoData[column as keyof SurveyDetailRequest] ?? '')) // 현재 선택된 항목 수 const currentSelected = value.length if (!isOtherChecked && currentSelected >= 2) { alert('Up to two roofing materials can be selected.') return } } setIsOtherChecked(!isOtherChecked) if (!isOtherChecked) { setOtherValue('') setDetailInfoData({ ...detailInfoData, [`${column}_etc`]: null, }) } else { setOtherValue('') } } const handleOtherInputChange = (e: React.ChangeEvent) => { const value = e.target.value setOtherValue(value) setDetailInfoData({ ...detailInfoData, [`${column}_etc`]: value, }) } return ( <> {column === 'supplementary_facilities' ? ( <>
電気袋設備※複数選択可能
) : ( <>
屋根材※最大2個まで選択可能
)}
{selectList.map((item) => (
handleCheckbox(item.id)} />
))}
) }