// material-ui
import * as React from 'react';
import {
    GridActionsCellItem,
} from "@mui/x-data-grid";
import * as Icon from '../utils/IconUtils';
import * as HttpUtils from "../utils/HttpUtils"
import * as UrlUtils from "../utils/ApiPathConst"
import * as DateUtils from "../utils/DateUtils"
import { FiDataGrid } from './FiDataGrid';
import {useTheme} from "@emotion/react";
import {useMediaQuery} from "@mui/material";
import {useIntl} from "react-intl";
import { createDeleteFileColumn } from 'utils/fileListColumns';
import { CONTAINED_PRIMARY_BLUE } from "themes/colorConst";
// ==============================|| EVENT TABLE ||============================== //

export default function FileList({ refType, refId, allowDelete, sx, dateHideable,lang, ...props }) {
    const [rows, setRows] = React.useState([]);
    const [rowModesModel] = React.useState({});
    const theme = useTheme();
    const isMdOrLg = useMediaQuery(theme.breakpoints.up('md'));
    const intl = useIntl();
    const [onDownload, setOnDownload] = React.useState(false);

    React.useEffect(() => {
        loadData();
    }, []);

    const onDeleteClick = (fileId, skey, filename) => () => {
        HttpUtils.get(
            {
                url: UrlUtils.GET_FILE_DELETE,
                params: {
                    fileId: fileId,
                    skey: skey,
                    filename: filename
                },
                onSuccess: function () {
                    loadData();
                }
            }
        );
    };

    const onDownloadClick = (fileId, skey, filename) => () => {
        setOnDownload(true)
        HttpUtils.fileDownload({
            fileId: fileId,
            skey: skey,
            filename: filename,
            onResponse:()=>{
                setOnDownload(false)
            },
            onError:()=>{
                setOnDownload(false)
            }
        });
    };


    const loadData = () => {
      
            HttpUtils.post(
                {
                    url: UrlUtils.POST_FILE_LIST,
                    params: {
                        refType: refType,
                        refId:refId,
                    },
                    onSuccess: function (responseData) {
                        setRows(responseData.records);
                    }
                }
            );
    };

    const convertToStr = (bytes, decimals) => {
        if (bytes == 0) return '0 Bytes';
        var dm = decimals || 2,
            sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        let i = 0;
        i = Math.floor(Math.log(bytes) / Math.log(1024));
        return parseFloat((bytes / Math.pow(1024, i)).toFixed(dm)) + ' ' + sizes[i];
    }

    const columns = (dateHideable ?
        [
            {
                field: 'actions',
                type: 'actions',
                headerName: '',
                width: 50,
                cellClassName: 'actions',
                getActions: (params) => {
                    return [
                        <GridActionsCellItem
                            key="OutSave"
                            icon={<Icon.Download sx={{ color: CONTAINED_PRIMARY_BLUE }} />}
                            label="Download"
                            className="textPrimary"
                            onClick={onDownloadClick(params.id, params.row.skey, params.row.filename)}
                            disabled={onDownload}
                        />]
                },
            },
            {
                id: 'filename',
                field: 'filename',
                headerName: intl.formatMessage({id: 'fileName'}),
                width: isMdOrLg ? 'auto' : 400,
                flex: isMdOrLg ? 3 : undefined,
            },
            {
                id: 'filesize',
                field: 'filesize',
                headerName: intl.formatMessage({id: 'fileSize'}),
                width: isMdOrLg ? 'auto' : 160,
                flex: isMdOrLg ? 1 : undefined,
                valueGetter: (params) => {
                    return convertToStr(params.value);
                }
            }
        ]
        :
        [
            {
                id: 'created',
                field: 'created',
                headerName: lang=="ch"?"日期":'Created',
                width: isMdOrLg ? 'auto' : 160,
                flex: isMdOrLg ? 1 : undefined,
                valueGetter: (params) => {
                    return DateUtils.datetimeStr(params.value);
                }
            },
            {
                field: 'actions',
                type: 'actions',
                headerName: '',
                width: 50,
                cellClassName: 'actions',
                getActions: (params) => {
                    return [
                        <GridActionsCellItem
                            key="OutSave"
                            icon={<Icon.Download sx={{ color: CONTAINED_PRIMARY_BLUE }} />}
                            label="Download"
                            className="textPrimary"
                            onClick={onDownloadClick(params.id, params.row.skey, params.row.filename)}
                            disabled={onDownload}
                        />]
                },
            },
            {
                id: 'filename',
                field: 'filename',
                headerName: intl.formatMessage({id: 'fileName'}),
                width: isMdOrLg ? 'auto' : 400,
                flex: isMdOrLg ? 3 : undefined,
            },
            {
                id: 'filesize',
                field: 'filesize',
                headerName: intl.formatMessage({id: 'fileSize'}),
                width: isMdOrLg ? 'auto' : 160,
                flex: isMdOrLg ? 1 : undefined,
                valueGetter: (params) => {
                    return convertToStr(params.value);
                }
            },
        ]
    );



    if (allowDelete) {
        columns.push(createDeleteFileColumn(
            (id, row) => onDeleteClick(id, row.skey, row.filename),
            { icon: Icon.Delete, color: 'primary', width: 100 }
        ));
    }

    return (
        <FiDataGrid
            {...props}
            hideFooterSelectedRowCount={true}
            sx={sx}
            rows={rows}
            columns={columns}
            editMode="row"
            rowModesModel={rowModesModel}
            // initialState={{
            //     pagination: {
            //         paginationModel: { page: 0, pageSize: 5 },
            //     },
            // }}
            //pageSizeOptions={[5, 10]}
            customPageSize={100}
            autoHeight={true}

        />
    );
}
