import React, { useState, useEffect, memo } from "react";
import {
    Table,
    Divider,
    Card,
    Button,
    Typography,
    Spin,
    Row,
    Col,
    Tooltip,
    Rate,
    Image,
    message,
    Section
} from "antd";
import { doFetch, postFetch } from "@/utils/doFetch";
import AutoTable from "@/components/Tableform";
import { useModel } from 'umi'
import styles from "./index.less";
import PrintProvider, { Print, NoPrint } from 'react-easy-print';

const Details = (props) => {
    /**
     * dataSource: 整个页面的数据，Object
     * totalPath: 整个详情页的接口，String
     * totalParams: 整个详情页接口的参数
     * totalCard: 整个页面的模块，Array
     * col: 列数
     *
     * totalCard中的每一项变量：cardTitle每一个模块的标题；itemData每一个模块的数据信息（Array）
     * itemData中的每一项变量：key所对应的字段；title每一项label标题；type每一项的类型（file，img，textarea，table，不填默认就是普通的展示类型）；col每一项的占比；columns表格类型所用；path当类型为表格时，若该表格是单独查询出来的可以填入path；urlName 当传入文件为url为字符串时
     *
     */
    const {
        totalPath = "",
        dataSource,
        totalCard,
        totalParams,
        col,
        bottomNode,
        topNode,
        printRef,
        onloadeddata,
    } = props;
    const [pageData, cp] = useState({});

    const { initialState, setInitialState } = useModel("@@initialState");

    useEffect(() => {
        if (dataSource) {
            cp(dataSource);
        } else if (!dataSource && !Array.isArray(totalPath)) {
            doFetch({
                url: totalPath,
                params: totalParams ? { ...totalParams } : {},
            }).then((res) => {
                if (res.code == "0000") {
                    if (!res.data) {
                        return;
                    }
                    cp(res?.data?.data);
                }
            });
        }
    }, []);

    useEffect(() => {
        onloadeddata?.(pageData);
    }, [pageData])


    const getCol = (itemcol) => {
        if (itemcol) {
            return itemcol;
        } else {
            return col ? col : { xs: 24, sm: 24, md: 12, lg: 8, xl: 8, xxl: 6 };
        }
    };
    //获取每一项
    const getItem = (itemData) => {
        const {
            type,
            key,
            title,
            columns,
            path,
            urlName,
            col,
            rowKey,
            expandable,
            pagination
        } = itemData,
            value = pageData[key];
        if (!type || type == "input") {
            return value == 0 || value ? (
                <Tooltip title={`${title}：${value}`}>
                    <pre className={col ? "" : styles.one}>{value}</pre>
                </Tooltip>
            ) : (
                <div>-</div>
            );
        } else if (type == "file") {
            return (
                <div style={{ display: "flex", flexFlow: "row wrap", width: "100%" }}>
                    {value && typeof value == "string" ? (
                        <a
                            href={value}
                            download={value}
                            style={{ margin: "0 10px 0 0", display: "block" }}
                        >
                            {urlName ? urlName : "下载"}
                        </a>
                    ) : value && Array.isArray(value) && value?.length ? (
                        value?.map((el) => {
                            return (
                                <a
                                    key={el.url}
                                    href={el.url}
                                    download={el.name}
                                    style={{ margin: "0 10px 0 0", display: "block" }}
                                >
                                    {el.name}
                                </a>
                            );
                        })
                    ) : (
                        "-"
                    )}
                </div>
            );
        } else if (type == "img") {
            return (
                <div style={{ display: "flex", flexFlow: "row wrap" }}>
                    {value && value?.length
                        ? value?.map((el) => {
                            return (
                                <Image
                                    style={{ margin: "0 10px 0 0" }}
                                    src={el?.url}
                                    width={30}
                                    height={30}
                                    key={el?.uid}
                                ></Image>
                            );
                        })
                        : "-"}
                </div>
            );
        } else if (type == "table") {
            return (
                value &&
                <AutoTable
                    columns={columns || []}
                    path={path ? path : null}
                    bordered={false}
                    dataSource={path ? null : value}
                    rowKey={rowKey ?? "id"}
                    expandable={expandable ? {
                        ...expandable,
                        defaultExpandedRowKeys: value?.map(it => it.id)
                    } : null}
                    pagination={pagination}
                ></AutoTable>
            );
        } else if (type == "rate") {
            return (
                <Rate
                    bordered={false}
                    className={"simple"}
                    style={{ width: "100%" }}
                    disabled={itemData.disabled}
                    allowHalf={itemData.allowHalf ? itemData.allowHalf : false}
                    value={value || 0}
                />
            );
        }
    };

    const pageStyle = `
        @media all {
            .page-break {
            display: none;
            }
        }
        
        @media print {
            html, body {
            height: initial !important;
            overflow: initial !important;
            -webkit-print-color-adjust: exact;
            }
        }
        
        @media print {
            .page-break {
            margin-top: 2rem;
            display: block;
            page-break-before: auto;
            }
        }
        
        @page {
            size: auto;
            margin: 20mm;
        }
    `;

    return (
        <PrintProvider>
            <div className={`${styles.bodyBox} detailCards`} ref={printRef ?? null}>
                <style type="text/css" media="print">
                    {pageStyle}
                </style>
                <Spin spinning={false}>
                    {topNode && <div>{topNode}</div>}
                    {totalCard?.map((item, i) => {
                        let Container = item?.noPrint ? NoPrint : Print;
                        return (
                            <Container force={true}>
                                <Card
                                    key={i}
                                    title={item.cardTitle}
                                    bordered={false}
                                    style={{ marginBottom: 16 }}
                                    bodyStyle={{ padding: "16px 10px" }}
                                    extra={item?.extra ? <Button type="primary" onClick={() => {
                                        doFetch({ url: item.extrapath, params: initialState[item.extrakey] }).then(res => {
                                            if (res.code == "0000") {
                                                message.success("操作成功")
                                            }
                                        })
                                    }}>保存</Button> : null}
                                >
                                    <Row gutter={[12, 12]}>
                                        {item?.itemData?.map((it, j) => {
                                            return (
                                                <Col key={j} {...getCol(it.col)}>
                                                    <div style={{ width: "100%", display: "flex" }}>
                                                        <div
                                                            style={{
                                                                flexShrink: 0,
                                                                display: `${it.title ? "block" : "none"}`,
                                                                textAlign: "right",
                                                                width: 126,
                                                            }}
                                                        >
                                                            {it.title}：
                                                        </div>
                                                        {getItem(it)}
                                                    </div>
                                                </Col>
                                            );
                                        })}
                                    </Row>
                                </Card>
                            </Container>
                        );
                    })}
                    {bottomNode && <div>{bottomNode}</div>}
                </Spin>
            </div>
        </PrintProvider>

    );
};

export default memo(Details);
