import React, { useState, useEffect } from 'react';
import axios from 'axios';
import {
  CCard,
  CCardBody,
  CCardHeader,
  CCol,
  CRow,
  CDropdown,
  CDropdownDivider,
  CDropdownItem,
  CDropdownMenu,
  CDropdownToggle,
  /////
  CButton,
  CCardFooter,
  CForm,
  CFormGroup,
  CFormText,
  CTextarea,
  CInput,
  CInputFile,
  CInputCheckbox,
  CInputRadio,
  CLabel,
  CSelect,
  CSwitch,
} from  '@coreui/react'
import CIcon from '@coreui/icons-react'

import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

function Index() {

  const baseUrl = "https://openshield.ts.bizside.biz";


  const [data, setData] = useState([]);
  const [report, setReport] = useState('');
  const [selectedcons, setSelectedCons] = useState('');
  const [graph, setGraph] = useState(false);

  const [startDate, setStartDate] = useState(null);
  const [validDates, setValidDates] = useState([]);
  const [downloadUrl, setDownloadUrl] = useState('');

  useEffect(() => {
    async function fetchData() {
      // You can await here
      const result = await axios('https://openshield.ts.bizside.biz/getConstructionList');
      setData(result.data);
    }
    fetchData();
  }, []);

  useEffect(() => {
    async function fetchData() {
      // You can await here
      if(selectedcons !== "" && report !== "" && isDate() == true) {
        const result = await axios('https://openshield.ts.bizside.biz/getDateToHaveData?construction_id=' + selectedcons + '&sheetname=' + report);
        setValidDates(result.data.record);
      }
    }
    fetchData();
  }, [report, selectedcons]);

  function getDateWithFormat(date) {
    var thisDate = date;
    var dd = String(date.getDate()).padStart(2, '0');
    var mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = date.getFullYear();

    thisDate = yyyy + '-' + mm + '-' + dd
    return thisDate;
  }

  function setingReport(e){
    setReport(e.target.value);
    setStartDate(null);
    setDownloadUrl('');
  }

  function setingSelectedCons(e) {
    setSelectedCons(e.target.value);
    setStartDate(null);
    setDownloadUrl('');
  }

  function setingGraph(e){
    console.log("setting report" + downloadUrl);
    setGraph(e.target.checked);
    setDownloadUrl('');
    
  }

  function doGetReport(){
    console.log(isDownload());
    console.log(downloadUrl);
    if(report == "" || selectedcons == ""){
      alert("建設とレポートの両方を選択してください");
      return;
    }
    var url = "";
    if(startDate !== null){
      if(graph){
      url = baseUrl + "/generate" + report + "?construction_id=" +selectedcons+ "&construction_date="+getDateWithFormat(startDate)+"&graph=true";
      }
      else{
        url = baseUrl + "/generate" + report + "?construction_id=" +selectedcons+ "&construction_date="+getDateWithFormat(startDate);
      }
      setDownloadUrl(url);
      //downloadReport(url);
    }
    else {
      if(graph){
        url = baseUrl + "/generate" + report + "?construction_id=" +selectedcons+"&graph=true";
        }
        else{
          url = baseUrl + "/generate" + report + "?construction_id=" +selectedcons;
        }
        setDownloadUrl(url);
        //downloadReport(url);
    }
  }

  // function downloadReport(url)
  //   console.log(url);
  //   fetch(url)
  //   .then(response => {
  //     console.log(response)
  //     const filename =  response.headers.get('Content-Disposition').split('filename=')[1];
  //     response.blob().then(blob => {
  //       let url = window.URL.createObjectURL(blob);
  //       let a = document.createElement('a');
  //       a.href = url;
  //       a.download = filename;
  //       a.click();
  //     });
  //   });
  // }

  // function downloadReport(url) {
  //   axios({
  //     url: url, //your url
  //     method: 'GET',
  //     responseType: 'blob', // important
  //   }).then((response) => {
  //     //  const url = window.URL.createObjectURL(new Blob([response.data]));
  //     //  const link = document.createElement('a');
  //     //  link.href = url;
  //     //  //link.setAttribute('download', 'file.xls'); //or any other extension
  //     //  //document.body.appendChild(link);
  //     //  link.click();

  //     const filename = response.headers
  //         .get("content-disposition")
  //         .split('"')[1];
  //       const text = response.text();
  //       console.log(filename)
  //       console.log(text)
  //       //return { filename, text };
      
  //   });

  // }

  const checkAvilable = (date) => {
    if(validDates === undefined){
      return false;
    }
    var thisDate = getDateWithFormat(date);
    if(validDates.includes(thisDate)){
      return true;
    }
    else{
      return false;
    }
  };

  function isDownload() {
    if(isDate() === false && report !== '' && selectedcons !== '') {
      return true;
    }
    else{
      if(startDate !== null) {
        return true;
      }
    }
    return false;
  }

  function isDate() {
    if(report === 'BoxDisplacement' || report === 'MachineControl' || report === 'MachineSheet'){
      return true;
    }
    else {
      return false;
    }
  }

  return (
    <CRow>
      <CCol xs="12" sm="12" md="12">
        <CCard>
          <CCardHeader>
          レポート
          </CCardHeader>
          <CCardBody>

    <CSelect custom name="cons_select" id="cons_select" onChange={setingSelectedCons}>
      " <option value=''>-- 工事名 --</option>"+
      {
        data.map((cc, index) => {
          return(
            <option key={cc.construction_id} value={cc.construction_id}>{cc.construction_name}</option>
          )
        })
      }
    </CSelect>

  <CCard>
            <CCardBody>
              <CForm action="" method="post" encType="multipart/form-data" className="form-horizontal">
                <CFormGroup row>
                  <CCol md="3">
                    <CLabel htmlFor="select">レポート種類</CLabel>
                  </CCol>
                  <CCol xs="12" md="9">
                    <CSelect custom name="select" id="select" onChange={setingReport} value={report}>
                      <option value="">-- レポート種類 --</option>
                      <option value="BoxDisplacement">函体変位表</option>
                      <option value="MachineControl">オープンシールドマシン管理日報</option>
                      <option value="Measurement">函底高・偏位量測定一覧表</option>
                      <option value="CheckSheet">工程内検査表</option>
                      <option value="Injection">裏込注入材料受払い簿</option>
                    </CSelect>
                  </CCol>
                </CFormGroup>
                {isDate() === true ? 
                <CFormGroup row>
                <CCol md="3">
                  <CLabel htmlFor="select">報告日</CLabel>
                </CCol>
                <CCol xs="12" md="9">
                <DatePicker
                  dateFormat="yyyy/MM/dd"
                  selected={startDate}
                  onChange={(date) => setStartDate(date)}
                  filterDate={checkAvilable}
                  placeholderText='日付を選択'
                  />
                </CCol>
              </CFormGroup>
              :
              <div></div>
                }

  {report == 'MachineControl' ?
    <CFormGroup variant="checkbox" className="checkbox">
      <CInputCheckbox
        id="checkbox1"
        name="checkbox1"
        checked = {graph}
        value='graph'
        onChange={setingGraph}
      />
      <CLabel variant="checkbox" className="form-check-label" htmlFor="checkbox1">グラフの有無</CLabel>
    </CFormGroup>
   :
  ("")}

              </CForm>
            </CCardBody>
            <CCardFooter>
            {isDownload() === true ?
            <p>
            <CButton type="submit" size="sm" color="primary"  onClick={doGetReport}><CIcon name="cil-scrubber" /> ダウンロード</CButton>
            <br/>
            {downloadUrl === '' ?
            <p></p>
            :
            <a href={downloadUrl}>Download</a>
            }
            </p>
            :
              <CButton disabled type="submit" size="sm" color="primary"  onClick={doGetReport}><CIcon name="cil-scrubber" /> ダウンロード</CButton>
            }
            </CCardFooter>
          </CCard>
          </CCardBody>
        </CCard>
      </CCol>
      <CCol xs="1" sm="1" md="1">
      </CCol>
    </CRow>
  );
}

export default Index
