import {Table, DatePicker, Form, Button, Upload, ConfigProvider} from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import MenuDocuments from "./MenuDocuments"
import { FileService } from '../services/api'
import {useState, useEffect} from "react"
import {useParams} from 'react-router-dom'
import notify from './notify'
import LoaderPortal from './LoaderPortal'
import locale from "antd/lib/locale/ru_RU"
import moment from 'moment'

const pageSize = 12
const {RangePicker} = DatePicker;


export default function Documents({selectedFileCategory}) {
  let {id} = useParams()

  const [page, setPage] = useState(1)
  const [range, setRange] = useState([])
  const [pagination, setPagination] = useState(null)
  const [files, setFiles] = useState([])
  const [selectedFiles, setSelectedFiles] = useState([])
  const [isTableUpdating, setTableUpdating] = useState(false)

  const [loader, setLoader] = useState(false)
  const [form] = Form.useForm();

  const handleFileNameCLick = async (event, row) => {    
    const element = event.target

    if(!element.href.length) {
      try {
        setLoader(true)

        await fetch(`/api/files/${id}/${row.id}`, {
          headers: {
            Authorization: 'Bearer ' + localStorage['token']
          }
        })
        .then(async (response) => {
          const blob = await response.blob();
  
          let reader = new FileReader();
          reader.readAsDataURL(blob);
          reader.onload = function (e) {
            element.href = e.target.result
            element.click()
          };
          setLoader(false)
        });
      } catch (error) {
        notify(`Не удалось скачать файл ${row}`, 'error')
        console.log(error)
      }
    }
  }
  
  const columns = [
    {
        title: 'Документ',
        key: 'document',
        dataIndex: 'name',
        render: (name, row) => 
          <a onClick={ev => handleFileNameCLick(ev, row)} download={name}>{name}</a>
    },
    {
        title: 'Дата загрузки',
        key: 'uploadDate',
        dataIndex: 'uploadDate',
        render: (item) => moment.utc(item).local().format('DD MMM YYYY, HH:mm:ss')
    },
    {
        title: 'Ф.И.О.',
        key: 'userName',
        dataIndex: 'userName',
    }
  ];

  const submitFileFormProps = {
    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      strokeWidth: 3,
      format: percent => `${parseFloat(percent.toFixed(2))}%`,
    },
    onChange({ file, fileList }) {
      if (file.status !== 'uploading') {
        setSelectedFiles(fileList)
      }
    }
  }

  const onChangeRange = (range) => {
    setRange(range)
  }

  const onFinish = (values, form) => {
    var fileList = values.fileInput.fileList

    if (fileList.length > 0)
    {
      setLoader(true)
      const formData = new FormData();

      fileList.forEach(val => {
        formData.append('files', val.originFileObj)
      })

      fetch(`/api/files/${id}/files?idCategory=${selectedFileCategory}&idUser=${localStorage['userId']}`, {
        headers: {
          Authorization: 'Bearer ' + localStorage['token']
        },
        method: 'POST',
        body: formData
      })
      .then(async (response) => {
        setLoader(false)
        form.resetFields()
        setTableUpdating(true)
      });
    }
  }

  const onFinishFailed = (errorInfo) => {
    notify(`Не удалось отправить файлы по скважине "${id}".`, 'error')
  }

  useEffect(() => {
    const GetDocuments = async () => {
      setLoader(true)

      try {
        let begin = null
        let end = null
        if (range?.length > 1) {
          begin = range[0].toISOString()
          end = range[1].toISOString()
        }

        await FileService.getFilesInfo(
            `${id}`,
            (page - 1) * pageSize,
            pageSize,
            selectedFileCategory,
            begin,
            end
            ).then((paginatedFiles) => {
                setFiles(paginatedFiles?.items.map(f => {
                    return {
                        key: f.id,
                        begin: f.date,
                        ...f
                    }
                }))

                setPagination({
                    total: paginatedFiles?.count,
                    current: Math.floor(paginatedFiles?.skip / pageSize),
                })

                setTableUpdating(false)
                setLoader(false)
            }
        )
      } catch (ex) {
        notify(`Не удалось загрузить файлы по скважине "${id}"`, 'error')
        console.log(ex)
      }
    }
    GetDocuments()
  }, [id, range, selectedFileCategory, isTableUpdating])

  return (
    <div>
      <MenuDocuments/>
        <div className='filter-group'>
          <h3 className='filter-group-heading'>Фильтр документов:</h3>
          <ConfigProvider locale={locale}>
              <RangePicker
                  showTime
                  onChange={onChangeRange}
              />
          </ConfigProvider>
        </div>
        <LoaderPortal show={loader}></LoaderPortal>
        <div>&nbsp;</div>
        <Form
          form={form}
          name="DocumentsUploadForm"
          onFinish={(values) => onFinish(values, form)}
          onFinishFailed={onFinishFailed}
          style={{width: '300px'}}
        >
          <Form.Item
            name="fileInput"
            rules={[{ required: true, message: 'Выберите файл' }]}
          >
            <Upload {...submitFileFormProps}>
              <Button icon={<UploadOutlined />}>Загрузить файл</Button>
            </Upload>
          </Form.Item>
          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit"
              disabled={selectedFiles.length === 0}
            >
              Отправить
            </Button>
          </Form.Item>
        </Form>
      <div>&nbsp;</div>
      <Table
        columns={columns}
        dataSource={files}
        size={'small'}
        pagination={{
          pageSize: pageSize,
          showSizeChanger: false,
          total: pagination?.total,
          current: page,
          onChange: (page) => setPage(page)
        }}
        rowKey={(record) => record.id}
      />
    </div>);
}