'use client'
import { useState } from 'react'
import { useMessage } from '@/hooks/useMessage'
import { useAxios } from '@/hooks/useAxios'
import { useRecoilValue } from 'recoil'
import { floorPlanObjectState } from '@/store/floorPlanObjectAtom'

export default function DocDownOptionPop({ planNo, setEstimatePopupOpen }) {
  const { getMessage } = useMessage()
  const { promisePost } = useAxios()

  //EXCEL, PDF 구분
  const [schDownload, setSchDownload] = useState('EXCEL')
  //다운로드 파일 EXCEL
  const [schUnitPriceFlg, setSchUnitPriceFlg] = useState('0')
  //견적제출서 표시명
  const [schDisplayFlg, setSchSchDisplayFlg] = useState('0')
  //가대 중량표 포함(포함:1 미포함 : 0)
  const [schWeightFlg, setSchWeightFlg] = useState('1')
  //도면/시뮬레이션 파일 포함
  const [schDrawingFlg, setSchDrawingFlg] = useState('1')

  // recoil 물건번호
  const objectRecoil = useRecoilValue(floorPlanObjectState)

  //문서 다운로드
  const handleFileDown = async () => {
    const url = '/api/estimate/excel-download'
    let sendUnitPriceFlg
    if (schUnitPriceFlg === '0') {
      sendUnitPriceFlg = '0'
    } else if (schUnitPriceFlg === '1') {
      sendUnitPriceFlg = '1'
    } else if (schUnitPriceFlg === '2') {
      sendUnitPriceFlg = '0'
    } else {
      sendUnitPriceFlg = '1'
    }

    //schDrawingFlg 선택값은 의미없어짐
    //가대중량표 포함, 도면/시뮬레이션 파일 포함 선택값에따라 schDrawingFlg에 |구분자로 보냄
    //SchDrawingFlg (1 : 견적서,2 : 발전시뮬레이션, 3 : 도면, 4 : 가대)
    // ex) 1|2|3|4
    let defaultSchDrawingFlg = '1'
    if (schWeightFlg === '1') {
      defaultSchDrawingFlg = defaultSchDrawingFlg.concat('|', '4')
    }
    if (schDrawingFlg === '1') {
      defaultSchDrawingFlg = defaultSchDrawingFlg.concat('|', '3')
    }

    const params = {
      objectNo: objectRecoil.floorPlanObjectNo,
      planNo: planNo,
      schDownload: schDownload,
      schUnitPriceFlg: sendUnitPriceFlg,
      schDisplayFlg: schDisplayFlg,
      schWeightFlg: schWeightFlg,
      schDrawingFlg: defaultSchDrawingFlg,
      pwrGnrSimType: 'D', //default 화면에 안보여줌
    }

    const options = { responseType: 'blob' }
    await promisePost({ url: url, data: params, option: options })
      .then((resultData) => {
        if (resultData) {
          let fileName = 'unknow'
          const blob = new Blob([resultData.data], { type: resultData.headers['content-type'] || 'application/octet-stream' })
          const fileUrl = window.URL.createObjectURL(blob)

          const link = document.createElement('a')
          link.href = fileUrl

          //서버에서 내려오는 파일명
          const contentDisposition = resultData.headers['content-disposition']
          if (contentDisposition) {
            fileName = contentDisposition.split('filename=')[1].replace(/['"]/g, '')
          }

          link.download = fileName
          document.body.appendChild(link)
          link.click()
          link.remove()
          window.URL.revokeObjectURL(fileUrl)
        }
      })
      .catch((error) => {
        console.log('::FileDownLoad Error::', error)
        alert('File does not exist.')
      })
  }

  return (
    <div className="modal-popup">
      <div className="modal-dialog middle">
        <div className="modal-content">
          <div className="modal-header">
            <h1 className="title">{getMessage('estimate.detail.docPopup.title')}</h1>
            <button
              type="button"
              className="modal-close"
              onClick={() => {
                setEstimatePopupOpen(false)
              }}
            >
              {getMessage('estimate.detail.docPopup.close')}
            </button>
          </div>
          <div className="modal-body">
            <div className="modal-body-inner">
              <div className="explane">{getMessage('estimate.detail.docPopup.explane')}</div>
              <div className="common-table">
                <table>
                  <colgroup>
                    <col style={{ width: '260px' }} />
                    <col />
                  </colgroup>
                  <tbody>
                    <tr>
                      <th>
                        {getMessage('estimate.detail.docPopup.schUnitPriceFlg')}
                        <span className="red">*</span>
                      </th>
                      <td>
                        <div className="form-flex-wrap">
                          <div className="d-check-radio light mr10">
                            <input
                              type="radio"
                              id="schUnitPriceExcelFlg0"
                              name="schUnitPriceFlg"
                              value={'0'}
                              checked={schUnitPriceFlg === '0'}
                              onChange={(e) => {
                                setSchDownload('EXCEL')
                                setSchUnitPriceFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schUnitPriceExcelFlg0">{getMessage('estimate.detail.docPopup.schUnitPriceFlg.excelFlg0')}</label>
                          </div>
                          <div className="d-check-radio light mr10">
                            <input
                              type="radio"
                              id="schUnitPriceExcelFlg1"
                              name="schUnitPriceFlg"
                              value={'1'}
                              checked={schUnitPriceFlg === '1'}
                              onChange={(e) => {
                                setSchDownload('EXCEL')
                                setSchUnitPriceFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schUnitPriceExcelFlg1">{getMessage('estimate.detail.docPopup.schUnitPriceFlg.excelFlg1')}</label>
                          </div>
                          <div className="d-check-radio light mr10">
                            <input
                              type="radio"
                              id="schUnitPricePdfFlg0"
                              name="schUnitPriceFlg"
                              value={'2'}
                              checked={schUnitPriceFlg === '2'}
                              onChange={(e) => {
                                setSchDownload('PDF')
                                setSchUnitPriceFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schUnitPricePdfFlg0">{getMessage('estimate.detail.docPopup.schUnitPriceFlg.pdfFlg0')}</label>
                          </div>
                          <div className="d-check-radio light ">
                            <input
                              type="radio"
                              id="schUnitPricePdfFlg1"
                              name="schUnitPriceFlg"
                              value={'3'}
                              checked={schUnitPriceFlg === '3'}
                              onChange={(e) => {
                                setSchDownload('PDF')
                                setSchUnitPriceFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schUnitPricePdfFlg1">{getMessage('estimate.detail.docPopup.schUnitPriceFlg.pdfFlg1')}</label>
                          </div>
                        </div>
                      </td>
                    </tr>
                    <tr>
                      <th>
                        {getMessage('estimate.detail.docPopup.schDisplayFlg')} <span className="red">*</span>
                      </th>
                      <td>
                        <div className="form-flex-wrap">
                          <div className="d-check-radio light mr10">
                            <input
                              type="radio"
                              name="schDisplayFlg"
                              id="schDisplayFlg0"
                              value={'0'}
                              checked={schDisplayFlg === '0'}
                              onChange={(e) => {
                                setSchSchDisplayFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schDisplayFlg0">{getMessage('estimate.detail.docPopup.schDisplayFlg.schDisplayFlg0')}</label>
                          </div>
                          <div className="d-check-radio light">
                            <input
                              type="radio"
                              name="schDisplayFlg"
                              id="schDisplayFlg1"
                              value={'1'}
                              checked={schDisplayFlg === '1'}
                              onChange={(e) => {
                                setSchSchDisplayFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schDisplayFlg1">{getMessage('estimate.detail.docPopup.schDisplayFlg.schDisplayFlg1')}</label>
                          </div>
                        </div>
                      </td>
                    </tr>
                    <tr>
                      <th>
                        {getMessage('estimate.detail.docPopup.schWeightFlg')} <span className="red">*</span>
                      </th>
                      <td>
                        <div className="form-flex-wrap">
                          <div className="d-check-radio light mr10">
                            <input
                              type="radio"
                              name="schWeightFlg"
                              id="schWeightFlg1"
                              value={'1'}
                              checked={schWeightFlg === '1'}
                              onChange={(e) => {
                                setSchWeightFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schWeightFlg1">{getMessage('estimate.detail.docPopup.schWeightFlg.schWeightFlg1')}</label>
                          </div>
                          <div className="d-check-radio light">
                            <input
                              type="radio"
                              name="schWeightFlg"
                              id="schWeightFlg0"
                              value={'0'}
                              checked={schWeightFlg === '0'}
                              onChange={(e) => {
                                setSchWeightFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schWeightFlg0">{getMessage('estimate.detail.docPopup.schWeightFlg.schWeightFlg0')}</label>
                          </div>
                        </div>
                      </td>
                    </tr>
                    <tr>
                      <th>{getMessage('estimate.detail.docPopup.schDrawingFlg')}</th>
                      <td>
                        <div className="form-flex-wrap">
                          <div className="d-check-radio light mr10">
                            <input
                              type="radio"
                              name="schDrawingFlg"
                              id="schDrawingFlg1"
                              value={'1'}
                              checked={schDrawingFlg === '1'}
                              onChange={(e) => {
                                setSchDrawingFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schDrawingFlg1">{getMessage('estimate.detail.docPopup.schDrawingFlg.schDrawingFlg1')}</label>
                          </div>
                          <div className="d-check-radio light">
                            <input
                              type="radio"
                              name="schDrawingFlg"
                              id="schDrawingFlg0"
                              value={'0'}
                              checked={schDrawingFlg === '0'}
                              onChange={(e) => {
                                setSchDrawingFlg(e.target.value)
                              }}
                            />
                            <label htmlFor="schDrawingFlg0">{getMessage('estimate.detail.docPopup.schDrawingFlg.schDrawingFlg0')}</label>
                          </div>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <div className="footer-btn-wrap">
              <button
                type="button"
                className="btn-origin grey mr5"
                onClick={() => {
                  setEstimatePopupOpen(false)
                }}
              >
                {getMessage('estimate.detail.docPopup.close')}
              </button>
              <button type="button" className="btn-origin navy" onClick={() => handleFileDown()}>
                {getMessage('estimate.detail.docPopup.docDownload')}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
