'use client' import { useEffect, useState, useContext } from 'react' import { useRecoilValue } from 'recoil' import { floorPlanObjectState } from '@/store/floorPlanObjectAtom' import { useMessage } from '@/hooks/useMessage' import { useCanvasMenu } from '@/hooks/common/useCanvasMenu' import SingleDatePicker from '../common/datepicker/SingleDatePicker' import EstimateFileUploader from './EstimateFileUploader' import { useAxios } from '@/hooks/useAxios' import { globalLocaleStore } from '@/store/localeAtom' import { isNotEmptyArray, isObjectNotEmpty, queryStringFormatter } from '@/util/common-utils' import dayjs from 'dayjs' import { useCommonCode } from '@/hooks/common/useCommonCode' import { useEstimateController } from '@/hooks/floorPlan/estimate/useEstimateController' import { SessionContext } from '@/app/SessionProvider' import Select, { components } from 'react-select' import { convertNumberToPriceDecimal } from '@/util/common-utils' import ProductFeaturesPop from './popup/ProductFeaturesPop' export default function Estimate({ params }) { const { session } = useContext(SessionContext) const [objectNo, setObjectNo] = useState('') //물건번호 const [planNo, setPlanNo] = useState('') //플랜번호 const [files, setFiles] = useState([]) // 보내는 첨부파일 const [originFiles, setOriginFiles] = useState([]) //기존 첨부파일 const [showContentCode, setShowContentCode] = useState('ATTR001') const [productFeaturesPopupOpen, setProductFeaturesPopupOpen] = useState(false) //견적특이사항 팝업 const [showProductFeatureData, setShowProductFeatureData] = useState([]) //팝업에 보여줄 견적특이사항 데이터 const [selection, setSelection] = useState(new Set()) //견적특이사항 접고 펼치기 const [hidden, setHidden] = useState(false) //아이템 자동완성 리스트 const [displayItemList, setDisplayItemList] = useState([]) //공통코드 const { findCommonCode } = useCommonCode() const [honorificCodeList, setHonorificCodeList] = useState([]) //경칭 공통코드 const [storePriceList, setStorePriceList] = useState([]) //가격표시 option const [tempPriceCd, setTempPriceCd] = useState('') const [startDate, setStartDate] = useState(new Date()) const singleDatePickerProps = { startDate, setStartDate, } const objectRecoil = useRecoilValue(floorPlanObjectState) //견적서 상세데이터 const { state, setState, addItem } = useEstimateController(params.pid) const [itemList, setItemList] = useState([]) //기존 아이템 리스트 //견적특이사항 List const [specialNoteList, setSpecialNoteList] = useState([]) const globalLocaleState = useRecoilValue(globalLocaleStore) const { get, promisePost } = useAxios(globalLocaleState) const { getMessage } = useMessage() const { setMenuNumber } = useCanvasMenu() //새로 추가한 첨부파일 props const fileUploadProps = { uploadFiles: files, setUploadFiles: setFiles, } useEffect(() => { setMenuNumber(5) setObjectNo(objectRecoil.floorPlanObjectNo) setPlanNo(params.pid) // 공통코드 const code1 = findCommonCode(200800) if (code1 != null) { setHonorificCodeList(code1) } //아이템 자동완성 목록 가져오기 const param = { saleStoreId: session.storeId, } const apiUrl = `/api/display-item/item-list?${queryStringFormatter(param)}` get({ url: apiUrl }).then((res) => { if (res.length > 0) { setDisplayItemList(res) } }) }, []) useEffect(() => { //견적특이사항 API호출 //여러개 선택하면 구분자로 (、) let url = `/api/estimate/special-note-list` get({ url: url }).then((res) => { if (isNotEmptyArray(res)) { if (state?.estimateOption) { res.map((row) => { let estimateOption = state?.estimateOption?.split('、') row.text = false estimateOption.map((row2) => { if (row2 === row.code) { row.text = true } }) }) setSpecialNoteList(res) } } }) }, [state?.estimateOption]) //견적일 set useEffect(() => { let estimateDate = dayjs(startDate).format('YYYY-MM-DD') setState({ estimateDate: estimateDate }) }, [startDate]) useEffect(() => { //선택된 견적특이사항 setState if (isNotEmptyArray(specialNoteList)) { const liveCheckedData = specialNoteList.filter((row) => row.text === true) const data = [] for (let ele of liveCheckedData) { data.push(ele.code) } const newData = data.join('、') setState({ estimateOption: newData }) } }, [specialNoteList]) // 견적특이사항 remark 보여주기 const settingShowContent = (code, event) => { setShowContentCode(code) event.stopPropagation() } // 추가한 첨부파일 state에 넣기 useEffect(() => { if (isNotEmptyArray(files)) { files.map((row) => { setState({ fileList: row.data }) }) } else { setState({ fileList: [] }) } }, [files]) //상세에서 내려온 첨부파일 set 만들기 useEffect(() => { if (isNotEmptyArray(state.fileList)) { setOriginFiles(state.fileList) } }, [state?.fileList]) // 기존첨부파일 삭제 const deleteOriginFile = async (objectNo, no) => { const delParams = { userId: session.userId, objectNo: objectNo, no: no, } await promisePost({ url: 'api/file/fileDelete', data: delParams }).then((res) => { if (res.status === 204) { setOriginFiles(originFiles.filter((file) => file.objectNo === objectNo && file.no !== no)) setState({ fileList: originFiles.filter((file) => file.objectNo === objectNo && file.no !== no), }) } }) } //아이템 목록 useEffect(() => { if (isNotEmptyArray(state.itemList)) { setItemList(state.itemList) } }, [state?.itemList]) //가격표시 option 최초세팅 useEffect(() => { if (state.estimateType !== '') { const param = { saleStoreId: session.storeId, sapSalesStoreCd: session.custCd, docTpCd: state?.estimateType, } const apiUrl = `/api/estimate/price/store-price-list?${queryStringFormatter(param)}` get({ url: apiUrl }).then((res) => { if (isNotEmptyArray(res?.data)) { setStorePriceList(res.data) } }) } }, [state?.estimateType]) // useEffect(() => { // if (state.priceCd) { // setTempPriceCd(state.priceCd) // } // }, [state?.priceCd]) //가격표시 option 변경시 useEffect(() => { if (tempPriceCd !== '') { const param = { saleStoreId: session.storeId, sapSalesStoreCd: session.custCd, docTpCd: tempPriceCd, } const apiUrl = `/api/estimate/price/store-price-list?${queryStringFormatter(param)}` get({ url: apiUrl }).then((res) => { if (isNotEmptyArray(res?.data)) { setStorePriceList(res.data) } }) } }, [tempPriceCd]) //Pricing 버튼 const handlePricing = async (priceCd) => { const param = { saleStoreId: session.storeId, sapSalesStoreCd: session.custCd, docTpCd: state.estimateType, priceCd: session.storeLvl === '1' ? tempPriceCd : priceCd, itemIdList: state.itemList, //아이템 최초정보로 호출 } // console.log('프라이싱파람::', param) await promisePost({ url: '/api/estimate/price/item-price-list', data: param }).then((res) => { if (res) { if (res.status === 200) { const data = res.data if (data.result.code === 200) { if (isNotEmptyArray(data.data2)) { //아이템쪽 다 새로고침............ //성공후.. //기존itemList랑 프라이싱결과랑 비교해서 단가만 업뎃 서로 갯수가 안맞을 수 있음 없는 itemId면 unitPrice 0으로 //itemId로 비교해서 단가정보만 업데이트 setState({ priceCd: session.storeLvl === '1' ? tempPriceCd : priceCd, }) } } } } }) } //row 체크박스 컨트롤 const onChangeSelect = (dispOrder) => { const newSelection = new Set(selection) if (newSelection.has(dispOrder)) { newSelection.delete(dispOrder) } else { newSelection.add(dispOrder) } setSelection(newSelection) } // 아이템 자동완성 검색시 const onChangeDisplayItem = (itemId, dispOrder) => { console.log('아이템 자동완성:::::::', dispOrder) const param = { itemId: itemId, } const apiUrl = `/api/display-item/item-detail?${queryStringFormatter(param)}` get({ url: apiUrl }).then((res) => { console.log('제품상세 결과::::::::', res) }) // setState({ // itemList: [{ itemNo: '123123123123' }], // }) } //제품 삭제 const removeItem = () => { const array = [...selection] console.log(array) } return (
{/* 물건번호, 견적서번호, 등록일, 변경일시 시작 */}
{getMessage('estimate.detail.objectNo')}
{objectNo} (Plan No: {planNo})
{getMessage('estimate.detail.docNo')}
{state.docNo}
{getMessage('estimate.detail.drawingEstimateCreateDate')}
{state?.drawingEstimateCreateDate ? `${dayjs(state.drawingEstimateCreateDate).format('YYYY.MM.DD')}` : ''}
{getMessage('estimate.detail.lastEditDatetime')}
{state?.lastEditDatetime ? `${dayjs(state.lastEditDatetime).format('YYYY.MM.DD HH:mm')}` : ''}
{/* 물건번호, 견적서번호, 등록일, 변경일시 끝 */} {/* 기본정보 시작 */}

{getMessage('estimate.detail.header.title')}

{/* 1차 판매점명 */} {/* 견적일 */} {/* 2차 판매점명 */} {/* 담당자 */} {/* 안건명 */} {/* 물건정보에서 입력한 메모 */} {/* 주문분류 */} {/* 지붕재・사양시공 최대4개*/} {/* 비고 */}
{getMessage('estimate.detail.saleStoreId')} {state?.firstSaleStoreName} {getMessage('estimate.detail.estimateDate')} *
{getMessage('estimate.detail.otherSaleStoreId')} {state?.agencySaleStoreName} {getMessage('estimate.detail.receiveUser')} *
{ //담당자 charger setState({ charger: e.target.value }) }} />
{getMessage('estimate.detail.objectName')} *
{ //안건명 objectName setState({ objectName: e.target.value }) }} />
{getMessage('estimate.detail.objectRemarks')} {state?.objectRemarks}
{getMessage('estimate.detail.estimateType')} *
{ //주문분류 setState({ estimateType: e.target.value }) }} />
{ setState({ estimateType: e.target.value }) }} />
{getMessage('estimate.detail.roofCns')} {state?.roofMaterialIdMulti?.split('、').map((row, index) => { //지붕재 let roofList = row let roofListLength = state?.roofMaterialIdMulti?.split('、').length let style = 'mb5' if (roofListLength == index + 1) { style = '' } //사양시공 let constructSpecificationMulti = state?.constructSpecificationMulti?.split('、') return ( <>
) })}
{getMessage('estimate.detail.remarks')}
{ //비고 setState({ remarks: e.target.value }) }} />
{/* 파일첨부 시작 */}

{getMessage('estimate.detail.header.fileList1')}

{ setState({ fileFlg: e.target.checked ? '1' : '0', }) }} />
{getMessage('estimate.detail.header.fileList1')}
{/* 첨부파일 목록 시작 */}
{getMessage('estimate.detail.header.fileList2')}
    {originFiles.length > 0 && originFiles.map((originFile) => { return (
  • {originFile.faileName}
  • ) })}
{/* 첨부파일 목록 끝 */} {/* 파일첨부 끝 */} {/* 견적특이사항 시작 */}

{getMessage('estimate.detail.header.specialEstimate')}

{getMessage('estimate.detail.header.specialEstimateProductInfo')}
{/* 견적 특이사항 코드영역시작 */}
{/* SpecialNoteList반복문 */} {specialNoteList.length > 0 && specialNoteList.map((row) => { return (
{ settingShowContent(row.code, event) }} >
{ setSpecialNoteList((specialNote) => specialNote.map((temp) => (temp.code === row.code ? { ...temp, text: !temp.text } : temp)), ) settingShowContent(row.code, event) }} />
) })}
{/* 견적특이사항 선택한 내용 영역시작 */}
{specialNoteList.map((row) => { if (row.code === showContentCode) { return (
{row.codeNm}
) } })}
{/* 견적특이사항 선택한 내용 영역끝 */}
{/* 견적 특이사항 코드영역 끝 */} {/* 견적특이사항 영역끝 */} {/* 제품정보 시작 */}

