'use client'

import { useState, useEffect, useRef, useContext } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Button } from '@nextui-org/react'
import Select, { components } from 'react-select'
import { useAxios } from '@/hooks/useAxios'
import { globalLocaleStore } from '@/store/localeAtom'
import { isEmptyArray, isNotEmptyArray, isObjectNotEmpty, queryStringFormatter } from '@/util/common-utils'
import { useMessage } from '@/hooks/useMessage'
import { useForm } from 'react-hook-form'
import { useRecoilValue, useSetRecoilState, useRecoilState } from 'recoil'
import { SessionContext } from '@/app/SessionProvider'
import FindAddressPop from './popup/FindAddressPop'
import PlanRequestPop from './popup/PlanRequestPop'
import WindSelectPop from './popup/WindSelectPop'
import { useCommonCode } from '@/hooks/common/useCommonCode'
import StuffPlanQGrid from './StuffPlanQGrid'
import { floorPlanObjectState } from '@/store/floorPlanObjectAtom'
import { GlobalDataContext } from '@/app/GlobalDataProvider'
import DocDownOptionPop from '../estimate/popup/DocDownOptionPop'
import { stuffSearchState } from '@/store/stuffAtom'
import { QcastContext } from '@/app/QcastProvider'
import { useCanvasMenu } from '@/hooks/common/useCanvasMenu'
import { useSwal } from '@/hooks/useSwal'

