import React, { useEffect, useRef, useState } from 'react';
import { Card, List, Modal, Typography, Image, Radio, Table, Drawer } from 'antd';
import ProCard from '@ant-design/pro-card';
import { getCameraList, getWarnDetailData } from './service';
import ScreenVideoPlay from './ScreenVideoPlay';
import { pictureDisplayPath } from '@/utils/DownloadUtils';
import moment from 'moment';

interface ScreenWarnBackProps {
    modalVisible: boolean;
    onCancel: () => void;
    warnId: string;//告警id
}
const modalHeight = window.innerHeight * 96 / 100;

/**
 * 异常告警详情回放
 * @param props 
 * @returns 
 */
const ScreenWarnBack: React.FC<ScreenWarnBackProps> = (props) => {
    const { modalVisible, onCancel, warnId } = props;
    const { Title } = Typography;
    //详情信息
    const [detailData, setDetailData] = useState<any>();
    //设备列表
    const [caremaList, setCaremaList] = useState<any[]>([]);
    //当前选择的设备
    const [cameraSelect, setCameraSelect] = useState<string>("1");
    //当前播放的设备参数
    const [cameraParams, setCameraParams] = useState<any>();
    //图片查看抽屉显隐
    const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
    //图片查看URL
    const [drawerUrl, setDrawerUrl] = useState<string>('');
    //监控视频Ref
    const videoRef = useRef<any>();
    //图片展示ref
    const zoomImg = useRef<any>(null);
    const peopleNumColumns: any[] = [
        {
            title: '时间',
            dataIndex: 'eventTime',
            key: 'eventTime',
            align: 'center',
            width: "40%",
        },
        {
            title: '阈值',
            dataIndex: 'thresholdOfPeople',
            key: 'thresholdOfPeople',
            align: 'center',
            ellipsis: true,
            render: (_: any, record: any) => `${_}人`,
        },
        {
            title: '实际人数',
            dataIndex: 'realOfPeople',
            key: 'realOfPeople',
            align: 'center',
            render: (_: any, record: any) => `${_}人`,
        },
    ];
    //回放
    const videoBack = (deviceCode: any, data: any) => {
        let backTime = 20;
        if (data.type == "2") {//人数预警
            backTime = 10;
        }
        videoRef.current?.back(deviceCode, moment(data?.createDate).subtract(backTime, 'm').format('yyyy-MM-DD HH:mm:ss'), data?.createDate);
    }

    //获取告警详情数据
    const getWarnDetail = () => {
        getWarnDetailData({ id: warnId }).then(res => {
            if (res?.code == 200) {
                const data = res?.data;
                setDetailData(data);
                getCaremaData(data);
            }
        })
    }

    //获取设备
    const getCaremaData = (baseData: any) => {
        getCameraList({ areaId: baseData.placeId }).then(res => {
            if (res?.code == 200) {
                const data = res?.data;
                setCaremaList(data);
                if (data?.length > 0) {
                    //获取回看时间
                    setCameraSelect(data[0].deviceCode);
                    setCameraParams(data[0].platform);
                    setTimeout(() => {
                        videoBack(data[0].deviceCode, baseData);
                    }, 4000);
                }
            }
        })
    }
    //切换设备
    const onCaremaChange = (e: any) => {
        const caremaCode = e.target.value;
        for (const ite of caremaList) {
            if (ite.deviceCode == caremaCode) {
                setCameraSelect(caremaCode);
                setCameraParams(ite.platform);
                videoBack(caremaCode, detailData);
            }
        }
    }

    //图片放大抽屉显示
    const drawerClick = (filePath: string) => {
        setDrawerUrl(filePath);
        setDrawerVisible(true);
    }
    //图片放大抽屉关闭
    const drawerClose = () => {
        setDrawerVisible(false);
        setDrawerUrl("");
    }
    const handleImgZoom = (e: { nativeEvent: { deltaY: number; }; }) => {
        const { clientWidth, clientHeight, style, height, width } = zoomImg.current
        const value = height / width
        const num = 50
        const bool = height > width ? clientWidth < 2000 : clientHeight < 1500
        if (e.nativeEvent.deltaY <= 0 && bool) {
            style.maxWidth = "none"
            style.maxHeight = "none"
            style.width = width + num + "px"
            style.height = height + (num * value) + "px"
            style.left = style.left - 1 % +"px"
            style.top = style.top - 1 % +"px"
        } else if (e.nativeEvent.deltaY > 0) {
            if (width > 200 && height > 100) {
                style.width = width - num + "px"
                style.height = height - (num * value) + "px"
                style.left = style.left + 1 % + "px"
                style.top = style.top + 1 % + "px"
            }
        }
    }

    useEffect(() => {
        warnId && getWarnDetail();
    }, [warnId])

    return (
        <Modal
            destroyOnClose
            title="告警详情"
            visible={modalVisible}
            onCancel={() => onCancel()}
            okButtonProps={{ hidden: true }}
            width={"80%"}
            maskClosable={false}
            style={{ maxHeight: modalHeight }}
            bodyStyle={{ height: modalHeight - 107, overflowY: 'auto', padding: 0 }}
            centered
        >
            <ProCard split="vertical" bodyStyle={{ height: "calc(100vh - 136px)" }}>
                <ProCard colSpan={7} key="0" bodyStyle={{ padding: "16px", overflowY: 'auto', height: "calc(100vh - 136px)" }} className="screen-warn-p">
                    <Title level={5} style={{ marginBottom: '8px', color: "#b30000" }}>告警信息：{detailData?.type == "3" ? "陌生人进入" : "人数异常"}</Title>
                    {detailData?.type == "3" ? (
                        <List
                            grid={{ column: 1 }}
                            dataSource={detailData?.details}
                            renderItem={(item: any) => (
                                <List.Item>
                                    <Card bodyStyle={{ padding: "8px" }}>
                                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                            <Typography>时间：{item.eventTime}</Typography>
                                            <Image src={pictureDisplayPath + "?filePath=" + item.filePath} preview={{ getContainer: "null" }} height="70px" onClick={() => drawerClick(item.filePath)} />
                                        </div>
                                    </Card>
                                </List.Item>
                            )}
                        />
                    ) : (
                        <Table
                            pagination={false}
                            rowKey="id"
                            size="small"
                            dataSource={detailData?.details}
                            columns={peopleNumColumns}
                        />
                    )}
                    {drawerVisible && <Drawer
                        placement="left"
                        onClose={drawerClose}
                        visible={drawerVisible}
                        width={'29.17%'}
                        getContainer={false}
                        style={{ position: 'absolute' }}
                    >
                        <div onClick={drawerClose}>
                            <img src={pictureDisplayPath + "?filePath=" + drawerUrl} onWheel={handleImgZoom} ref={zoomImg} />
                        </div>
                    </Drawer>}
                </ProCard>
                <ProCard colSpan={17} key="1" bodyStyle={{ padding: "16px" }}>
                    <Radio.Group value={cameraSelect} buttonStyle="solid" style={{ marginBottom: "8px" }} onChange={onCaremaChange}>
                        {caremaList.map(item => (<Radio.Button value={item.deviceCode} key={item.deviceCode}>{item.deviceName}</Radio.Button>))}
                    </Radio.Group>
                    <div style={{ height: "94%", border: '1px solid red' }}>
                        {cameraParams && <ScreenVideoPlay videoRef={videoRef} cameraParams={cameraParams} status={1} />}
                    </div>
                </ProCard>
            </ProCard>
        </Modal>
    );
};

export default ScreenWarnBack;
