import { useEffect, useState, useRef } from 'react'
import { useAxios } from '@/hooks/useAxios'
import { globalLocaleStore } from '@/store/localeAtom'
import { useRecoilValue } from 'recoil'
import { useMessage } from '@/hooks/useMessage'
import { isNotEmptyArray } from '@/util/common-utils'
import SingleDatePicker from '@/components/common/datepicker/SingleDatePicker'
import dayjs from 'dayjs'
import PlanRequestPopQGrid from './PlanRequestPopQGrid'
import { isObjectNotEmpty, queryStringFormatter } from '@/util/common-utils'
import { useCommonCode } from '@/hooks/common/useCommonCode'
import Select from 'react-select'
import QPagination from '@/components/common/pagination/QPagination'
export default function PlanRequestPop(props) {
  const [pageNo, setPageNo] = useState(1) //현재 페이지 번호
  const [pageSize, setPageSize] = useState(20) //페이지 당 게시물 개수
  const [totalCount, setTotalCount] = useState(0) //총 갯수

  //공통코드
  const { commonCode, findCommonCode } = useCommonCode()

  const [planStatCdList, setPlanStatCdList] = useState([])

  const globalLocaleState = useRecoilValue(globalLocaleStore)

  const [planReqObject, setPlanReqObject] = useState({})

  const { promiseGet } = useAxios(globalLocaleState)

  const { getMessage } = useMessage()
  //Select ref
  const ref = useRef()
  // 검색조건 달력 셋팅
  const [startDate, setStartDate] = useState(dayjs(new Date()).add(-3, 'month').format('YYYY-MM-DD'))
  const [endDate, setEndDate] = useState(dayjs(new Date()).format('YYYY-MM-DD'))

  const rangeDatePickerProps1 = {
    startDate, //시작일
    setStartDate,
  }

  const rangeDatePickerProps2 = {
    startDate: endDate, //종료일
    setStartDate: setEndDate,
  }

  const [schPlanReqNo, setSchPlanReqNo] = useState('') //설계의뢰번호
  const [schTitle, setSchTitle] = useState('') //안건명
  const [schAddress, setSchAddress] = useState('') //도도부현
  const [schSaleStoreName, setSchSaleStoreName] = useState('') //판매대리점명
  const [schPlanReqName, setSchPlanReqName] = useState('') //의뢰자명
  const [schPlanStatCd, setSchPlanStatCd] = useState('') //상태코드
  const [schDateGbn, setSchDateGbn] = useState('S') //기간구분코드(S/R)

  //초기화
  const resetRecoil = () => {
    setSchPlanReqNo('')
    setSchTitle('')
    setSchAddress('')
    setSchSaleStoreName('')
    setSchPlanReqName('')
    setSchDateGbn('S')
    setStartDate(dayjs(new Date()).add(-3, 'month').format('YYYY-MM-DD'))
    setEndDate(dayjs(new Date()).format('YYYY-MM-DD'))
    setSchPlanStatCd('')
    handleClear() //셀렉트 자동완성 초기화
  }

  //셀렉트 자동완성 초기화
  const handleClear = () => {
    if (ref.current) {
      ref.current.clearValue()
    }
  }

  // 상태 검색조건 변경
  const onSelectionChange = (key) => {
    if (isObjectNotEmpty(key)) {
      setSchPlanStatCd(key.clCode)
    } else {
      //X누름
      setSchPlanStatCd('')
    }
  }

  // 조회
  const onSubmit = (page, type) => {
    //2차점 테스트 201X112
    const params = {
      // saleStoreId: 'T100',
      // saleStoreLevel: '1',
      saleStoreId: props?.otherSaleStoreId ? props.otherSaleStoreId : props.saleStoreId,
      saleStoreLevel: props?.otherSaleStoreLevel ? props.otherSaleStoreLevel : props.saleStoreLevel,
      schPlanReqNo: schPlanReqNo,
      schTitle: schTitle,
      schAddress: schAddress,
      schSaleStoreName: schSaleStoreName,
      schPlanReqName: schPlanReqName,
      schPlanStatCd: schPlanStatCd,
      schDateGbn: schDateGbn,
      schStartDt: dayjs(startDate).format('YYYY-MM-DD'),
      schEndDt: dayjs(endDate).format('YYYY-MM-DD'),
      startRow: type === 'S' ? (1 - 1) * pageSize + 1 : (page - 1) * pageSize + 1,
      endRow: type === 'S' ? 1 * pageSize : page * pageSize,
    }
    if (type === 'S') {
      setPageNo(1)
    } else {
      setPageNo(page)
    }

    const apiUrl = `/api/object/planReq/list?${queryStringFormatter(params)}`
    promiseGet({ url: apiUrl }).then((res) => {
      if (res.status === 200) {
        if (isNotEmptyArray(res.data.data)) {
          setGridProps({ ...gridProps, gridData: res.data.data, gridCount: res.data.data[0].totCnt })
          setTotalCount(res.data.data[0].totCnt)
        } else {
          setGridProps({ ...gridProps, gridData: [], gridCount: 0 })
          setTotalCount(0)
        }
      } else {
        setGridProps({ ...gridProps, gridData: [], gridCount: 0 })
        setTotalCount(0)
      }
    })
  }
  // 페이징 현재페이지 변경
  const handleChangePage = (page) => {
    setPageNo(page)

    onSubmit(page, 'P')
  }

  //페이지 갯수 변경 이벤트
  const onChangePerPage = (e) => {
    const params = {
      // saleStoreId: 'T100',
      // saleStoreLevel: '1',
      saleStoreId: props?.otherSaleStoreId ? props.otherSaleStoreId : props.saleStoreId,
      saleStoreLevel: props?.otherSaleStoreLevel ? props.otherSaleStoreLevel : props.saleStoreLevel,
      schTitle: schTitle,
      schAddress: schAddress,
      schPlanReqNo: schPlanReqNo,
      schSaleStoreName: schSaleStoreName,
      schPlanReqName: schPlanReqName,
      schPlanStatCd: schPlanStatCd,
      schDateGbn: schDateGbn,
      schStartDt: dayjs(startDate).format('YYYY-MM-DD'),
      schEndDt: dayjs(endDate).format('YYYY-MM-DD'),
      startRow: (1 - 1) * e.target.value + 1,
      endRow: 1 * e.target.value,
    }

    setPageSize(e.target.value)
    setPageNo(1)

    const apiUrl = `/api/object/planReq/list?${queryStringFormatter(params)}`
    promiseGet({ url: apiUrl }).then((res) => {
      if (res.status === 200) {
        if (isNotEmptyArray(res.data.data)) {
          setGridProps({ ...gridProps, gridData: res.data.data, gridCount: res.data.data[0].totCnt })
          setTotalCount(res.data.data[0].totCnt)
        } else {
          setGridProps({ ...gridProps, gridData: [], gridCount: 0 })
          setTotalCount(0)
        }
      } else {
        setGridProps({ ...gridProps, gridData: [], gridCount: 0 })
        setTotalCount(0)
      }
    })
  }

  const [gridProps, setGridProps] = useState({
    gridData: [],
    isPageable: false,
    gridColumns: [
      {
        field: 'planStatName',
        headerName: getMessage('stuff.planReqPopup.gridHeader.planStatName'),
        minWidth: 150,
        checkboxSelection: true,
        showDisabledCheckboxes: true,
      },
      {
        field: 'planReqNo',
        headerName: getMessage('stuff.planReqPopup.gridHeader.planReqNo'),
        minWidth: 150,
      },
      {
        field: 'saleStoreId',
        headerName: getMessage('stuff.planReqPopup.gridHeader.saleStoreId'),
        minWidth: 150,
      },
      {
        field: 'saleStoreName',
        headerName: getMessage('stuff.planReqPopup.gridHeader.saleStoreName'),
        minWidth: 150,
      },
      {
        field: 'title',
        headerName: getMessage('stuff.planReqPopup.gridHeader.title'),
        minWidth: 150,
      },
      {
        field: 'address1',
        headerName: getMessage('stuff.planReqPopup.gridHeader.address1'),
        minWidth: 150,
      },
      {
        field: 'houseCntName',
        headerName: getMessage('stuff.planReqPopup.gridHeader.houseCntName'),
        minWidth: 150,
      },
      {
        field: 'planReqName',
        headerName: getMessage('stuff.planReqPopup.gridHeader.planReqName'),
        minWidth: 150,
      },
      {
        field: 'submitDt',
        headerName: getMessage('stuff.planReqPopup.gridHeader.submitDt'),
        minWidth: 150,
      },
    ],
  })

  //설계의뢰 그리드에서 선택한 설계의로 정보
  const getSelectedRowdata = (data) => {
    if (isNotEmptyArray(data)) {
      setPlanReqObject(data[0])
    } else {
      setPlanReqObject({})
    }
  }

  // 설계의뢰 적용 클릭
  const applyPlanReq = () => {
    if (isObjectNotEmpty(planReqObject)) {
      props.planReqInfo(planReqObject)
      // 팝업닫기
      props.setShowDesignRequestButtonValid(false)
    } else {
      alert(getMessage('stuff.planReqPopup.error.message1'))
    }
  }

  useEffect(() => {
    const code1 = findCommonCode(115800) //상태
    if (code1 != null) {
      setPlanStatCdList(code1)
    }
  }, [commonCode])

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

  // 엔터 이벤트
  const handleByOnKeyUp = (e) => {
    if (e.key === 'Enter') {
      onSubmit(pageNo, 'S')
    }
  }

  return (
    <div className="modal-popup">
      <div className="modal-dialog big">
        <div className="modal-content">
          <div className="modal-header">
            <h1 className="title">{getMessage('stuff.planReqPopup.title')}</h1>
            <button className="modal-close" onClick={() => props.setShowDesignRequestButtonValid(false)}>
              닫기
            </button>
          </div>
          <div className="modal-body">
            <div className="modal-body-inner">
              <div className="design-tit-wrap">
                <h3>{getMessage('stuff.planReqPopup.popTitle')}</h3>
                <div className="design-search-wrap">
                  <button
                    className="btn-origin navy mr5"
                    onClick={() => {
                      onSubmit(pageNo, 'S')
                    }}
                  >
                    {getMessage('stuff.planReqPopup.btn1')}
                  </button>
                  <button className="btn-origin grey" onClick={resetRecoil}>
                    {getMessage('stuff.planReqPopup.btn2')}
                  </button>
                </div>
              </div>
              <div className="design-request-table">
                <div className="common-table">
                  <table>
                    <colgroup>
                      <col style={{ width: '160px' }} />
                      <col />
                      <col style={{ width: '160px' }} />
                      <col />
                      <col style={{ width: '160px' }} />
                      <col />
                    </colgroup>
                    <tbody>
                      <tr>
                        <th>{getMessage('stuff.planReqPopup.search.planReqNo')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={schPlanReqNo}
                              onKeyUp={handleKeyUp}
                              onChange={(e) => {
                                setSchPlanReqNo(e.target.value)
                              }}
                            />
                          </div>
                        </td>
                        <th>{getMessage('stuff.planReqPopup.search.title')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={schTitle}
                              onChange={(e) => {
                                setSchTitle(e.target.value)
                              }}
                              onKeyUp={handleByOnKeyUp}
                            />
                          </div>
                        </td>
                        <th>{getMessage('stuff.planReqPopup.search.address1')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={schAddress}
                              onChange={(e) => {
                                setSchAddress(e.target.value)
                              }}
                              onKeyUp={handleByOnKeyUp}
                            />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('stuff.planReqPopup.search.saleStoreName')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={schSaleStoreName}
                              onChange={(e) => {
                                setSchSaleStoreName(e.target.value)
                              }}
                              onKeyUp={handleByOnKeyUp}
                            />
                          </div>
                        </td>
                        <th>{getMessage('stuff.planReqPopup.search.planReqName')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={schPlanReqName}
                              onChange={(e) => {
                                setSchPlanReqName(e.target.value)
                              }}
                              onKeyUp={handleByOnKeyUp}
                            />
                          </div>
                        </td>
                        <th>{getMessage('stuff.planReqPopup.search.planStatName')}</th>
                        <td>
                          <div className="select-wrap">
                            <Select
                              id="long-value-select1"
                              instanceId="long-value-select1"
                              className="react-select-custom"
                              classNamePrefix="custom"
                              ref={ref}
                              options={planStatCdList}
                              onChange={onSelectionChange}
                              getOptionLabel={(x) => x.clCodeNm}
                              getOptionValue={(x) => x.clCode}
                              isSearchable={false}
                              placeholder="Select"
                              isClearable={true}
                            />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('stuff.planReqPopup.search.period')}</th>
                        <td colSpan={5}>
                          <div className="form-flex-wrap">
                            <div className="radio-wrap mr10">
                              <div className="d-check-radio light mr10">
                                <input
                                  type="radio"
                                  name="radio04"
                                  id="ra07"
                                  checked={schDateGbn === 'S' ? true : false}
                                  value={'S'}
                                  onChange={(e) => {
                                    setSchDateGbn(e.target.value)
                                  }}
                                />
                                <label htmlFor="ra07">{getMessage('stuff.planReqPopup.search.schDateGbnS')}</label>
                              </div>
                              <div className="d-check-radio light">
                                <input
                                  type="radio"
                                  name="radio04"
                                  id="ra08"
                                  checked={schDateGbn === 'R' ? true : false}
                                  value={'R'}
                                  onChange={(e) => {
                                    setSchDateGbn(e.target.value)
                                  }}
                                />
                                <label htmlFor="ra08">{getMessage('stuff.planReqPopup.search.schDateGbnR')}</label>
                              </div>
                            </div>
                            <div className="date-picker-wrap">
                              <div className="date-picker" style={{ flex: 1 }}>
                                <SingleDatePicker {...rangeDatePickerProps1} />
                              </div>
                              <span> ~ </span>
                              <div className="date-picker" style={{ flex: 1 }}>
                                <SingleDatePicker {...rangeDatePickerProps2} />
                              </div>
                            </div>
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <div className="design-request-grid">
                <div className="design-request-count">
                  <div className="design-request-grid-tit">Plan List</div>
                  <div className="select-wrap">
                    <select className="select-light" onChange={onChangePerPage}>
                      <option>20</option>
                      <option>40</option>
                      <option>60</option>
                    </select>
                  </div>
                </div>
                <PlanRequestPopQGrid {...gridProps} getSelectedRowdata={getSelectedRowdata} />
                <div className="pagination-wrap">
                  <QPagination pageNo={pageNo} pageSize={pageSize} pagePerBlock={10} totalCount={totalCount} handleChangePage={handleChangePage} />
                </div>
              </div>
            </div>
            <div className="footer-btn-wrap">
              <button className="btn-origin grey mr5" onClick={() => props.setShowDesignRequestButtonValid(false)}>
                {getMessage('stuff.planReqPopup.btn3')}
              </button>
              <button className="btn-origin navy" onClick={applyPlanReq}>
                {getMessage('stuff.planReqPopup.btn4')}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
