'use client' import React, { useState, useEffect, useRef } from 'react' import { useRouter, useSearchParams } from 'next/navigation' import { Button } from '@nextui-org/react' import Select from 'react-dropdown-select' import Link from 'next/link' import { useAxios } from '@/hooks/useAxios' import { globalLocaleStore } from '@/store/localeAtom' import { isEmptyArray, isObjectNotEmpty } from '@/util/common-utils' import { useMessage } from '@/hooks/useMessage' import { useForm } from 'react-hook-form' import { useRecoilValue } from 'recoil' import { sessionStore } from '@/store/commonAtom' import FindAddressPop from './popup/FindAddressPop' import PlanRequestPop from './popup/PlanRequestPop' export default function StuffDetail() { const sessionState = useRecoilValue(sessionStore) const router = useRouter() const searchParams = useSearchParams() const { getMessage } = useMessage() const globalLocaleState = useRecoilValue(globalLocaleStore) const ref = useRef() const { get, post, del } = useAxios(globalLocaleState) //form const formInitValue = { // 물건번호 T...(임시) R...(진짜) dispCompanyName: '', //담당자 objectStatusId: '0', //물건구분(신축:0 기축 : 1) objectName: '', //물건명 objectNameOmit: '', //경칭선택 objectNameKana: '', //물건명 후리가나 saleStoreLevel: '', //1차점스토어레벨 saleStoreId: '', //1차점판매점ID saleStoreName: '', //1차점판매점명 otherSaleStoreId: '', //1차점 외 판매점ID otherSaleStoreName: '', //1차점 외 판매점명 otherSaleStoreLevel: '', //1차점 외 스토어레벨 zipNo: '', //우편번호 prefId: '', //도도부현 prefName: '', address: '', //주소 areaId: '', //발전량시뮬레이션지역id // areaName: '', //발전량시뮬레이션지역명 windSpeed: '', //기준풍속 verticalSnowCover: '', //수직적설량NEW coldRegionFlg: false, //한랭지대책시행(true : 1 / false : 0) surfaceType: 'III・IV', //면조도구분(III・IV / Ⅱ) saltAreaFlg: false, //염해지역용아이템사용 (true : 1 / false : 0) installHeight: '', //설치높이 conType: '0', //계약조건(잉여 / 전량) remarks: '', //메모 tempFlag: 'T', //임시저장(1) 저장(0) } const { register, setValue, getValues, handleSubmit, resetField, control, watch } = useForm({ defaultValues: formInitValue, }) const form = { register, setValue, getValues, handleSubmit, resetField, control, watch } const [prefCodeList, setPrefCodeList] = useState([]) //도도부현 코트 리스트 const [prefValue, setPrefValue] = useState('') const [saleStoreList, setSaleStoreList] = useState([]) // 판매점 리스트 const [otherSaleStoreList, setOtherSaleStoreList] = useState([]) const [originOtherSaleStoreList, setOriginOtherSaleStoreList] = useState([]) const [areaIdList, setAreaIdList] = useState([]) //발전시뮬레이션 리스트 const [windSpeedList, setWindSpeedList] = useState([]) //기준풍속 리스트 const [isFormValid, setIsFormValid] = useState(false) //임시저장, 진짜저장 버튼 컨트롤 const [showAddressButtonValid, setShowAddressButtonValid] = useState(false) //주소검색팝업 활성화 컨트롤 const [showDesignRequestButtonValid, setShowDesignRequestButtonValid] = useState(false) //설계의뢰팝업 활성화 컨트롤 const objectNo = searchParams.get('objectNo') //url에서 물건번호 꺼내서 바로 set const [editMode, setEditMode] = useState('NEW') const [detailData, setDetailData] = useState({}) const [tempDetailData, setTempDetailData] = useState({}) useEffect(() => { console.log('objectNo::', objectNo) if (objectNo) { console.log('수정화면') setEditMode('EDIT') if (objectNo.substring(0, 1) === 'R') { //진짜 setIsFormValid(true) } get({ url: `/api/object/${objectNo}/detail` }).then((res) => { console.log('물건번호로 상세 API 호출') if (res != null) { setDetailData(res) } }) } else { // 신규 상세 공통APi // 도도부현API console.log('신규화면') get({ url: '/api/object/prefecture/list' }).then((res) => { if (!isEmptyArray(res)) { // console.log('신규화면 도도부현API 결과:::', res) setPrefCodeList(res) } }) // 임시 1차점 판매점코드 saleStoreId=201TES01 // T01 //1차점 : X167 get({ url: `/api/object/saleStore/T01/list` }).then((res) => { // get({ url: `/api/object/saleStore/${sessionState?.storeId}/list` }).then((res) => { if (!isEmptyArray(res)) { const firstList = res.filter((row) => row.saleStoreLevel === '1') const otherList = res.filter((row) => row.saleStoreLevel !== '1') //1차점 셀렉트박스 setSaleStoreList(firstList) //1차점 아닌 판매점 셀렉트박스 setOriginOtherSaleStoreList(otherList) setOtherSaleStoreList(otherList) } }) } }, [objectNo]) useEffect(() => { if (isObjectNotEmpty(detailData)) { console.log('상세데이타:::::::', detailData) // 도도부현API get({ url: '/api/object/prefecture/list' }).then((res) => { if (!isEmptyArray(res)) { // console.log('도도부현API 결과:::', res) setPrefCodeList(res) } }) //상세정보로 1차점 목록등 셋팅?? // 임시 1차점 판매점코드 saleStoreId=201TES01 // T01 //1차점 : X167 // get({ url: `/api/object/saleStore/X167/list` }).then((res) => { // get({ url: `/api/object/saleStore/${sessionState?.storeId}/list` }).then((res) => { // if (!isEmptyArray(res)) { // // console.log('판매점 결과:::::', res) // setSaleStoreList(res) // //1차 판매점 자동완성 값 셋팅 // form.setValue('saleStoreId', res[0].saleStoreId) // //1차 판매점 번호 셋팅 // form.setValue('saleStoreName', res[0].saleStoreId) // setOtherSaleStoreList([]) // } // }) } }, [detailData]) useEffect(() => { if (isObjectNotEmpty(tempDetailData)) { console.log('임시저장하고 새로고침했을때:::::::::', tempDetailData) } }, [tempDetailData]) //1차점 변경 이벤트 const onSelectionChange = (key) => { if (!isEmptyArray(key)) { setOtherSaleStoreList(otherSaleStoreList) form.setValue('saleStoreId', key[0].saleStoreId) form.setValue('saleStoreName', key[0].saleStoreName) form.setValue('saleStoreLevel', key[0].saleStoreLevel) //선택한 1차점 정보로 2차점 list 추리기 //長府工産株式会社 大阪支社 let newOtherSaleStoreList = originOtherSaleStoreList.filter((row) => row.firstAgentId === key[0].saleStoreId) setOtherSaleStoreList(newOtherSaleStoreList) } else { //X누름 form.setValue('saleStoreId', '') form.setValue('saleStoreName', '') form.setValue('saleStoreLevel', '') form.setValue('otherSaleStoreId', '') form.setValue('otherSaleStoreName', '') form.setValue('otherSaleStoreLevel', '') setOtherSaleStoreList(originOtherSaleStoreList) //1차점 지웠을때 2차점 자동완성 초기화 handleClear() } } //2차점 변경 이벤트 const onSelectionChange2 = (key) => { if (!isEmptyArray(key)) { form.setValue('otherSaleStoreId', key[0].saleStoreId) form.setValue('otherSaleStoreName', key[0].saleStoreName) form.setValue('otherSaleStoreLevel', key[0].saleStoreLevel) } else { form.setValue('otherSaleStoreId', '') form.setValue('otherSaleStoreName', '') form.setValue('otherSaleStoreLevel', '') } } //1차점 지웠을때 2차점 자동완성 초기화 const handleClear = () => { if (ref.current.state.dropDown) { ref.current.methods.dropDown() } else { ref.current.state.values = [] } } //팝업에서 넘어온 우편정보 const setZipInfo = (info) => { // console.log('팝업에서 넘어온 데이타::::::::', info) setPrefValue(info.prefId) form.setValue('prefId', info.prefId) form.setValue('prefName', info.address1) form.setValue('address', info.address2 + info.address3) form.setValue('zipNo', info.zipNo) } //임시저장 저장 버튼 컨트롤 // dispCompanyName: '', //담당자 // objectName: '', //물건명 // objectNameOmit: '', //경칭선택 // saleStoreId: '', //판매점ID // zipNo: '', //우편번호 // prefId: '', //도도부현 // address: '', //주소 // areaId: '', //발전량시뮬레이션지역new // windSpeed: '', //기준풍속 // verticalSnowCover: '', //수직적설량 // coldRegionFlg: false, //한랭지대책시행 // surfaceType: 'Ⅲ・Ⅳ', //면조도구분(Ⅲ・Ⅳ / Ⅱ) // saltAreaFlg: false, //염해지역용아이템사용 // installHeight: '', //설치높이 // conType : '0' //계약조건(잉여 / 전량) // remarks: '', //메모 // tempFlag: 'T', //임시저장(1) 저장(0) const _dispCompanyName = watch('dispCompanyName') const _objectName = watch('objectName') const _objectNameOmit = watch('objectNameOmit') const _saleStoreId = watch('saleStoreId') const _saleStoreLevel = watch('saleStoreLevel') const _prefId = watch('prefId') const _address = watch('address') const _areaId = watch('areaId') //new const _windSpeed = watch('windSpeed') const _verticalSnowCover = watch('verticalSnowCover') const _installHeight = watch('installHeight') useEffect(() => { if (editMode === 'NEW') { const formData = form.getValues() // console.log('임시저장폼::::::::::::', formData) let errors = {} if (!formData.dispCompanyName || formData.dispCompanyName.trim().length === 0) { errors.dispCompanyName = true } if (!formData.objectName || formData.objectName.trim().length === 0) { errors.objectName = true } if (!formData.objectNameOmit) { errors.objectNameOmit = true } if (!formData.saleStoreId) { errors.saleStoreId = true } if (!formData.prefId) { errors.prefId = true } if (!formData.areaId) { errors.areaId = true } if (!formData.windSpeed) { errors.windSpeed = true } if (!formData.verticalSnowCover) { errors.verticalSnowCover = true } if (!formData.installHeight) { errors.installHeight = true } // console.log('임시저장용::', errors) setIsFormValid(Object.keys(errors).length === 0) } else { console.log('상세일때 폼체크') } }, [ _dispCompanyName, _objectName, _objectNameOmit, _saleStoreId, _saleStoreLevel, // _otherSaleStoreId, // _otherSaleStoreLevel, _prefId, _address, _areaId, _windSpeed, _verticalSnowCover, _installHeight, ]) // 주소검색 팝업오픈 const onSearchPostNumberPopOpen = () => { setShowAddressButtonValid(true) } //설계의뢰 팝업 오픈 const onSearchDesignRequestPopOpen = () => { setShowDesignRequestButtonValid(true) } useEffect(() => { if (prefValue !== '') { // 발전량시뮬레이션 지역 목록 get({ url: `/api/object/prefecture/${prefValue}/list` }).then((res) => { if (!isEmptyArray(res)) { // console.log('발전량 시뮬레이션::::::::', res) form.setValue('areaId', res[0].areaId) form.setValue('areaName', res[0].prefName) setAreaIdList(res) } }) } }, [prefValue]) // 발전량 시뮬레이션 변경 const handleAreaIdOnChange = (e) => { form.setValue('areaId', e.target.value) } useEffect(() => { if (!isEmptyArray(areaIdList)) { let _prefName = form.watch('prefName') // console.log('기준풍속 가져오는 API', _prefName) get({ url: `/api/object/windSpeed/${_prefName}/list` }).then((res) => { // console.log('res::', res) if (!isEmptyArray(res)) { setWindSpeedList(res) } }) } }, [areaIdList]) //필수값 다 입력했을때 const onValid = (data) => { // 수정모드일때는 PUT // console.log('필수값 다 있고 저장') // console.log('data::::::', data) const formData = form.getValues() // console.log('formData::::', formData) // const _dispCompanyName = watch('dispCompanyName') // const _objectStatusId = watch('objectStatusId') // const _objectNameOmit = watch('objectNameOmit') // const _zipNo = watch('zipNo') // const _prefId = watch('prefId') // const _address = watch('address') // const _coldRegionFlg = watch('coldRegionFlg') // console.log(_dispCompanyName) // console.log(_objectStatusId) // console.log(_objectNameOmit) // console.log(_zipNo) // console.log(_prefId) // console.log('prefValue::', prefValue) // console.log(_address) // console.log('_coldRegionFlg::', _coldRegionFlg) } //필수값 안넣었을때 임시저장 form required사용시 // const onInvalid = (errors) => { // console.log('22222222222222222222222') // const formData = form.getValues() // console.log('임시저장formData::::', formData) // } // 임시저장 const onTempSave = async () => { const formData = form.getValues() // console.log('formData::', formData) const params = { saleStoreId: formData.otherSaleStoreId ? formData.otherSaleStoreId : formData.saleStoreId, saleStoreName: formData.otherSaleStoreName ? formData.otherSaleStoreName : formData.saleStoreName, saleStoreLevel: formData.otherSaleStoreLevel ? formData.otherSaleStoreLevel : formData.saleStoreLevel, objectStatusId: formData.objectStatusId, objectName: formData.objectName, objectNameOmit: formData.objectNameOmit, objectNameKana: formData.objectNameKana, zipNo: formData.zipNo, prefId: formData.prefId, prefName: formData.prefName, address: formData.address, areaId: formData.areaId, receiveUser: formData.dispCompanyName, installHeight: formData.installHeight, windSpeed: formData.windSpeed, verticalSnowCover: formData.verticalSnowCover, surfaceType: formData.surfaceType, conType: formData.conType, coldRegionFlg: formData.coldRegionFlg, saltAreaFlg: formData.saltAreaFlg, tempFlg: '1', workNo: null, workName: null, } //1차점 or 2차점 안고르고 임시저장하면 if (params.saleStoreId == '') { params.saleStoreId = sessionState.storeId params.saleStoreLevel = sessionState.storeLevel } console.log('임시저장params::', params) // return await post({ url: '/api/object/save-object', data: params }).then((res) => { if (res) { console.log('임시저장res::::::', res) setTempDetailData(res) alert('임시저장 되었습니다. 물건번호를 획득하려면 필수 항목을 모두 입력해 주십시오.') } }) } // 물건삭제 const onDelete = () => { //http://localhost:8080/api/object/R201TES01240910023 // console.log('물건번호::::::::', objectNo) alert('사양확정일이 있으면 삭제 불가') if (confirm(getMessage('common.message.data.delete'))) { let testobj = '10' del({ url: `/api/object/${testobj}` }).then((res) => { // console.log('삭제 결과:::', res) router.push('/management/stuff') }) } } return ( <> {(editMode === 'NEW' && (
)) || ( <> {objectNo.substring(0, 1) === 'R' ? ( <> > ) : ( <> {!isFormValid ? ( ) : ( )} > )} > )} {showAddressButtonValid &&