{getMessage('estimate.detail.header.specialEstimateProductInfo')}

{getMessage('estimate.detail.sepcialEstimateProductInfo.totPcs')}
74
{getMessage('estimate.detail.sepcialEstimateProductInfo.vol')}
8300
{getMessage('estimate.detail.sepcialEstimateProductInfo.netAmt')}
6,798,900
{getMessage('estimate.detail.sepcialEstimateProductInfo.vat')}
679,890
{getMessage('estimate.detail.sepcialEstimateProductInfo.totPrice')}
7,478,790
{/* YJOD면 아래영역 숨김 */}
{getMessage('estimate.detail.sepcialEstimateProductInfo.pkgUnitPrice')} *
{getMessage('estimate.detail.sepcialEstimateProductInfo.pkgWeight')} {getMessage('estimate.detail.sepcialEstimateProductInfo.calcFormula1')} {getMessage('estimate.detail.sepcialEstimateProductInfo.pkgPrice')} {getMessage('estimate.detail.sepcialEstimateProductInfo.calcFormula2')}
{/* 제품정보 끝 */} {/* 가격표시영역시작 */}
{getMessage('estimate.detail.header.showPrice')}
{session?.storeLvl === '1' ? ( ) : ( )}
  • {getMessage('estimate.detail.showPrice.description1')}
  • {getMessage('estimate.detail.showPrice.description2')}
  • {getMessage('estimate.detail.showPrice.description3')}
  • {getMessage('estimate.detail.showPrice.description4')}
{/* 가격표시영역끝 */} {/* html테이블시작 */}
{state?.itemList.length > 0 && state.itemList.map((item, index) => { return ( ) })}
{getMessage('estimate.detail.itemTableHeader.dispOrder')} {getMessage('estimate.detail.itemTableHeader.itemId')} {getMessage('estimate.detail.itemTableHeader.itemNo')} {getMessage('estimate.detail.itemTableHeader.amount')} {getMessage('estimate.detail.itemTableHeader.unit')} {getMessage('estimate.detail.itemTableHeader.salePrice')} {getMessage('estimate.detail.itemTableHeader.saleTotPrice')}
onChangeSelect(item.dispOrder)} />
{item?.dispOrder * 100}
{item?.itemNo}
{item?.fileUploadFlg === '1' && } {item?.specialNoteCd && ( )}
{item.unit}
{/*
OPEN아이콘 처리
*/}
{convertNumberToPriceDecimal(item?.saleTotPrice)}
{/* html테이블끝 */}
{/* 기본정보끝 */}
{productFeaturesPopupOpen && ( )}
) }