export default function StuffDetail() {
  const [stuffSearch, setStuffSearch] = useRecoilState(stuffSearchState)
  const { swalFire } = useSwal()
  const { setIsGlobalLoading } = useContext(QcastContext)
  const stuffSearchParams = useRecoilValue(stuffSearchState)

  const setFloorPlanObjectNo = useSetRecoilState(floorPlanObjectState) //견적서 화면용 물건번호리코일

  const [estimatePopupOpen, setEstimatePopupOpen] = useState(false)

  const [popPlanNo, setPopPlanNo] = useState('1') //default 1

  const [showButton, setShowButton] = useState('') //임시저장, 저장, 삭제 버튼 컨트롤

  const { setMenuNumber } = useCanvasMenu()

  //공통코드
  const { commonCode, findCommonCode } = useCommonCode()
  const [selOptions, setSelOptions] = useState('') //선택한 1차점
  const [otherSelOptions, setOtherSelOptions] = useState('') //선택한 1차점외

  const { session } = useContext(SessionContext)

  const router = useRouter()
  const searchParams = useSearchParams()
  const { getMessage } = useMessage()
  const globalLocaleState = useRecoilValue(globalLocaleStore)
  const ref = useRef()
  const { get, promiseGet, del, promisePost, promisePut } = useAxios(globalLocaleState)
  //form
  const formInitValue = {
    // 물건번호 T...(임시) R...(진짜)
    planReqNo: '', //설계의뢰No
    receiveUser: session?.userNm, //담당자 로그인사용자명 디폴트
    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
    standardWindSpeedId: '', //기준풍속
    verticalSnowCover: '', //수직적설량
    coldRegionFlg: false, //한랭지대책시행(true : 1 / false : 0)
    surfaceType: 'Ⅲ・Ⅳ', //면조도구분(Ⅲ・Ⅳ / Ⅱ)
    saltAreaFlg: false, //염해지역용아이템사용 (true : 1 / false : 0)
    installHeight: '', //설치높이
    conType: '0', //계약조건(잉여 / 전량)
    remarks: '', //메모
    tempFlg: 'T', //임시저장(1) 저장(0)
  }
  const { register, setValue, getValues, handleSubmit, resetField, control, watch } = useForm({
    defaultValues: formInitValue,
  })

  const form = { register, setValue, getValues, handleSubmit, resetField, control, watch }

  const [honorificCodeList, setHonorificCodeList] = useState([]) //경칭 공통코드 리스트
  const [selHonorificCode, setSelHonorificCode] = useState('') //선택한 경칭코드
  const [objectStatusList, setObjectStatusList] = useState([]) //물건구분 공통코드 리스트

  const [selectObjectStatusId, setSelectObjectStatusId] = useState('0') //신축기축 선택값
  const [windSpeedList, setWindSpeedList] = useState([]) //기준 풍속 공통코드 리스트
  const [prefCodeList, setPrefCodeList] = useState([]) //도도부현 코트 리스트
  const [prefValue, setPrefValue] = useState('')
  const [saleStoreList, setSaleStoreList] = useState([]) // 판매점 리스트
  const [favoriteStoreList, setFavoriteStoreList] = useState([]) //즐겨찾기한 판매점목록
  const [showSaleStoreList, setShowSaleStoreList] = useState([]) //보여줄 판매점목록

  const [otherSaleStoreList, setOtherSaleStoreList] = useState([])
  const [originOtherSaleStoreList, setOriginOtherSaleStoreList] = useState([])

  const [areaIdList, setAreaIdList] = useState([]) //발전시뮬레이션 리스트

  const [isFormValid, setIsFormValid] = useState(false) //임시저장, 진짜저장 버튼 컨트롤
  const [showAddressButtonValid, setShowAddressButtonValid] = useState(false) //주소검색팝업 활성화 컨트롤
  const [showDesignRequestButtonValid, setShowDesignRequestButtonValid] = useState(false) //설계의뢰팝업 활성화 컨트롤
  const [showWindSpeedButtonValid, setShowWindSpeedButtonValid] = useState(false) //풍속선택팝업 활성화 컨트롤
  const objectNo = searchParams.get('objectNo') //url에서 물건번호 꺼내서 바로 set

  const [editMode, setEditMode] = useState('NEW')
  const { managementState, setManagementState } = useContext(GlobalDataContext)
  const [planGridProps, setPlanGridProps] = useState({
    planGridData: [],
    isPageable: false,
    planGridColumns: [
      {
        field: 'planNo',
        headerName: getMessage('stuff.detail.planGridHeader.planNo'),
        width: 100,
        cellStyle: { alignItems: 'center', cursor: 'pointer' },
      },
      {
        field: 'orderFlg',
        headerName: getMessage('stuff.detail.planGridHeader.orderFlg'),
        width: 80,
        cellStyle: { alignItems: 'center', cursor: 'pointer' },
        cellRenderer: (params) => {
          //1일때만 동그라미
          let orderFlg
          orderFlg = params.value === '1' ? 'O' : 'X'
          return orderFlg
        },
      },
      {
        field: 'moduleModel',
        headerName: getMessage('stuff.detail.planGridHeader.moduleModel'),
        flex: 1,
        wrapText: true,
        cellStyle: { alignItems: 'flex-start' /* 좌측정렬*/, cursor: 'pointer' },
        cellRenderer: (params) => {
          let origin = params.value
          if (origin !== null) {
            return (
              <>
                {origin?.split('、').map((it, idx) => (
                  <span key={idx} className="block">
                    {it}
                    <br />
                  </span>
                ))}
              </>
            )
          } else {
            return null
          }
        },
      },
      {
        field: 'capacity',
        headerName: getMessage('stuff.detail.planGridHeader.capacity'),
        width: 120,
        cellStyle: { alignItems: 'flex-end' /* 우측정렬*/, cursor: 'pointer' },
        cellRenderer: (params) => {
          let origin = params.value
          let capacity
          if (origin) {
            capacity = origin / 1000
            //#400 소수점 2자리까지만 변경
            return capacity.toFixed(2) + 'kW'
          } else {
            return null
          }
        },
      },
      {
        field: 'roofMaterialIdMulti',
        headerName: getMessage('stuff.detail.planGridHeader.roofMaterialIdMulti'),
        width: 140,
        wrapText: true,
        autoHeight: true,
        cellStyle: { alignItems: 'flex-start' /* 좌측정렬*/, cursor: 'pointer' },
        cellRenderer: (params) => {
          let origin = params.value
          if (origin !== null) {
            return (
              <>
                {origin?.split('、').map((it, idx) => (
                  <span key={idx} className="block">
                    {it}
                    <br />
                  </span>
                ))}
              </>
            )
          } else {
            return null
          }
        },
      },
      {
        field: 'constructSpecificationMulti',
        headerName: getMessage('stuff.detail.planGridHeader.constructSpecificationMulti'),
        wrapText: true,
        autoHeight: true,
        cellStyle: { alignItems: 'flex-start' /* 좌측정렬*/, cursor: 'pointer' },
        cellRenderer: (params) => {
          let origin = params.value
          if (origin !== null) {
            return (
              <>
                {origin?.split('、').map((it, idx) => (
                  <span key={idx} className="block">
                    {it}
                    <br />
                  </span>
                ))}
              </>
            )
          } else {
            return null
          }
        },
      },
      {
        field: 'supportMethodIdMulti',
        headerName: getMessage('stuff.detail.planGridHeader.supportMethodIdMulti'),
        wrapText: true,
        autoHeight: true,
        cellStyle: { alignItems: 'flex-start' /* 좌측정렬*/, cursor: 'pointer' },
        cellRenderer: (params) => {
          let origin = params.value
          if (origin !== null) {
            return (
              <>
                {origin?.split('、').map((it, idx) => (
                  <span key={idx} className="block">
                    {it}
                    <br />
                  </span>
                ))}
              </>
            )
          } else {
            return null
          }
        },
      },
      {
        field: 'pcTypeNo',
        headerName: getMessage('stuff.detail.planGridHeader.pcTypeNo'),
        flex: 1,
        wrapText: true,
        autoHeight: true,
        cellStyle: { alignItems: 'flex-start' /* 좌측정렬*/, cursor: 'pointer' },
        cellRenderer: (params) => {
          let origin = params.value
          if (origin !== null) {
            return (
              <>
                {origin?.split('、').map((it, idx) => (
                  <span key={idx} className="block">
                    {it}
                    <br />
                  </span>
                ))}
              </>
            )
          } else {
            return null
          }
        },
      },
      {
        field: 'estimateDate',
        headerName: getMessage('stuff.detail.planGridHeader.management'),
        width: 200,
        autoHeight: true,
        cellStyle: { justifyContent: 'center' },
        cellRenderer: (params) => {
          let buttonStyle = { display: 'flex' }
          let buttonStyle2 = { display: 'flex' }
          if (params.value == null) {
            buttonStyle = {
              display: 'none',
            }
            buttonStyle2 = {
              display: 'none',
            }
          } else {
            if (params?.data?.createSaleStoreId === 'T01') {
              if (session?.storeId !== 'T01') {
                buttonStyle = { display: 'none' }
              }
            }
          }
          return (
            <>
              <div className="grid-cell-btn">
                <button
                  style={buttonStyle}
                  type="button"
                  className="grid-btn"
                  onClick={() => {
                    setFloorPlanObjectNo({ floorPlanObjectNo: params.data.objectNo })
                    setIsGlobalLoading(true)
                    setMenuNumber(5)
                    router.push(`/floor-plan/estimate/5?pid=${params.data.planNo}&objectNo=${params.data.objectNo}`)
                  }}
                >
                  <span className="file"></span>
                  {getMessage('stuff.detail.planGrid.btn1')}
                </button>
                <button
                  style={buttonStyle2}
                  type="button"
                  className="grid-btn"
                  onClick={() => {
                    setFloorPlanObjectNo({ floorPlanObjectNo: params.data.objectNo })
                    handleEstimatePopup(params.data.planNo)
                  }}
                >
                  <span className="excel"></span>
                  {getMessage('stuff.detail.planGrid.docDownload')}
                </button>
              </div>
            </>
          )
        },
      },
    ],
  })

  // 문서다운로드 팝업 오픈 셋팅
  const handleEstimatePopup = (planNo) => {
    setPopPlanNo(planNo)
    setEstimatePopupOpen(true)
  }

  useEffect(() => {
    if (objectNo) {
      setManagementState({})
      setEditMode('EDIT')
      if (objectNo.substring(0, 1) !== 'T') {
        //벨리데이션 체크용..
        setIsFormValid(true)
      }
      promiseGet({ url: `/api/object/${objectNo}/detail` }).then((res) => {
        if (res.status === 200) {
          if (res?.data?.createSaleStoreId === 'T01') {
            if (session?.storeId !== 'T01') {
              setShowButton('none')
            }
          }
          if (isObjectNotEmpty(res.data)) {
            let surfaceTypeValue
            if (res.data.surfaceType === 'Ⅲ・Ⅳ') {
              surfaceTypeValue = '3'
            } else if (res.data.surfaceType === 'Ⅱ') {
              surfaceTypeValue = '2'
            }
            setManagementState({ ...res.data, surfaceTypeValue: surfaceTypeValue })
          } else {
            setIsGlobalLoading(false)
            setManagementState({})
            swalFire({
              text: getMessage('stuff.detail.header.notExistObjectNo'),
              type: 'alert',
              confirmFn: () => {
                router.push('/management/stuff', { scroll: false })
              },
            })
          }
          if (isNotEmptyArray(res.data.planList)) {
            setPlanGridProps({ ...planGridProps, planGridData: res.data.planList })
          } else {
            setPlanGridProps({ ...planGridProps, planGridData: [] })
          }
        } else {
          setIsGlobalLoading(false)
          setManagementState({})
          setPlanGridProps({ ...planGridProps, planGridData: [] })
          swalFire({
            text: getMessage('stuff.detail.header.notExistObjectNo'),
            type: 'alert',
            confirmFn: () => {
              router.push('/management/stuff', { scroll: false })
            },
          })
        }
      })
    } else {
      // 신규 상세 공통APi
      // 도도부현API
      get({ url: '/api/object/prefecture/list' }).then((res) => {
        if (!isEmptyArray(res)) {
          setPrefCodeList(res)
        }
      })

      //1차점 : X167 T01
      //2차점 : 10X22, 201X112
      let url
      let firstList
      let otherList
      let favList
      if (session?.storeId === 'T01') {
        url = `/api/object/saleStore/${session?.storeId}/firstList?userId=${session?.userId}`
      } else {
        url = `/api/object/saleStore/${session?.storeId}/list?firstFlg=1&userId=${session?.userId}`
      }

      get({ url: url }).then((res) => {
        if (!isEmptyArray(res)) {
          res.map((row) => {
            row.value = row.saleStoreId
            row.label = row.saleStoreName
          })
          if (session?.storeId === 'T01') {
            firstList = res
            firstList.sort((a, b) => (a.saleStoreId !== 'T01') - (b.saleStoreId !== 'T01') || a.saleStoreId - b.saleStoreId)
            favList = firstList.filter((row) => row.saleStoreId === 'T01' || row.priority !== 'B')

            setSaleStoreList(firstList)
            setFavoriteStoreList(favList)
            setShowSaleStoreList(favList)
            setSelOptions(session?.storeId)
            form.setValue('saleStoreId', session?.storeId)
            form.setValue('saleStoreLevel', session?.storeLvl)
            //T01일떄는 1차점을 고른다음 2차점 목록 조회하기
            //디폴트 값(T01)으로 2차점목록 조회하기
            url = `/api/object/saleStore/${session?.storeId}/list?firstFlg=0&userId=${session?.userId}`
            get({ url: url }).then((res) => {
              if (!isEmptyArray(res)) {
                res.map((row) => {
                  row.value = row.saleStoreId
                  row.label = row.saleStoreName
                })

                otherList = res
                setOtherSaleStoreList(otherList)
              } else {
                setOtherSaleStoreList([])
              }
            })
          } else {
            if (session?.storeLvl === '1') {
              firstList = res
              favList = res.filter((row) => row.priority !== 'B')
              otherList = res.filter((row) => row.firstAgentYn === 'N')
              setSaleStoreList(firstList)
              setFavoriteStoreList(firstList)
              setShowSaleStoreList(firstList)
              setSelOptions(firstList[0].saleStoreId)
              form.setValue('saleStoreId', session?.storeId)
              form.setValue('saleStoreLevel', session?.storeLvl)

              setOtherSaleStoreList(otherList)
            } else {
              firstList = res.filter((row) => row.firstAgentYn === 'Y')
              setSaleStoreList(firstList)
              setFavoriteStoreList(firstList)
              setShowSaleStoreList(firstList)
              setSelOptions(firstList[0].saleStoreId)

              form.setValue('saleStoreId', firstList[0].saleStoreId)
              form.setValue('saleStoreLevel', firstList[0].saleStoreLevel)

              otherList = res.filter((row) => row.firstAgentYn === 'N')

              setOtherSaleStoreList(otherList)
              //2차 판매점명/ID는  본인을 셀렉트
              setOtherSelOptions(session?.storeId)
              form.setValue('otherSaleStoreId', session?.storeId)
              form.setValue('otherSaleStoreLevel', session?.storeLvl)
            }
          }
        }
      })

      setIsGlobalLoading(false)
    }
  }, [objectNo, session])

  useEffect(() => {
    const code1 = findCommonCode(200800) //경칭
    const code2 = findCommonCode(201700) //신축/기축
    const code3 = findCommonCode(202000) //기준풍속 202000
    if (code1 != null) {
      setHonorificCodeList(code1)
    }
    if (code2 != null) {
      setObjectStatusList(code2)
    }
    if (code3 != null) {
      setWindSpeedList(code3)
    }
  }, [commonCode])

  useEffect(() => {
    if (objectNo) {
      if (isObjectNotEmpty(managementState)) {
        // 도도부현API
        get({ url: '/api/object/prefecture/list' }).then((res) => {
          if (!isEmptyArray(res)) {
            setPrefCodeList(res)
          }
        })

        let url
        let firstList
        let otherList
        let favList

        if (session?.storeId === 'T01') {
          url = `/api/object/saleStore/${session?.storeId}/firstList?userId=${session?.userId}`
        } else {
          url = `/api/object/saleStore/${session?.storeId}/list?firstFlg=1&userId=${session?.userId}`
        }
        get({ url: url }).then((res) => {
          if (!isEmptyArray(res)) {
            if (session?.storeId === 'T01') {
              //즐겨찾기 구분 추가
              res.map((row) => {
                row.value = row.saleStoreId
                row.label = row.saleStoreName
              })
              firstList = res.filter((row) => row.saleStoreLevel === '1')
              firstList.sort((a, b) => (a.saleStoreId !== 'T01') - (b.saleStoreId !== 'T01') || a.saleStoreId - b.saleStoreId)
              favList = firstList.filter((row) => row.saleStoreId === 'T01' || row.priority !== 'B')
              setSaleStoreList(firstList)
              setFavoriteStoreList(favList)
              setShowSaleStoreList(favList)

              if (managementState.firstAgentId != null) {
                form.setValue('saleStoreId', managementState.firstAgentId)
                setSelOptions(managementState.firstAgentId)
              } else {
                form.setValue('saleStoreId', managementState.saleStoreId)
                setSelOptions(managementState.saleStoreId)
              }

              //상세데이터의 1차점 아이디로 2차점 목록 조회하기

              let data = managementState?.firstAgentId ? managementState.firstAgentId : managementState.saleStoreId
              url = `/api/object/saleStore/${data}/list?firstFlg=0&userId=${session?.userId}`

              get({ url: url }).then((res) => {
                if (!isEmptyArray(res)) {
                  res.map((row) => {
                    row.value = row.saleStoreId
                    row.label = row.saleStoreName
                  })

                  otherList = res
                  setOriginOtherSaleStoreList(otherList)
                  setOtherSaleStoreList(otherList)
                }
              })
            } else {
              //1차점 셀렉트박스
              if (session?.storeLvl === '1') {
                firstList = res
                favList = res.filter((row) => row.priority !== 'B')
                otherList = res.filter((row) => row.firstAgentYn === 'N')
                setSaleStoreList(firstList)
                setFavoriteStoreList(firstList)
                setShowSaleStoreList(firstList)

                setOtherSaleStoreList(otherList)
              } else {
                setSelOptions(res[0].saleStoreId)
                form.setValue('saleStoreId', res[0].saleStoreId)
                form.setValue('saleStoreLevel', res[0].storeLvl)
                setSaleStoreList(res)
                setFavoriteStoreList(res)
                setShowSaleStoreList(res)
                otherList = res.filter((row) => row.firstAgentYn === 'N')
                setOtherSaleStoreList(otherList)
              }
            }
          }

          //상세데이터가 1차점이면 1차점에 세팅
          //상세데이터가 2차점이면 2차점에 세팅하고 세션으로 1차점 세팅
          if (managementState.saleStoreLevel === '1') {
            setSelOptions(managementState.saleStoreId)
            form.setValue('saleStoreId', managementState.saleStoreId)
            form.setValue('saleStoreLevel', managementState.saleStoreLevel)
            //#435
            setOtherSelOptions('')
            form.setValue('otherSaleStoreId', '')
            form.setValue('otherSaleStoreLevel', '')
            form.setValue('otherSaleStoreName', '')
          } else {
            setOtherSelOptions(managementState.saleStoreId)
            form.setValue('otherSaleStoreId', managementState.saleStoreId)
            form.setValue('otherSaleStoreLevel', managementState.saleStoreLevel)

            form.setValue('saleStoreLevel', '1')

            form.setValue('saleStoreId', managementState.firstAgentId)
            setSelOptions(managementState.firstAgentId)
          }

          //설계의뢰No.
          form.setValue('planReqNo', managementState.planReqNo)
          //담당자
          form.setValue('receiveUser', managementState.receiveUser)

          //물건구분objectStatusId
          setSelectObjectStatusId(managementState.objectStatusId)
          form.setValue('objectStatusId', managementState.objectStatusId)

          //물건명
          form.setValue('objectName', managementState.objectName)

          //경칭코드
          setSelHonorificCode(managementState.objectNameOmit)
          form.setValue('objectNameOmit', managementState.objectNameOmit)

          //물건명 후리가나
          form.setValue('objectNameKana', managementState.objectNameKana)

          //우편번호
          form.setValue('zipNo', managementState.zipNo)

          //도도부현 / 주소
          setPrefValue(managementState.prefId)
          form.setValue('prefId', managementState.prefId)
          form.setValue('prefName', managementState.prefName)
          form.setValue('address', managementState.address)
          //발전시뮬
          form.setValue('areaId', managementState.areaId)

          //기준풍속
          form.setValue('standardWindSpeedId', managementState.standardWindSpeedId)
          //수직적설량
          form.setValue('verticalSnowCover', managementState.verticalSnowCover)
          //한랭지대책시행 coldRegionFlg 1이면 true
          form.setValue('coldRegionFlg', managementState.coldRegionFlg === '1' ? true : false)

          //면조도구분 surfaceType null로 내려오면 셋팅 안하고 저장할때 필수값 체크하도록
          // form.setValue('surfaceType', 'Ⅱ')
          // form.setValue('surfaceType', 'Ⅲ・Ⅳ')
          form.setValue('surfaceType', managementState.surfaceType)
          //염해지역용아이템사용 saltAreaFlg 1이면 true
          form.setValue('saltAreaFlg', managementState.saltAreaFlg === '1' ? true : false)
          //설치높이
          let installHeight = managementState.installHeight ? managementState.installHeight.split('.')[0] : ''
          form.setValue('installHeight', installHeight)
          //계약조건 null로 내려오면 0으로 디폴트셋팅
          if (managementState.conType === null) {
            form.setValue('conType', '0')
          } else {
            form.setValue('conType', managementState.conType)
          }
          //메모
          form.setValue('remarks', managementState.remarks)
        })

        //상세끝
        setIsGlobalLoading(false)
      }
    }
  }, [managementState])

  //경칭선택 변경 이벤트
  const onChangeHonorificCode = (key) => {
    if (isObjectNotEmpty(key)) {
      setSelHonorificCode(key.clCodeNm)
      form.setValue('objectNameOmit', key.clCodeNm)
    } else {
      setSelHonorificCode('')
      form.setValue('objectNameOmit', '')
    }
  }

  //기준풍속 변경 이벤트
  const onChangeWindSpeedCode = (key) => {
    if (isObjectNotEmpty(key)) {
      form.setValue('standardWindSpeedId', key.clCode)
    } else {
      form.setValue('standardWindSpeedId', '')
    }
  }

  //물건구분 변경 이벤트
  const onRadioChange = (key) => {
    setSelectObjectStatusId(key.target.value)
  }

  //1차점 자동완성 input
  const onInputChange = (key) => {
    if (key !== '') {
      setShowSaleStoreList(saleStoreList)
    } else {
      setShowSaleStoreList(favoriteStoreList)
    }
  }

  //1차점 변경 이벤트
  const onSelectionChange = (key) => {
    if (isObjectNotEmpty(key)) {
      if (key.saleStoreId === selOptions) {
        return
      }
    }

    const planReqNo = form.watch('planReqNo')
    let delFlg = false

    if (editMode === 'NEW') {
      if (planReqNo !== '') {
        if (confirm(getMessage('stuff.detail.confirm.message1'))) {
          delFlg = true
        } else {
          delFlg = false
        }
      }
    } else {
      // EDIT
      if (planReqNo !== null && planReqNo !== '') {
        if (confirm(getMessage('stuff.detail.confirm.message1'))) {
          delFlg = true
        } else {
          delFlg = false
        }
      }
    }

    let tempObjectNo = 'T'
    if (objectNo) {
      tempObjectNo = objectNo.substring(0, 1)
    }

    if (tempObjectNo === 'T') {
      if (planReqNo) {
        if (delFlg) {
          form.setValue('planReqNo', '')
          if (isObjectNotEmpty(key)) {
            setOtherSaleStoreList(otherSaleStoreList)
            form.setValue('saleStoreId', key.saleStoreId)
            form.setValue('saleStoreName', key.saleStoreName)
            form.setValue('saleStoreLevel', key.saleStoreLevel)
            setSelOptions(key.saleStoreId)
            let url = `/api/object/saleStore/${key.saleStoreId}/list?firstFlg=0&userId=${session?.userId}`
            let otherList
            get({ url: url }).then((res) => {
              if (!isEmptyArray(res)) {
                res.map((row) => {
                  row.value = row.saleStoreId
                  row.label = row.saleStoreName
                })

                otherList = res
                setOtherSaleStoreList(otherList)
              } else {
                setOtherSaleStoreList([])
              }
            })
          } else {
            //X누름
            setSelOptions('')
            form.setValue('saleStoreId', '')
            form.setValue('saleStoreName', '')
            form.setValue('saleStoreLevel', '')
            form.setValue('otherSaleStoreId', '')
            form.setValue('otherSaleStoreName', '')
            form.setValue('otherSaleStoreLevel', '')
            //1차점 지웠을때 2차점 자동완성 초기화
            setOtherSaleStoreList(originOtherSaleStoreList)
            handleClear()
          }
        }
      } else {
        if (isObjectNotEmpty(key)) {
          setSelOptions(key.saleStoreId)
          form.setValue('saleStoreId', key.saleStoreId)
          form.setValue('saleStoreName', key.saleStoreName)
          form.setValue('saleStoreLevel', key.saleStoreLevel)
          //선택한 1차점 정보로 2차점 조회하기
          let url = `/api/object/saleStore/${key.saleStoreId}/list?firstFlg=0&userId=${session?.userId}`
          let otherList
          get({ url: url }).then((res) => {
            if (!isEmptyArray(res)) {
              res.map((row) => {
                row.value = row.saleStoreId
                row.label = row.saleStoreName
              })

              otherList = res
              setOtherSaleStoreList(otherList)
              setOtherSelOptions('')
              form.setValue('otherSaleStoreId', '')
              form.setValue('otherSaleStoreName', '')
              form.setValue('otherSaleStoreLevel', '')
            } else {
              setOtherSelOptions('')
              form.setValue('otherSaleStoreId', '')
              form.setValue('otherSaleStoreName', '')
              form.setValue('otherSaleStoreLevel', '')
              setOtherSaleStoreList([])
            }
          })
        } else {
          //X누름
          setSelOptions('')
          form.setValue('saleStoreId', '')
          form.setValue('saleStoreName', '')
          form.setValue('saleStoreLevel', '')
          form.setValue('otherSaleStoreId', '')
          form.setValue('otherSaleStoreName', '')
          form.setValue('otherSaleStoreLevel', '')
          //1차점 지웠을때 2차점 자동완성 초기화
          setOtherSaleStoreList(originOtherSaleStoreList)
          handleClear()
        }
      }
    } else {
      if (isObjectNotEmpty(key)) {
        setOtherSaleStoreList(otherSaleStoreList)
        form.setValue('saleStoreId', key.saleStoreId)
        form.setValue('saleStoreName', key.saleStoreName)
        form.setValue('saleStoreLevel', key.saleStoreLevel)
        setSelOptions(key.saleStoreId)
        let url = `/api/object/saleStore/${key.saleStoreId}/list?firstFlg=0&userId=${session?.userId}`
        let otherList
        get({ url: url }).then((res) => {
          if (!isEmptyArray(res)) {
            res.map((row) => {
              row.value = row.saleStoreId
              row.label = row.saleStoreName
            })

            otherList = res
            setOtherSaleStoreList(otherList)
          } else {
            setOtherSaleStoreList([])
          }
        })
      } else {
        //X누름
        setSelOptions('')
        form.setValue('saleStoreId', '')
        form.setValue('saleStoreName', '')
        form.setValue('saleStoreLevel', '')
        form.setValue('otherSaleStoreId', '')
        form.setValue('otherSaleStoreName', '')
        form.setValue('otherSaleStoreLevel', '')
        //1차점 지웠을때 2차점 자동완성 초기화
        setOtherSaleStoreList(originOtherSaleStoreList)
        handleClear()
      }
    }
  }

  //2차점 변경 이벤트
  const onSelectionChange2 = (key) => {
    if (isObjectNotEmpty(key)) {
      if (key.saleStoreId === otherSelOptions) {
        return
      }
    }

    const planReqNo = form.watch('planReqNo')
    let delFlg = false
    if (editMode === 'NEW') {
      if (planReqNo !== '') {
        if (confirm(getMessage('stuff.detail.confirm.message1'))) {
          delFlg = true
        } else {
          delFlg = false
        }
      }
    } else {
      //EDIT
      if (planReqNo !== null && planReqNo !== '') {
        if (confirm(getMessage('stuff.detail.confirm.message1'))) {
          delFlg = true
        } else {
          delFlg = false
        }
      }
    }

    let tempObjectNo = 'T'
    if (objectNo) {
      tempObjectNo = objectNo.substring(0, 1)
    }

    if (tempObjectNo === 'T') {
      if (planReqNo) {
        if (delFlg) {
          form.setValue('planReqNo', '')
          if (isObjectNotEmpty(key)) {
            setOtherSelOptions(key.saleStoreId)
            form.setValue('otherSaleStoreId', key.saleStoreId)
            form.setValue('otherSaleStoreName', key.saleStoreName)
            form.setValue('otherSaleStoreLevel', key.saleStoreLevel)
          } else {
            setOtherSelOptions('')
            form.setValue('otherSaleStoreId', '')
            form.setValue('otherSaleStoreName', '')
            form.setValue('otherSaleStoreLevel', '')
          }
        }
      } else {
        if (isObjectNotEmpty(key)) {
          setOtherSelOptions(key.saleStoreId)
          form.setValue('otherSaleStoreId', key.saleStoreId)
          form.setValue('otherSaleStoreName', key.saleStoreName)
          form.setValue('otherSaleStoreLevel', key.saleStoreLevel)
        } else {
          setOtherSelOptions('')
          form.setValue('otherSaleStoreId', '')
          form.setValue('otherSaleStoreName', '')
          form.setValue('otherSaleStoreLevel', '')
        }
      }
    } else {
      if (isObjectNotEmpty(key)) {
        setOtherSelOptions(key.saleStoreId)
        form.setValue('otherSaleStoreId', key.saleStoreId)
        form.setValue('otherSaleStoreName', key.saleStoreName)
        form.setValue('otherSaleStoreLevel', key.saleStoreLevel)
      } else {
        setOtherSelOptions('')
        form.setValue('otherSaleStoreId', '')
        form.setValue('otherSaleStoreName', '')
        form.setValue('otherSaleStoreLevel', '')
      }
    }
  }

  //1차점 지웠을때 2차점 자동완성 초기화
  const handleClear = () => {
    if (ref.current) {
      ref.current.clearValue()
    }
  }

  //팝업에서 넘어온 우편정보
  const setZipInfo = (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)
  }

  //팝업에서 넘어온 설계의뢰 정보로 바꾸기
  const setPlanReqInfo = (info) => {
    form.setValue('planReqNo', info.planReqNo)

    form.setValue('objectStatusId', info.building)
    setSelectObjectStatusId(info.building)

    form.setValue('objectName', info.title)
    form.setValue('zipNo', info.zipNo)
    form.setValue('address', info.address2)

    prefCodeList.map((row) => {
      if (row.prefName == info.address1) {
        setPrefValue(row.prefId)
        form.setValue('prefId', row.prefId)
        form.setValue('prefName', info.address1)
      }
    })

    //설계의뢰 팝업에선 WL_안붙어서 옴
    if (info.windSpeed !== '') {
      form.setValue('standardWindSpeedId', `WL_${info.windSpeed}`)
    } else {
      form.setValue('standardWindSpeedId', `WL_${info.windSpeed}`)
    }
    form.setValue('verticalSnowCover', info.verticalSnowCover)
    form.setValue('surfaceType', info.surfaceType)

    if (info.surfaceType === 'Ⅱ') {
      form.setValue('saltAreaFlg', true)
    } else {
      form.setValue('saltAreaFlg', false)
    }

    let installHeight = info.installHeight ? info.installHeight.split('.')[0] : ''

    form.setValue('installHeight', installHeight)
    form.setValue('remarks', info.remarks)

    if (info.saleStoreLevel === '1') {
      setSelOptions(info.saleStoreId)
      form.setValue('saleStoreId', info.saleStoreId)
      form.setValue('saleStoreName', info.saleStoreName)
      form.setValue('saleStoreLevel', info.saleStoreLevel)
    } else {
      setOtherSelOptions(info.saleStoreId)
      form.setValue('otherSaleStoreId', info.saleStoreId)
      form.setValue('otherSaleStoreName', info.saleStoreName)
      form.setValue('otherSaleStoreLevel', info.saleStoreLevel)
    }
  }

  //풍속선택 팝업에서 넘어온 바람정보
  const setWindSppedInfo = (info) => {
    form.setValue('standardWindSpeedId', info.windSpeed)
  }

  //면조도구분surfaceType & 염해지역용아이템사용saltAreaFlg 컨트롤
  const handleRadioChange = (e) => {
    if (e.target.value === 'Ⅱ') {
      form.setValue('saltAreaFlg', true)
    } else {
      form.setValue('saltAreaFlg', false)
    }
  }

  //receiveUser: '', //담당자
  const _receiveUser = watch('receiveUser')
  //objectName: '', //물건명
  const _objectName = watch('objectName')
  // objectNameOmit: '', //경칭선택
  const _objectNameOmit = watch('objectNameOmit')
  // saleStoreId: '', //1차 판매점ID
  const _saleStoreId = watch('saleStoreId')
  // 2차 판매점명
  const _otherSaleStoreId = watch('otherSaleStoreId')
  // zipNo: '', //우편번호
  const _zipNo = watch('zipNo')
  // prefId: '', //도도부현
  const _prefId = watch('prefId')
  // address: '', //주소
  const _address = watch('address')
  // areaId: '', //발전량시뮬레이션지역
  const _areaId = watch('areaId')
  // standardWindSpeedId: '', //기준풍속
  const _standardWindSpeedId = watch('standardWindSpeedId')
  // verticalSnowCover: '', //수직적설량
  const _verticalSnowCover = watch('verticalSnowCover')
  // installHeight: '', //설치높이
  const _installHeight = watch('installHeight')

  useEffect(() => {
    if (editMode === 'NEW') {
      const formData = form.getValues()

      let errors = {}
      if (!formData.receiveUser || formData.receiveUser.trim().length === 0) {
        errors.receiveUser = 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 (session?.storeLvl === '2') {
        if (!formData.otherSaleStoreId) {
          errors.otherSaleStoreId = true
        }
      }

      if (!formData.zipNo) {
        errors.zipNo = true
      }

      if (!formData.prefId) {
        errors.prefId = true
      }

      if (!formData.areaId) {
        errors.areaId = true
      }

      if (!formData.standardWindSpeedId) {
        errors.standardWindSpeedId = true
      }

      if (!formData.verticalSnowCover) {
        errors.verticalSnowCover = true
      }

      if (!formData.installHeight) {
        errors.installHeight = true
      }

      setIsFormValid(Object.keys(errors).length === 0 ? true : false)
    } else {
      //상세일떄 폼체크
      const formData = form.getValues()
      let errors = {}
      if (!formData.receiveUser || formData.receiveUser.trim().length === 0) {
        errors.receiveUser = 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 (session?.storeLvl === '2') {
        if (!formData.otherSaleStoreId) {
          errors.otherSaleStoreId = true
        }
      }

      if (!formData.zipNo) {
        errors.zipNo = true
      }

      if (!formData.prefId || formData.prefId === '0') {
        errors.prefId = true
      }

      if (!formData.areaId || formData.areaId === '0') {
        errors.areaId = true
      }

      if (!formData.standardWindSpeedId) {
        errors.standardWindSpeedId = true
      }

      if (!formData.verticalSnowCover) {
        errors.verticalSnowCover = true
      }

      if (!formData.installHeight) {
        errors.installHeight = true
      }

      setIsFormValid(Object.keys(errors).length === 0 ? true : false)
    }
  }, [
    _receiveUser,
    _objectName,
    _objectNameOmit,
    _saleStoreId,
    _otherSaleStoreId,
    _zipNo,
    _prefId,
    _address,
    _areaId,
    _standardWindSpeedId,
    _verticalSnowCover,
    _installHeight,
  ])

  // 주소검색 팝업오픈
  const onSearchPostNumberPopOpen = () => {
    setShowAddressButtonValid(true)
  }

  //설계의뢰 팝업 오픈
  const onSearchDesignRequestPopOpen = () => {
    const saleStoreId = form.watch('saleStoreId')
    if (saleStoreId === '') {
      swalFire({ text: getMessage('stuff.planReqPopup.error.message2'), type: 'alert' })
    } else {
      setShowDesignRequestButtonValid(true)
    }
  }

  // 풍속선택 팝업 오픈
  const onSearchWindSpeedPopOpen = () => {
    const prefName = form.watch('prefName')
    if (prefName === '') {
      swalFire({ text: getMessage('stuff.windSelectPopup.error.message1'), type: 'alert' })
    } else {
      setShowWindSpeedButtonValid(true)
    }
  }

  useEffect(() => {
    if (prefValue) {
      // 발전량시뮬레이션 지역 목록
      get({ url: `/api/object/prefecture/${prefValue}/list` }).then((res) => {
        if (!isEmptyArray(res)) {
          setAreaIdList(res)
        }
      })
    }
  }, [prefValue])

  // 발전량 시뮬레이션 변경
  const handleAreaIdOnChange = (e) => {
    form.setValue('areaId', e.areaId)
    form.setValue('areaName', e.prefName)
  }

  // 저장
  const onValid = async () => {
    const formData = form.getValues()
    let errors = {}
    let fieldNm
    //담당자
    if (!formData.receiveUser || formData.receiveUser.trim().length === 0) {
      fieldNm = getMessage('stuff.detail.receiveUser')
      errors = fieldNm
    }
    //물건명
    if (!formData.objectName || formData.objectName.trim().length === 0) {
      fieldNm = getMessage('stuff.detail.objectStatusId')
      errors = fieldNm
    }
    //경칭
    if (!formData.objectNameOmit) {
      fieldNm = getMessage('stuff.detail.objectNameOmit')
      errors = fieldNm
    }
    //1차판매점명
    if (!formData.saleStoreId) {
      fieldNm = getMessage('stuff.detail.saleStoreId')
      errors = fieldNm
    }
    //우편번호
    if (!formData.zipNo) {
      fieldNm = getMessage('stuff.detail.zipNo')
      errors = fieldNm
    }
    //주소
    if (!formData.address) {
      fieldNm = getMessage('stuff.detail.address')
      errors = fieldNm
    }
    //도도부현
    if (!formData.prefId || formData.prefId === '0') {
      fieldNm = getMessage('stuff.detail.prefId')
      errors = fieldNm
    }
    //발전시뮬레이션지역
    if (!formData.areaId) {
      fieldNm = getMessage('stuff.detail.areaId')
      errors = fieldNm
    }
    //기준풍속
    if (!formData.standardWindSpeedId) {
      fieldNm = getMessage('stuff.detail.standardWindSpeedId')
      errors = fieldNm
    }
    //수직적설량
    if (!formData.verticalSnowCover) {
      fieldNm = getMessage('stuff.detail.verticalSnowCover')
      errors = fieldNm
    }

    //면조도구분
    if (!formData.surfaceType) {
      fieldNm = getMessage('stuff.detail.surfaceType')
      errors = fieldNm
    }
    //설치높이
    if (!formData.installHeight) {
      fieldNm = getMessage('stuff.detail.installHeight')
      errors = fieldNm
    }

    if (Object.keys(errors).length > 0) {
      return swalFire({ text: getMessage('stuff.detail.save.valierror3', [errors]), type: 'alert' })
    }

    const apiUrl = '/api/object/save-object'

    const params = {
      objectNo: objectNo,
      planReqNo: formData.planReqNo,
      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.receiveUser,
      installHeight: formData.installHeight,
      standardWindSpeedId: formData.standardWindSpeedId,
      verticalSnowCover: formData.verticalSnowCover,
      surfaceType: formData.surfaceType,
      conType: formData.conType,
      coldRegionFlg: formData.coldRegionFlg === true ? '1' : '0',
      saltAreaFlg: formData.saltAreaFlg === true ? '1' : '0',
      remarks: formData.remarks,
      tempFlg: '0',
      workNo: null,
      workName: null,
      userId: session.userId,
    }

    //수직적설량, 설치높이 0인지 체크
    let snow = params.verticalSnowCover
    let height = params.installHeight

    if (snow === '0') {
      return swalFire({ text: getMessage('stuff.detail.save.valierror1'), type: 'alert' })
    }
    if (height === '0') {
      return swalFire({ text: getMessage('stuff.detail.save.valierror2'), type: 'alert' })
    }

    if (managementState) {
      let detail_sort = Object.keys(managementState)
        .sort()
        .reduce((obj, key) => ((obj[key] = managementState[key]), obj), {})
      let params_sort = Object.keys(params)
        .sort()
        .reduce((obj, key) => ((obj[key] = params[key]), obj), {})

      delete detail_sort.areaName
      delete detail_sort.contentsPath
      delete detail_sort.createDatetime
      delete detail_sort.createUserName
      delete detail_sort.dispCompanyName
      delete detail_sort.firstAgentId
      delete detail_sort.lastEditDatetime
      delete detail_sort.lastEditUserName
      delete detail_sort.planList
      delete detail_sort.planNo
      delete detail_sort.planTotCnt
      delete detail_sort.receiveCompanyName
      delete detail_sort.saleStoreName
      delete detail_sort.rowNumber
      delete detail_sort.prefName
      delete detail_sort.sameObjectInfo
      delete detail_sort.specificationConfirmDate
      delete detail_sort.totCnt
      delete detail_sort.workNo
      delete detail_sort.workName

      delete params_sort.areaName
      delete params_sort.contentsPath
      delete params_sort.createDatetime
      delete params_sort.createUserName
      delete params_sort.dispCompanyName
      delete params_sort.firstAgentId
      delete params_sort.lastEditDatetime
      delete params_sort.lastEditUserName
      delete params_sort.planList
      delete params_sort.planNo
      delete params_sort.planTotCnt
      delete params_sort.receiveCompanyName
      delete params_sort.saleStoreName
      delete params_sort.rowNumber
      delete params_sort.prefName
      delete params_sort.sameObjectInfo
      delete params_sort.specificationConfirmDate
      delete params_sort.totCnt
      delete params_sort.workNo
      delete params_sort.workName

      if (Object.entries(detail_sort).toString() === Object.entries(params_sort).toString()) {
        return swalFire({ text: getMessage('stuff.detail.noChgData'), type: 'alert' })
      }
    }

    if (params?.receiveUser !== '') {
      if (params?.receiveUser.trim().length > 10) {
        return swalFire({ text: getMessage('stuff.detail.tempSave.message2'), type: 'alert' })
      }
    }
    //로그인이 2차점인데 otherSaleStoreId가 없으면 알럿
    if (session.storeLvl !== '1') {
      if (params.saleStoreLevel === '1') {
        return swalFire({ text: getMessage('stuff.detail.tempSave.message3'), type: 'alert' })
      }
    }

    if (editMode === 'NEW') {
      await promisePost({ url: apiUrl, data: params })
        .then((res) => {
          setIsGlobalLoading(true)
          //상세화면으로 전환
          if (res.status === 201) {
            setIsGlobalLoading(false)
            setFloorPlanObjectNo({ floorPlanObjectNo: res?.data?.objectNo })
            swalFire({
              text: getMessage('stuff.detail.save'),
              type: 'alert',
              confirmFn: () => {
                router.push(`/management/stuff/detail?objectNo=${res.data.objectNo.toString()}`, { scroll: false })
              },
            })
          }
        })
        .catch((error) => {
          console.log('error::::::', error)
          setIsGlobalLoading(false)
        })
    } else {
      // 수정모드일때는 PUT
      await promisePut({ url: apiUrl, data: params })
        .then((res) => {
          setIsGlobalLoading(true)

          if (res.status === 201) {
            setIsGlobalLoading(false)
            setFloorPlanObjectNo({ floorPlanObjectNo: res.data.objectNo })
            swalFire({
              text: getMessage('stuff.detail.save'),
              type: 'alert',
              confirmFn: () => {
                let surfaceTypeValue
                if (res.data.surfaceType === 'Ⅲ・Ⅳ') {
                  surfaceTypeValue = '3'
                } else if (res.data.surfaceType === 'Ⅱ') {
                  surfaceTypeValue = '2'
                }
                setManagementState({ ...res.data, surfaceTypeValue: surfaceTypeValue })
                router.push(`/management/stuff/detail?objectNo=${res.data.objectNo.toString()}`, { scroll: false })
              },
            })
          }
        })
        .catch((error) => {
          console.log('error::::::', error)
          setIsGlobalLoading(false)
        })
    }
  }

  // 임시저장
  const onTempSave = async () => {
    const formData = form.getValues()
    const params = {
      planReqNo: formData.planReqNo,
      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.receiveUser,
      installHeight: formData.installHeight,
      standardWindSpeedId: formData.standardWindSpeedId,
      verticalSnowCover: formData.verticalSnowCover,
      surfaceType: formData.surfaceType,
      conType: formData.conType,
      coldRegionFlg: formData.coldRegionFlg === true ? '1' : '0',
      saltAreaFlg: formData.saltAreaFlg === true ? '1' : '0',
      remarks: formData.remarks,
      tempFlg: '1',
      workNo: null,
      workName: null,
      objectNo: objectNo ? objectNo : '',
      userId: session.userId,
    }

    //1차점 or 2차점 안고르고 임시저장하면
    if (params.saleStoreId == '') {
      params.saleStoreId = session.storeId
      params.saleStoreLevel = session.storeLvl
    }

    if (session.storeLvl !== '1') {
      //로그인이 1차점이 아닌데 2차점을 안골라서 saleStoreLevel = 1로 셋팅되어있으면 알럿
      if (params.saleStoreLevel === '1') {
        return swalFire({ text: getMessage('stuff.detail.tempSave.message3'), type: 'alert' })
      }
    }

    // 담당자 자리수 체크
    if (params?.receiveUser !== '') {
      if (params?.receiveUser.trim().length > 10) {
        return swalFire({ text: getMessage('stuff.detail.tempSave.message2'), type: 'alert' })
      }
    }

    const apiUrl = '/api/object/save-object'
    if (objectNo) {
      await promisePut({ url: apiUrl, data: params })
        .then((res) => {
          setIsGlobalLoading(true)
          if (res.status === 201) {
            setIsGlobalLoading(false)
            swalFire({
              text: getMessage('stuff.detail.tempSave.message1'),
              type: 'alert',
              confirmFn: () => {
                router.push(`/management/stuff/tempdetail?objectNo=${res.data.objectNo.toString()}`, { scroll: false })
              },
            })
          }
        })
        .catch((error) => {
          setIsGlobalLoading(false)
          console.log('error::::::', error)
        })
    } else {
      await promisePost({ url: apiUrl, data: params })
        .then((res) => {
          setIsGlobalLoading(true)
          if (res.status === 201) {
            setIsGlobalLoading(false)
            swalFire({
              text: getMessage('stuff.detail.tempSave.message1'),
              type: 'alert',
              confirmFn: () => {
                router.push(`/management/stuff/tempdetail?objectNo=${res.data.objectNo.toString()}`, { scroll: false })
              },
            })
          }
        })
        .catch((error) => {
          console.log('error::::::', error)
          setIsGlobalLoading(false)
        })
    }
  }

  // 물건삭제
  const onDelete = () => {
    const specificationConfirmDate = managementState.specificationConfirmDate
    const delParams = {
      userId: session.userId,
    }
    if (specificationConfirmDate != null) {
      swalFire({ text: getMessage('stuff.detail.delete.message1'), type: 'alert' })
    } else {
      swalFire({
        text: getMessage('common.message.data.delete'),
        type: 'confirm',
        confirmFn: () => {
          setFloorPlanObjectNo({ floorPlanObjectNo: '' })
          del({ url: `/api/object/${objectNo}?${queryStringFormatter(delParams)}` })
            .then(() => {
              setIsGlobalLoading(true)
              setFloorPlanObjectNo({ floorPlanObjectNo: '' })
              if (session.storeId === 'T01') {
                stuffSearchParams.code = 'DELETE'
              } else {
                if (session.storeLvl === '1') {
                  stuffSearch.schObjectNo = ''
                  stuffSearch.schAddress = ''
                  stuffSearch.schObjectName = ''
                  stuffSearch.schSaleStoreName = ''
                  stuffSearch.schReceiveUser = ''
                  stuffSearch.schDispCompanyName = ''
                  stuffSearch.schDateType = 'U'
                  stuffSearch.schTempFlg = ''
                  stuffSearch.schMyDataCheck = false
                  stuffSearch.startRow = 1
                  stuffSearch.endRow = 100
                  stuffSearch.schSortType = 'U'
                  stuffSearch.pageNo = 1
                  stuffSearch.pageSize = 100
                  stuffSearch.code = 'S'
                } else {
                  stuffSearch.schObjectNo = ''
                  stuffSearch.schAddress = ''
                  stuffSearch.schObjectName = ''
                  stuffSearch.schSaleStoreName = ''
                  stuffSearch.schReceiveUser = ''
                  stuffSearch.schDispCompanyName = ''
                  stuffSearch.schDateType = 'U'
                  stuffSearch.schTempFlg = ''
                  stuffSearch.schMyDataCheck = false
                  stuffSearch.startRow = 1
                  stuffSearch.endRow = 100
                  stuffSearch.schSortType = 'U'
                  stuffSearch.pageNo = 1
                  stuffSearch.pageSize = 100
                  stuffSearch.code = 'S'
                }
              }
              setIsGlobalLoading(false)
              router.push('/management/stuff', { scroll: false })
            })
            .catch((error) => {
              console.log('error::::::', error)
              setIsGlobalLoading(false)
            })
        },
      })
    }
  }

  // 숫자만 입력 가능
  const handleKeyUp = (e) => {
    let input = e.target
    input.value = input.value.replace(/[^0-9]/g, '')
  }

  const handleBlur = (e) => {
    let input = e.target
    input.value = input.value.replace(/[^0-9]/g, '')
  }

  //자동완성 옵션 없을때 메세지 컴포넌트..
  const NoOptionsMessage = (props) => {
    return (
      <components.NoOptionsMessage {...props}>
        <span style={{ background: 'red' }} className="custom-css-class">
          TEXTTTTTTT
        </span>
      </components.NoOptionsMessage>
    )
  }

  // 그리드 더블 클릭 해당플랜의 도면작성 화면으로 이동
  const getCellDoubleClicked = (params) => {
    if (managementState?.createSaleStoreId === 'T01') {
      if (session?.storeId !== 'T01') {
        return false
      }
    }

    if (params?.column?.colId !== 'estimateDate') {
      if (params?.data?.planNo && params?.data?.objectNo) {
        let objectNo = params?.data?.objectNo
        let planNo = params?.data?.planNo

        const param = {
          pid: planNo,
          objectNo: objectNo,
        }
        setMenuNumber(null)
        const url = `/floor-plan?${queryStringFormatter(param)}`
        router.push(url)
      }
    }
  }

  const CustomOption = (props) => {
    const { data, innerRef, innerProps, isSelected, isFocused, isDisabled } = props
    const customClass = data.saleStoreId === 'T01' || data.priority !== 'B' ? 'special-option' : ''
    // 기본 선택/호버 상태 적용
    const optionClass = `${customClass} ${isSelected ? 'custom__option--is-selected' : ''} ${isFocused ? 'custom__option--is-focused' : ''} ${isDisabled ? 'custom__option--is-disabled' : ''}`

    return (
      <div ref={innerRef} {...innerProps} className={`custom__option ${optionClass}`}>
        {data.label}
      </div>
    )
  }

  const CustomOption2 = (props) => {
    const { data, innerRef, innerProps, isSelected, isFocused, isDisabled } = props
    const customClass = data.priority !== 'B' ? 'special-option' : ''
    // 기본 선택/호버 상태 적용
    const optionClass = `${customClass} ${isSelected ? 'custom__option--is-selected' : ''} ${isFocused ? 'custom__option--is-focused' : ''} ${isDisabled ? 'custom__option--is-disabled' : ''}`
    return (
      <div ref={innerRef} {...innerProps} className={`custom__option ${optionClass}`}>
        {data.label}
      </div>
    )
  }

  return (
    <>
      {(editMode === 'NEW' && (
        <form onSubmit={handleSubmit(onValid)}>
          <div className="sub-table-box">
            <div className="promise-title-wrap">
              <div className="promise-gudie">
                <span className="important">*</span>
                {getMessage('stuff.detail.required')}
              </div>
              <div className="left-unit-box">
                {!isFormValid ? (
                  <Button className="btn-origin grey mr5" onPress={onTempSave} style={{ display: showButton }}>
                    {getMessage('stuff.detail.btn.tempSave')}
                  </Button>
                ) : (
                  <Button type="submit" className="btn-origin navy mr5" style={{ display: showButton }}>
                    {getMessage('stuff.detail.btn.save')}
                  </Button>
                )}
                {/* <Link href="/management/stuff" scroll={false}>
                  <button type="button" className="btn-origin grey">
                    {getMessage('stuff.detail.btn.moveList')}
                  </button>
                </Link> */}
                <button
                  type="button"
                  className="btn-origin grey"
                  onClick={() => {
                    setIsGlobalLoading(true)
                    router.push(`/management/stuff`, { scroll: false })
                  }}
                >
                  {getMessage('stuff.detail.btn.moveList')}
                </button>
              </div>
            </div>
            <div className="infomation-table">
              <table>
                <colgroup>
                  <col style={{ width: '200px' }} />
                  <col />
                </colgroup>
                <tbody>
                  <tr>
                    <th>{getMessage('stuff.detail.planReqNo')}</th>
                    <td>
                      <div className="flx-box">
                        <div className="product-input-wrap mr5">
                          <input type="text" className="product-input" readOnly value={form.watch('planReqNo') || ''} />
                          {(form.watch('planReqNo') !== '' && (
                            <button
                              type="button"
                              className="product-delete"
                              onClick={() => {
                                form.setValue('planReqNo', '')
                              }}
                            ></button>
                          )) ||
                            null}
                        </div>
                        <Button type="button" className="btn-origin grey" onPress={onSearchDesignRequestPopOpen} style={{ display: showButton }}>
                          {getMessage('stuff.planReqPopup.title')}
                        </Button>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      {getMessage('stuff.detail.receiveUser')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="input-wrap" style={{ width: '500px' }}>
                        <input type="text" className="input-light" {...form.register('receiveUser')} />
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      {getMessage('stuff.detail.objectStatusId')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="flx-box">
                        {/* 라디오시작 */}
                        {objectStatusList.map((row) => {
                          return (
                            <div className="d-check-radio light mr10" key={`objectStatusId_${row.clCode}`}>
                              <input
                                type="radio"
                                name="objectStatusId"
                                value={row.clCode}
                                id={`objectStatus${row.clCode}`}
                                {...register('objectStatusId')}
                                onChange={onRadioChange}
                                checked={row.clCode === selectObjectStatusId}
                              />
                              <label htmlFor={`objectStatus${row.clCode}`}>{row.clCodeNm}</label>
                            </div>
                          )
                        })}
                        {/* 라디오끝 */}
                        <div className="input-wrap mr5" style={{ width: '545px' }}>
                          <input type="text" className="input-light" {...form.register('objectName')} />
                        </div>
                        <div className="select-wrap" style={{ width: '120px' }}>
                          <Select
                            {...register('objectNameOmit')}
                            id="long-value-select0"
                            instanceId="long-value-select0"
                            className="react-select-custom"
                            classNamePrefix="custom"
                            placeholder="Select"
                            options={honorificCodeList}
                            onChange={onChangeHonorificCode}
                            getOptionLabel={(x) => x.clCodeNm}
                            getOptionValue={(x) => x.clCode}
                            isClearable={true}
                            isSearchable={false}
                            value={honorificCodeList.filter(function (option) {
                              return option.clCodeNm === selHonorificCode
                            })}
                          ></Select>
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>{getMessage('stuff.detail.objectNameKana')}</th>
                    <td>
                      <div className="input-wrap" style={{ width: '789px' }}>
                        <input type="text" className="input-light" {...form.register('objectNameKana')} />
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      <div className="flx-box">
                        <div className="title">
                          {getMessage('stuff.detail.saleStoreId')}
                          <span className="important">*</span>
                        </div>
                        <div className="tooltips">
                          <span>{getMessage('stuff.detail.tooltip.saleStoreId')}</span>
                        </div>
                      </div>
                    </th>
                    <td>
                      <div className="flx-box">
                        {session?.storeId === 'T01' && (
                          <>
                            <div className="select-wrap mr5" style={{ width: '567px' }}>
                              <Select
                                id="long-value-select1"
                                instanceId="long-value-select1"
                                className="react-select-custom"
                                classNamePrefix="custom"
                                placeholder="Select"
                                options={showSaleStoreList}
                                onInputChange={onInputChange}
                                onChange={onSelectionChange}
                                getOptionLabel={(x) => x.saleStoreName}
                                getOptionValue={(x) => x.saleStoreId}
                                isClearable={true}
                                isDisabled={session?.storeLvl !== '1' ? true : false}
                                value={saleStoreList.filter(function (option) {
                                  return option.saleStoreId === selOptions
                                })}
                                components={{ Option: CustomOption }}
                              ></Select>
                            </div>
                            <div className="input-wrap" style={{ width: '216px' }}>
                              <input
                                type="text"
                                className="input-light"
                                value={form.watch('saleStoreId') || ''}
                                {...form.register('saleStoreId')}
                                readOnly
                              />
                            </div>
                          </>
                        )}

                        {session?.storeId !== 'T01' && session?.storeLvl === '1' && (
                          <>
                            <div className="select-wrap mr5" style={{ width: '567px' }}>
                              <Select
                                id="long-value-select1"
                                instanceId="long-value-select1"
                                className="react-select-custom"
                                classNamePrefix="custom"
                                placeholder="Select"
                                options={showSaleStoreList[0]}
                                onChange={onSelectionChange}
                                getOptionLabel={(x) => x.saleStoreName}
                                getOptionValue={(x) => x.saleStoreId}
                                isClearable={false}
                                isDisabled={session?.storeLvl !== '1' ? true : session?.storeId !== 'T01' ? true : false}
                                value={showSaleStoreList.filter(function (option) {
                                  return option.saleStoreId === selOptions
                                })}
                                // components={{ Option: CustomOption }}
                              ></Select>
                            </div>
                            <div className="input-wrap" style={{ width: '216px' }}>
                              <input
                                type="text"
                                className="input-light"
                                value={form.watch('saleStoreId') || ''}
                                {...form.register('saleStoreId')}
                                readOnly
                              />
                            </div>
                          </>
                        )}
                        {session?.storeId !== 'T01' && session?.storeLvl !== '1' && (
                          <>
                            <div className="select-wrap mr5" style={{ width: '567px' }}>
                              <Select
                                id="long-value-select1"
                                instanceId="long-value-select1"
                                className="react-select-custom"
                                classNamePrefix="custom"
                                placeholder="Select"
                                options={showSaleStoreList}
                                onChange={onSelectionChange}
                                getOptionLabel={(x) => x.saleStoreName}
                                getOptionValue={(x) => x.saleStoreId}
                                isClearable={false}
                                isDisabled={true}
                                value={showSaleStoreList.filter(function (option) {
                                  return option.saleStoreId === selOptions
                                })}
                                // components={{ Option: CustomOption }}
                              ></Select>
                            </div>
                            <div className="input-wrap" style={{ width: '216px' }}>
                              <input
                                type="text"
                                className="input-light"
                                value={form.watch('saleStoreId') || ''}
                                {...form.register('saleStoreId')}
                                readOnly
                              />
                            </div>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      <div className="flx-box">
                        <div className="title">
                          {getMessage('stuff.detail.otherSaleStoreId')}
                          {session.storeLvl !== '1' && <span className="important">*</span>}
                        </div>
                        <div className="tooltips">
                          <span>{getMessage('stuff.detail.tooltip.saleStoreId')}</span>
                        </div>
                      </div>
                    </th>
                    <td>
                      <div className="flx-box">
                        <div className="select-wrap mr5" style={{ width: '567px' }}>
                          <Select
                            id="long-value-select2"
                            // components={{ NoOptionsMessage }}
                            instanceId="long-value-select2"
                            className="react-select-custom"
                            classNamePrefix="custom"
                            placeholder="Select"
                            ref={ref}
                            options={otherSaleStoreList}
                            onChange={onSelectionChange2}
                            getOptionLabel={(x) => x.saleStoreName}
                            getOptionValue={(x) => x.saleStoreId}
                            isDisabled={
                              session?.storeLvl === '1'
                                ? otherSaleStoreList.length > 0
                                  ? false
                                  : true
                                : otherSaleStoreList.length === 1
                                  ? true
                                  : false
                            }
                            isClearable={true}
                            value={otherSaleStoreList.filter(function (option) {
                              return option.saleStoreId === otherSelOptions
                            })}
                            components={{ Option: CustomOption2 }}
                          />
                        </div>
                        <div className="input-wrap" style={{ width: '216px' }}>
                          <input
                            type="text"
                            className="input-light"
                            value={form.watch('otherSaleStoreId') || ''}
                            {...form.register('otherSaleStoreId')}
                            readOnly
                          />
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      {getMessage('stuff.detail.zipNo')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="flx-box">
                        <div className="input-wrap mr5" style={{ width: '200px' }}>
                          <input type="text" className="input-light" disabled value={form.watch('zipNo') || ''} />
                        </div>
                        <Button className="btn-origin grey" onPress={onSearchPostNumberPopOpen} style={{ display: showButton }}>
                          {getMessage('stuff.detail.btn.addressPop')}
                        </Button>
                        <div className="guide">{getMessage('stuff.detail.btn.addressPop.guide')}</div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      {getMessage('stuff.detail.prefId')}
                      <span className="important">*</span>
                    </th>
                    <td>
                      <div className="flx-box">
                        <div className="select-wrap mr5" style={{ width: '200px' }}>
                          {prefCodeList?.length > 0 && (
                            <Select
                              id="long-value-select3"
                              instanceId="long-value-select3"
                              className="react-select-custom"
                              classNamePrefix="custom"
                              placeholder="Select"
                              options={prefCodeList}
                              getOptionLabel={(x) => x.prefName}
                              getOptionValue={(x) => x.prefId}
                              isSearchable={false}
                              value={prefCodeList.filter(function (option) {
                                return option.prefId === prefValue
                              })}
                              isDisabled={true}
                            />
                          )}
                        </div>
                        <div className="input-wrap mr5" style={{ width: '580px' }}>
                          <input type="text" className="input-light" value={form.watch('address') || ''} {...form.register('address')} />
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      {getMessage('stuff.detail.areaId')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="select-wrap" style={{ width: '200px' }}>
                        <Select
                          id="long-value-select4"
                          instanceId="long-value-select4"
                          className="react-select-custom"
                          classNamePrefix="custom"
                          options={areaIdList}
                          placeholder="Select"
                          getOptionLabel={(x) => x.prefName}
                          getOptionValue={(x) => x.areaId}
                          isSearchable={false}
                          onChange={handleAreaIdOnChange}
                          value={areaIdList.filter(function (option) {
                            return option.areaId === form.watch('areaId')
                          })}
                          isDisabled={areaIdList.length > 0 ? false : true}
                        />
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      {getMessage('stuff.detail.standardWindSpeedId')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="flx-box">
                        <div className="select-wrap mr10" style={{ width: '200px' }}>
                          <Select
                            {...register('standardWindSpeedId')}
                            id="long-value-select5"
                            instanceId="long-value-select5"
                            className="react-select-custom"
                            classNamePrefix="custom"
                            placeholder="Select"
                            options={windSpeedList}
                            onChange={onChangeWindSpeedCode}
                            getOptionLabel={(x) => x.clCodeNm}
                            getOptionValue={(x) => x.clCode}
                            isClearable={true}
                            isSearchable={false}
                            value={windSpeedList.filter(function (option) {
                              return option.clCode === watch('standardWindSpeedId')
                            })}
                          ></Select>
                        </div>
                        <span className="mr10">{getMessage('stuff.detail.standardWindSpeedIdSpan')}</span>
                        <Button type="button" className="btn-origin grey" onPress={onSearchWindSpeedPopOpen} style={{ display: showButton }}>
                          {getMessage('stuff.detail.btn.windSpeedPop')}
                        </Button>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      {getMessage('stuff.detail.verticalSnowCover')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="flx-box">
                        <div className="input-wrap mr10" style={{ width: '200px' }}>
                          <input
                            type="text"
                            className="input-light"
                            onInput={handleKeyUp}
                            onBlur={handleBlur}
                            value={form.watch('verticalSnowCover') || ''}
                            {...register('verticalSnowCover')}
                          />
                        </div>
                        <span className="mr10">cm</span>
                        <div className="d-check-box light">
                          <input type="checkbox" id="coldRegionFlg" {...form.register('coldRegionFlg')} />
                          <label htmlFor="coldRegionFlg">{getMessage('stuff.detail.coldRegionFlg')}</label>
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      {getMessage('stuff.detail.surfaceType')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="flx-box">
                        <div className="radio-wrap flx-box" style={{ width: '239px' }}>
                          <div className="d-check-radio light mr10">
                            <input
                              type="radio"
                              name="surfaceType"
                              value="Ⅲ・Ⅳ"
                              id="surfaceType0"
                              {...form.register('surfaceType')}
                              onChange={(e) => {
                                handleRadioChange(e)
                              }}
                            />
                            <label htmlFor="surfaceType0">Ⅲ・Ⅳ</label>
                          </div>
                          <div className="d-check-radio light">
                            <input
                              type="radio"
                              name="surfaceType"
                              value="Ⅱ"
                              id="surfaceType1"
                              {...form.register('surfaceType')}
                              onChange={(e) => {
                                handleRadioChange(e)
                              }}
                            />
                            <label htmlFor="surfaceType1">Ⅱ</label>
                          </div>
                        </div>
                        <div className="d-check-box light mr5">
                          <input type="checkbox" id="saltAreaFlg" {...form.register('saltAreaFlg')} />
                          <label htmlFor="saltAreaFlg">{getMessage('stuff.detail.saltAreaFlg')}</label>
                        </div>
                        <div className="tooltips">
                          <span>{getMessage('stuff.detail.tooltip.surfaceType')}</span>
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      {getMessage('stuff.detail.installHeight')} <span className="important">*</span>
                    </th>
                    <td>
                      <div className="flx-box">
                        <div className="input-wrap mr10" style={{ width: '200px' }}>
                          <input
                            type="text"
                            className="input-light"
                            onInput={handleKeyUp}
                            onBlur={handleBlur}
                            value={form.watch('installHeight') || ''}
                            {...register('installHeight')}
                          />
                        </div>
                        <span>m</span>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>{getMessage('stuff.detail.conType')}</th>
                    <td>
                      <div className="flx-box">
                        <div className="d-check-radio light mr10">
                          <input type="radio" name="conType" value="0" id="conType0" {...form.register('conType')} />
                          <label htmlFor="conType0">{getMessage('stuff.detail.conType0')}</label>
                        </div>
                        <div className="d-check-radio light mr10">
                          <input type="radio" name="conType" value="1" id="conType1" {...form.register('conType')} />
                          <label htmlFor="conType1">{getMessage('stuff.detail.conType1')}</label>
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>{getMessage('stuff.detail.remarks')}</th>
                    <td>
                      <div className="input-wrap">
                        <input type="text" className="input-light" {...form.register('remarks')} />
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div className="sub-right-footer">
              {!isFormValid ? (
                <Button className="btn-origin grey mr5" onPress={onTempSave} style={{ display: showButton }}>
                  {getMessage('stuff.detail.btn.tempSave')}
                </Button>
              ) : (
                <Button type="submit" className="btn-origin navy mr5" style={{ display: showButton }}>
                  {getMessage('stuff.detail.btn.save')}
                </Button>
              )}
              {/* <Link href="/management/stuff" scroll={false}>
                <button type="button" className="btn-origin grey">
                  {getMessage('stuff.detail.btn.moveList')}
                </button>
              </Link> */}
              <button
                type="button"
                className="btn-origin grey"
                onClick={() => {
                  setIsGlobalLoading(true)
                  router.push(`/management/stuff`, { scroll: false })
                }}
              >
                {getMessage('stuff.detail.btn.moveList')}
              </button>
            </div>
          </div>
        </form>
      )) || (
        <>
          <form onSubmit={handleSubmit(onValid)}>
            <div className="sub-table-box">
              <div className="promise-title-wrap">
                <div className="promise-gudie">
                  <span className="important">*</span> {getMessage('stuff.detail.required')}
                </div>
                {managementState?.tempFlg === '0' ? (
                  <>
                    <div className="left-unit-box">
                      {/* <Link href="/management/stuff" scroll={false}>
                        <button type="button" className="btn-origin grey mr5">
                          {getMessage('stuff.detail.btn.moveList')}
                        </button>
                      </Link> */}
                      <button
                        type="button"
                        className="btn-origin grey mr5"
                        onClick={() => {
                          setIsGlobalLoading(true)
                          router.push(`/management/stuff`, { scroll: false })
                        }}
                      >
                        {getMessage('stuff.detail.btn.moveList')}
                      </button>
                      <Button type="submit" className="btn-origin navy mr5" style={{ display: showButton }}>
                        {getMessage('stuff.detail.btn.save')}
                      </Button>
                      <Button type="button" className="btn-origin grey" onPress={onDelete} style={{ display: showButton }}>
                        {getMessage('stuff.detail.btn.delete')}
                      </Button>
                    </div>
                  </>
                ) : (
                  <>
                    <div className="left-unit-box">
                      {!isFormValid ? (
                        <Button className="btn-origin grey mr5" onPress={onTempSave} style={{ display: showButton }}>
                          {getMessage('stuff.detail.btn.tempSave')}
                        </Button>
                      ) : (
                        <Button type="submit" className="btn-origin navy mr5" style={{ display: showButton }}>
                          {getMessage('stuff.detail.btn.save')}
                        </Button>
                      )}
                      {/* <Link href="/management/stuff" scroll={false}>
                        <button type="button" className="btn-origin grey">
                          {getMessage('stuff.detail.btn.moveList')}
                        </button>
                      </Link> */}
                      <button
                        type="button"
                        className="btn-origin grey"
                        onClick={() => {
                          setIsGlobalLoading(true)
                          router.push(`/management/stuff`, { scroll: false })
                        }}
                      >
                        {getMessage('stuff.detail.btn.moveList')}
                      </button>
                    </div>
                  </>
                )}
              </div>
              <div className="infomation-wrap">
                <div className="infomation-table">
                  <table>
                    <colgroup>
                      <col style={{ width: '200px' }} />
                      <col />
                    </colgroup>
                    <tbody>
                      <tr>
                        <th>{getMessage('stuff.detail.planReqNo')}</th>
                        <td>
                          <div className="flx-box">
                            <div className="product-input-wrap mr5">
                              <input type="text" className="product-input" readOnly value={form.watch('planReqNo') || ''} />
                              {managementState?.tempFlg === '1' && form.watch('planReqNo') ? (
                                <button
                                  type="button"
                                  className="product-delete"
                                  onClick={() => {
                                    form.setValue('planReqNo', '')
                                  }}
                                  style={{ display: showButton }}
                                ></button>
                              ) : null}
                            </div>
                            {managementState?.tempFlg === '1' ? (
                              <>
                                <Button className="btn-origin grey" onPress={onSearchDesignRequestPopOpen} style={{ display: showButton }}>
                                  {getMessage('stuff.planReqPopup.title')}
                                </Button>
                              </>
                            ) : null}
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>
                          {getMessage('stuff.detail.receiveUser')} <span className="important">*</span>
                        </th>
                        <td>
                          <div className="input-wrap" style={{ width: '500px' }}>
                            <input type="text" className="input-light" {...form.register('receiveUser')} value={form.watch('receiveUser') || ''} />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>
                          {getMessage('stuff.detail.objectStatusId')} <span className="important">*</span>
                        </th>
                        <td>
                          <div className="flx-box">
                            {/* 상세라디오시작 */}
                            {objectStatusList.map((row) => {
                              return (
                                <div className="d-check-radio light mr10" key={`objectStatusId_${row.clCode}`}>
                                  <input
                                    type="radio"
                                    name="objectStatusId"
                                    value={row.clCode}
                                    id={`objectStatus${row.clCode}`}
                                    {...register('objectStatusId')}
                                    onChange={onRadioChange}
                                    checked={row.clCode === selectObjectStatusId}
                                  />
                                  <label htmlFor={`objectStatus${row.clCode}`}>{row.clCodeNm}</label>
                                </div>
                              )
                            })}
                            {/* 상세라디오끝 */}
                            <div className="input-wrap mr5" style={{ width: '545px' }}>
                              <input type="text" className="input-light" {...form.register('objectName')} />
                            </div>
                            <div className="select-wrap" style={{ width: '120px' }}>
                              <Select
                                {...register('objectNameOmit')}
                                id="long-value-select0"
                                instanceId="long-value-select0"
                                className="react-select-custom"
                                classNamePrefix="custom"
                                placeholder="Select"
                                options={honorificCodeList}
                                onChange={onChangeHonorificCode}
                                getOptionLabel={(x) => x.clCodeNm}
                                getOptionValue={(x) => x.clCode}
                                isClearable={true}
                                isSearchable={false}
                                value={honorificCodeList.filter(function (option) {
                                  return option.clCodeNm === selHonorificCode
                                })}
                              ></Select>
                            </div>
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('stuff.detail.objectNameKana')}</th>
                        <td>
                          <div className="input-wrap" style={{ width: '789px' }}>
                            <input type="text" className="input-light" {...form.register('objectNameKana')} />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>
                          <div className="flx-box">
                            <div className="title">
                              {getMessage('stuff.detail.saleStoreId')}
                              <span className="important">*</span>
                            </div>
                            <div className="tooltips">
                              <span>{getMessage('stuff.detail.tooltip.saleStoreId')}</span>
                            </div>
                          </div>
                        </th>
                        <td>
                          <div className="flx-box">
                            {session?.storeId === 'T01' && (
                              <>
                                <div className="select-wrap mr5" style={{ width: '567px' }}>
                                  <Select
                                    // menuPlacement={'auto'}
                                    id="long-value-select1"
                                    instanceId="long-value-select1"
                                    className="react-select-custom"
                                    classNamePrefix="custom"
                                    placeholder="Select"
                                    options={showSaleStoreList}
                                    onInputChange={onInputChange}
                                    onChange={onSelectionChange}
                                    getOptionLabel={(x) => x.saleStoreName}
                                    getOptionValue={(x) => x.saleStoreId}
                                    isClearable={managementState?.tempFlg === '0' ? false : session?.storeLvl === '1' ? true : false}
                                    isDisabled={managementState?.tempFlg === '0' ? true : session?.storeLvl !== '1' ? true : false}
                                    value={saleStoreList.filter(function (option) {
                                      return option.saleStoreId === selOptions
                                    })}
                                    components={{ Option: CustomOption }}
                                  />
                                </div>
                                <div className="input-wrap" style={{ width: '216px' }}>
                                  <input
                                    type="text"
                                    className="input-light"
                                    value={form.watch('saleStoreId') || ''}
                                    {...form.register('saleStoreId')}
                                    readOnly
                                  />
                                </div>
                              </>
                            )}
                            {session?.storeId !== 'T01' && session?.storeLvl === '1' && (
                              <>
                                <div className="select-wrap mr5" style={{ width: '567px' }}>
                                  <Select
                                    menuPlacement={'auto'}
                                    id="long-value-select1"
                                    instanceId="long-value-select1"
                                    className="react-select-custom"
                                    classNamePrefix="custom"
                                    placeholder="Select"
                                    options={showSaleStoreList[0]}
                                    onChange={onSelectionChange}
                                    getOptionLabel={(x) => x.saleStoreName}
                                    getOptionValue={(x) => x.saleStoreId}
                                    isClearable={false}
                                    isDisabled={
                                      managementState?.tempFlg === '0'
                                        ? true
                                        : session?.storeLvl !== '1'
                                          ? true
                                          : session?.storeId !== 'T01'
                                            ? true
                                            : false
                                    }
                                    value={showSaleStoreList.filter(function (option) {
                                      return option.saleStoreId === selOptions
                                    })}
                                    // components={{ Option: CustomOption }}
                                  />
                                </div>
                                <div className="input-wrap" style={{ width: '216px' }}>
                                  <input
                                    type="text"
                                    className="input-light"
                                    value={form.watch('saleStoreId') || ''}
                                    {...form.register('saleStoreId')}
                                    readOnly
                                  />
                                </div>
                              </>
                            )}
                            {session?.storeId !== 'T01' && session?.storeLvl !== '1' && (
                              <>
                                <div className="select-wrap mr5" style={{ width: '567px' }}>
                                  <Select
                                    menuPlacement={'auto'}
                                    id="long-value-select1"
                                    instanceId="long-value-select1"
                                    className="react-select-custom"
                                    classNamePrefix="custom"
                                    placeholder="Select"
                                    options={showSaleStoreList[0]}
                                    onChange={onSelectionChange}
                                    getOptionLabel={(x) => x.saleStoreName}
                                    getOptionValue={(x) => x.saleStoreId}
                                    isClearable={false}
                                    isDisabled={true}
                                    value={showSaleStoreList.filter(function (option) {
                                      if (option.firstAgentYn === 'Y') {
                                        return option.saleStoreId
                                      }
                                    })}
                                    // components={{ Option: CustomOption }}
                                  />
                                </div>
                                <div className="input-wrap" style={{ width: '216px' }}>
                                  <input
                                    type="text"
                                    className="input-light"
                                    value={form.watch('saleStoreId') || ''}
                                    {...form.register('saleStoreId')}
                                    readOnly
                                  />
                                </div>
                              </>
                            )}
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>
                          <div className="flx-box">
                            <div className="title">{getMessage('stuff.detail.otherSaleStoreId')}</div>
                            <div className="tooltips">
                              <span>{getMessage('stuff.detail.tooltip.saleStoreId')}</span>
                            </div>
                          </div>
                        </th>
                        <td>
                          <div className="flx-box">
                            <div className="select-wrap mr5" style={{ width: '567px' }}>
                              <Select
                                id="long-value-select2"
                                instanceId="long-value-select2"
                                className="react-select-custom"
                                classNamePrefix="custom"
                                placeholder="Select"
                                ref={ref}
                                options={otherSaleStoreList}
                                onChange={onSelectionChange2}
                                getOptionLabel={(x) => x.saleStoreName}
                                getOptionValue={(x) => x.saleStoreId}
                                isDisabled={
                                  managementState?.tempFlg === '0'
                                    ? true
                                    : session?.storeLvl === '1'
                                      ? otherSaleStoreList.length > 0
                                        ? false
                                        : true
                                      : otherSaleStoreList.length === 1
                                        ? true
                                        : false
                                }
                                isClearable={managementState?.tempFlg === '0' ? false : true}
                                value={otherSaleStoreList.filter(function (option) {
                                  return option.saleStoreId === otherSelOptions
                                })}
                                // components={{ Option: CustomOption2 }}
                              />
                            </div>
                            <div className="input-wrap" style={{ width: '216px' }}>
                              <input
                                type="text"
                                className="input-light"
                                value={form.watch('otherSaleStoreId') || ''}
                                {...form.register('otherSaleStoreId')}
                                readOnly
                              />
                            </div>
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>
                          {getMessage('stuff.detail.zipNo')} <span className="important">*</span>
                        </th>
                        <td>
                          <div className="flx-box">
                            <div className="input-wrap mr5" style={{ width: '200px' }}>
                              <input type="text" className="input-light" disabled value={form.watch('zipNo') || ''} />
                            </div>
                            <Button className="btn-origin grey" onPress={onSearchPostNumberPopOpen} style={{ display: showButton }}>
                              {getMessage('stuff.detail.btn.addressPop')}
                            </Button>
                            <div className="guide">{getMessage('stuff.detail.btn.addressPop.guide')}</div>
                          </div>
                        </td>
                      </tr>
                      {/* 도도부현 /주소 시작*/}
                      <tr>
                        <th>
                          {getMessage('stuff.detail.prefId')}
                          <span className="important">*</span>
                        </th>
                        <td>
                          <div className="flx-box">
                            <div className="select-wrap mr5" style={{ width: '200px' }}>
                              {prefCodeList?.length > 0 && (
                                <Select
                                  id="long-value-select3"
                                  instanceId="long-value-select3"
                                  className="react-select-custom"
                                  classNamePrefix="custom"
                                  placeholder="Select"
                                  options={prefCodeList}
                                  getOptionLabel={(x) => x.prefName}
                                  getOptionValue={(x) => x.prefId}
                                  isSearchable={false}
                                  value={prefCodeList.filter(function (option) {
                                    return option.prefId === prefValue
                                  })}
                                  isDisabled={true}
                                />
                              )}
                            </div>
                            <div className="input-wrap mr5" style={{ width: '580px' }}>
                              <input type="text" className="input-light" value={form.watch('address') || ''} {...form.register('address')} />
                            </div>
                          </div>
                        </td>
                      </tr>
                      {/* 도도부현 /주소 끝 */}
                      {/* 발전량시뮬레이션지역시작 */}
                      <tr>
                        <th>
                          {getMessage('stuff.detail.areaId')} <span className="important">*</span>
                        </th>
                        <td>
                          <div className="select-wrap" style={{ width: '200px' }}>
                            <Select
                              id="long-value-select4"
                              instanceId="long-value-select4"
                              className="react-select-custom"
                              classNamePrefix="custom"
                              options={areaIdList}
                              placeholder="Select"
                              getOptionLabel={(x) => x.prefName}
                              getOptionValue={(x) => x.areaId}
                              isSearchable={false}
                              onChange={handleAreaIdOnChange}
                              value={areaIdList.filter(function (option) {
                                return option.areaId === form.watch('areaId')
                              })}
                              isDisabled={areaIdList.length > 0 ? false : true}
                            />
                          </div>
                        </td>
                      </tr>
                      {/* 발전량시뮬레이션지역끝 */}
                      {/* 기준풍속시작 */}
                      <tr>
                        <th>
                          {getMessage('stuff.detail.standardWindSpeedId')} <span className="important">*</span>
                        </th>
                        <td>
                          <div className="flx-box">
                            <div className="select-wrap mr10" style={{ width: '200px' }}>
                              <Select
                                {...register('standardWindSpeedId')}
                                id="long-value-select5"
                                instanceId="long-value-select5"
                                className="react-select-custom"
                                classNamePrefix="custom"
                                placeholder="Select"
                                options={windSpeedList}
                                onChange={onChangeWindSpeedCode}
                                getOptionLabel={(x) => x.clCodeNm}
                                getOptionValue={(x) => x.clCode}
                                isClearable={true}
                                isSearchable={false}
                                value={windSpeedList.filter(function (option) {
                                  return option.clCode === watch('standardWindSpeedId')
                                })}
                              ></Select>
                            </div>
                            <span className="mr10">{getMessage('stuff.detail.standardWindSpeedIdSpan')}</span>
                            <Button type="button" className="btn-origin grey" onPress={onSearchWindSpeedPopOpen} style={{ display: showButton }}>
                              {getMessage('stuff.detail.btn.windSpeedPop')}
                            </Button>
                          </div>
                        </td>
                      </tr>
                      {/* 기준풍속끝 */}
                      {/* 수직적설량시작 */}
                      <tr>
                        <th>
                          {getMessage('stuff.detail.verticalSnowCover')} <span className="important">*</span>
                        </th>
                        <td>
                          <div className="flx-box">
                            <div className="input-wrap mr10" style={{ width: '200px' }}>
                              <input
                                type="text"
                                className="input-light"
                                onInput={handleKeyUp}
                                onBlur={handleBlur}
                                value={form.watch('verticalSnowCover') || ''}
                                {...register('verticalSnowCover')}
                              />
                            </div>
                            <span className="mr10">cm</span>
                            <div className="d-check-box light">
                              <input type="checkbox" id="coldRegionFlg" {...form.register('coldRegionFlg')} />
                              <label htmlFor="coldRegionFlg">{getMessage('stuff.detail.coldRegionFlg')}</label>
                            </div>
                          </div>
                        </td>
                      </tr>
                      {/* 수직적설량끝 */}
                      {/* 면조도구분시작 */}
                      <tr>
                        <th>
                          {getMessage('stuff.detail.surfaceType')} <span className="important">*</span>
                        </th>
                        <td>
                          <div className="flx-box">
                            <div className="radio-wrap flx-box" style={{ width: '239px' }}>
                              <div className="d-check-radio light mr10">
                                <input
                                  type="radio"
                                  name="surfaceType"
                                  value="Ⅲ・Ⅳ"
                                  id="surfaceType0"
                                  {...form.register('surfaceType')}
                                  onChange={(e) => {
                                    handleRadioChange(e)
                                  }}
                                />
                                <label htmlFor="surfaceType0">Ⅲ・Ⅳ</label>
                              </div>
                              <div className="d-check-radio light">
                                <input
                                  type="radio"
                                  name="surfaceType"
                                  value="Ⅱ"
                                  id="surfaceType1"
                                  {...form.register('surfaceType')}
                                  onChange={(e) => {
                                    handleRadioChange(e)
                                  }}
                                />
                                <label htmlFor="surfaceType1">Ⅱ</label>
                              </div>
                            </div>

                            <div className="d-check-box light mr5">
                              <input type="checkbox" id="saltAreaFlg" {...form.register('saltAreaFlg')} />
                              <label htmlFor="saltAreaFlg">{getMessage('stuff.detail.saltAreaFlg')}</label>
                            </div>
                            <div className="tooltips">
                              <span>{getMessage('stuff.detail.tooltip.surfaceType')}</span>
                            </div>
                          </div>
                        </td>
                      </tr>
                      {/* 면조도구분끝 */}
                      {/* 설치높이시작 */}
                      <tr>
                        <th>
                          {getMessage('stuff.detail.installHeight')} <span className="important">*</span>
                        </th>
                        <td>
                          <div className="flx-box">
                            <div className="input-wrap mr10" style={{ width: '200px' }}>
                              <input
                                type="text"
                                className="input-light"
                                onInput={handleKeyUp}
                                onBlur={handleBlur}
                                value={form.watch('installHeight') || ''}
                                {...register('installHeight')}
                              />
                            </div>
                            <span>m</span>
                          </div>
                        </td>
                      </tr>
                      {/* 설치높이끝 */}
                      {/* 계약조건시작 */}
                      <tr>
                        <th>{getMessage('stuff.detail.conType')}</th>
                        <td>
                          <div className="flx-box">
                            <div className="d-check-radio light mr10">
                              <input type="radio" name="conType" value="0" id="conType0" {...form.register('conType')} />
                              <label htmlFor="conType0">{getMessage('stuff.detail.conType0')}</label>
                            </div>
                            <div className="d-check-radio light mr10">
                              <input type="radio" name="conType" value="1" id="conType1" {...form.register('conType')} />
                              <label htmlFor="conType1">{getMessage('stuff.detail.conType1')}</label>
                            </div>
                          </div>
                        </td>
                      </tr>
                      {/* 계약조건끝 */}
                      {/* 메모시작 */}
                      <tr>
                        <th>{getMessage('stuff.detail.remarks')}</th>
                        <td>
                          <div className="input-wrap">
                            <input type="text" className="input-light" {...form.register('remarks')} value={form.watch('remarks') || ''} />
                          </div>
                        </td>
                      </tr>
                      {/* 메모끝 */}
                    </tbody>
                  </table>
                </div>
              </div>
              {managementState?.tempFlg === '0' ? (
                <>
                  {/* 진짜R 플랜시작 */}
                  <div className="table-box-title-wrap">
                    <div className="title-wrap">
                      <h3>{getMessage('stuff.detail.planList.title')}</h3>
                      <ul className="info-wrap">
                        <li>
                          {getMessage('stuff.detail.planList.cnt')}
                          <span className="red"> {managementState.planList?.length}</span>
                        </li>
                      </ul>
                    </div>
                  </div>
                  <div className="information-help-wrap">
                    <div className="information-help-tit-wrap">
                      <div className="help-tit-icon"></div>
                      <div className="help-tit">{getMessage('stuff.detail.planList.help')}</div>
                    </div>
                    <div className="information-help-guide">
                      <span>{getMessage('stuff.detail.planList.guide1')}</span>
                      <span>{getMessage('stuff.detail.planList.guide2')}</span>
                      <span>{getMessage('stuff.detail.planList.guide3')}</span>
                    </div>
                  </div>
                  <div className="information-grid">
                    <div className="q-grid no-cols">
                      <StuffPlanQGrid {...planGridProps} getCellDoubleClicked={getCellDoubleClicked} />
                    </div>
                  </div>
                  {/* 진짜R 플랜끝 */}
                  <div className="sub-right-footer">
                    {/* <Link href="/management/stuff" scroll={false}>
                      <button type="button" className="btn-origin grey mr5">
                        {getMessage('stuff.detail.btn.moveList')}
                      </button>
                    </Link> */}
                    <button
                      type="button"
                      className="btn-origin grey mr5"
                      onClick={() => {
                        setIsGlobalLoading(true)
                        router.push(`/management/stuff`, { scroll: false })
                      }}
                    >
                      {getMessage('stuff.detail.btn.moveList')}
                    </button>
                    <Button type="submit" className="btn-origin navy mr5" style={{ display: showButton }}>
                      {getMessage('stuff.detail.btn.save')}
                    </Button>
                    <Button type="button" className="btn-origin grey" onPress={onDelete} style={{ display: showButton }}>
                      {getMessage('stuff.detail.btn.delete')}
                    </Button>
                  </div>
                </>
              ) : (
                <>
                  <div className="sub-right-footer">
                    {!isFormValid ? (
                      <Button className="btn-origin grey mr5" onPress={onTempSave} style={{ display: showButton }}>
                        {getMessage('stuff.detail.btn.tempSave')}
                      </Button>
                    ) : (
                      <Button type="submit" className="btn-origin navy mr5" style={{ display: showButton }}>
                        {getMessage('stuff.detail.btn.save')}
                      </Button>
                    )}
                    {/* <Link href="/management/stuff" scroll={false}>
                      <button type="button" className="btn-origin grey">
                        {getMessage('stuff.detail.btn.moveList')}
                      </button>
                    </Link> */}
                    <button
                      type="button"
                      className="btn-origin grey"
                      onClick={() => {
                        setIsGlobalLoading(true)
                        router.push(`/management/stuff`, { scroll: false })
                      }}
                    >
                      {getMessage('stuff.detail.btn.moveList')}
                    </button>
                  </div>
                </>
              )}
            </div>
          </form>
        </>
      )}
      {showAddressButtonValid && <FindAddressPop setShowAddressButtonValid={setShowAddressButtonValid} zipInfo={setZipInfo} />}
      {showDesignRequestButtonValid && (
        <PlanRequestPop
          setShowDesignRequestButtonValid={setShowDesignRequestButtonValid}
          saleStoreId={form.watch('saleStoreId')}
          saleStoreLevel={form.watch('saleStoreLevel')}
          otherSaleStoreId={form.watch('otherSaleStoreId')}
          otherSaleStoreLevel={form.watch('otherSaleStoreLevel')}
          planReqInfo={setPlanReqInfo}
        />
      )}
      {showWindSpeedButtonValid && (
        <WindSelectPop setShowWindSpeedButtonValid={setShowWindSpeedButtonValid} prefName={form.watch('prefName')} windSpeedInfo={setWindSppedInfo} />
      )}

      {estimatePopupOpen && <DocDownOptionPop planNo={popPlanNo} setEstimatePopupOpen={setEstimatePopupOpen} />}
    </>
  )
}
