import React, { useState, useRef, useEffect, useImperativeHandle } from "react";
import { connect } from "react-redux";
import {
    Form,
    Row,
    Col,
    Button,
    CheckboxGroup,
    Checkbox,
    Radio,
    Input,
    Spin,
} from "@douyinfe/semi-ui";
import { IconEdit, IconPlayCircle, IconTickCircle } from "@douyinfe/semi-icons";
import "./cameraModal.less";
import PerfectScrollbar from "perfect-scrollbar";
import { VideoPlayModal } from "$components";

let equipmentScrollbar;
function nvrCamera ({ dispatch, actions, nvrRef, cameraData, addNvr, nvrNumber, }) {
    const { equipmentWarehouse } = actions;
    const cameraDataNvr = cameraData.nvr || "";
    const form = useRef();
    const [nvrCheckList, setNvrCheckList] = useState([]); //nvr视频流多选
    const [NVRcameraList, setNVRcameraList] = useState([]); //nvr视频流列表
    const [isAllChoose, setIsAllChoose] = useState(false); //全选
    const [equipmentNum, setEquipmentNum] = useState(""); //nvr视频编号
    const [isloading, setloading] = useState(false); //是否显示loading
    const [loadingTip, setloadingTip] = useState("获取中..."); //loading tip的值
    const [step, setstep] = useState("none");
    const [stepp, setstepp] = useState("none");
    const [videoPlay, setVideoPlay] = useState(false);//播放
    const [videoObj, setVideoObj] = useState(); //播放条件

    useEffect(() => {
        NVRcameraList
            ? (equipmentScrollbar = new PerfectScrollbar("#video_streaming", {
                suppressScrollX: true,
            }))
            : "";
    }, [NVRcameraList]);
    useEffect(() => {
        const videoStreaming = document.getElementById("video_streaming");
        if (videoStreaming && equipmentScrollbar) {
            equipmentScrollbar.update();
        }
    });
    useEffect(() => {
        if (cameraDataNvr) {
            setloading(true);
            setstep("block");
            dispatch(
                equipmentWarehouse.getVideoStreaming({
                    streamId: cameraDataNvr.serialNo,
                })
            ).then((res) => {
                let oneData = res.payload.data[0];
                let modifyData = res.payload.data.find(
                    (item) => item.id == cameraData.gbId);
                let data = res.payload.data.map((item, index) => {
                    if (item.camera) {
                        item.name = item.camera.name;
                        item.support = item.camera.cloudControl
                    }
                    if (item.id == cameraData.gbId) {
                        item = oneData;
                    }
                    if (index == 0) {
                        item = modifyData;
                    }

                    return item;
                });
                setNVRcameraList(data);
                setNvrCheckList([data[0].id]);
                if (res.success) {
                    setTimeout(() => {
                        setloadingTip("获取完成");
                        setTimeout(() => {
                            setstep("none");
                            setloading(false);
                            setstepp("block");
                            setloadingTip("获取中...");
                        }, 800);
                    }, 800)
                }
            })
        }

        //NVR添加页面跳到nvr摄像头添加页面
        if (addNvr) {
            setloading(true);
            setstep("block");
            dispatch(equipmentWarehouse.getVideoStreaming({ streamId: nvrNumber })).then((res) => {
                let chooseList = [];
                let data = res.payload.data.map((item) => {
                    item.change = false;
                    item.support = false;
                    return item;
                });
                setNVRcameraList(data);
                for (let index = 0; index < data.length; index++) {
                    chooseList.push(data[index].id);
                }
                setNvrCheckList(chooseList);
                setIsAllChoose(true);
                if (res.success) {
                    setTimeout(() => {
                        setloadingTip("接入完成");
                        setTimeout(() => {
                            setstep("none");
                            setloading(false);
                            setstepp("block");
                            setloadingTip("正在接入视频流...");
                        }, 800);
                    }, 800)
                }
            })
        }

    }, []);
    function NvrChangeName (e, index, id) {
        //nvr摄像头视频流获取修改名称
        let NvrchangeList = JSON.parse(JSON.stringify(NVRcameraList));
        if (!cameraData.gbId || cameraData.gbId == id) {
            NvrchangeList[index].change = true;
            setNVRcameraList(NvrchangeList);
        }
        e.stopPropagation();
    }
    function nvronBlur (index) {
        //nvr摄像头名称修改失去焦点
        let NvrchangeList = JSON.parse(JSON.stringify(NVRcameraList));
        NvrchangeList[index].change = false;
        setNVRcameraList(NvrchangeList);
    }
    function inputchange (e, index) {
        //nvr摄像头名称修改
        let NvrchangeList = JSON.parse(JSON.stringify(NVRcameraList));
        NvrchangeList[index].name = e;
        setNVRcameraList(NvrchangeList);
    }
    function toggle (e, index) {
        //nvr云台支持
        let NvrchangeList = JSON.parse(JSON.stringify(NVRcameraList));
        NvrchangeList[index].support = e.target.checked;
        setNVRcameraList(NvrchangeList);
        e.stopPropagation();
    }
    function getVideoList () {
        form.current
            .validate()
            .then((values) => {
                //表单校验成功
                let chooseList = [];
                let valuess = JSON.parse(JSON.stringify(values));
                valuess.streamId = values.serialNo;
                delete valuess.serialNo;
                setloading(true);
                setstep("block");
                dispatch(equipmentWarehouse.getVideoStreaming(valuess)).then((res) => {
                    let data = res.payload.data.map((item) => {
                        item.change = false;
                        item.support = false;
                        return item;
                    });
                    setNVRcameraList(data);
                    for (let index = 0; index < data.length; index++) {
                        chooseList.push(data[index].id);
                    }
                    setNvrCheckList(chooseList);
                    setIsAllChoose(true);
                    if (res.success) {
                        setTimeout(() => {
                            setloadingTip("获取完成");
                            setTimeout(() => {
                                setstep("none");
                                setloading(false);
                                setstepp("block");
                                setloadingTip("获取中...");
                            }, 800);
                        }, 800)
                    }
                });
            })
            .catch((errors) => {
                //表单校验失败
                // console.log("errors", errors);
            });
    }
    function allChoose (e) {
        //全选/全不选
        let chooseList = [];
        if (NVRcameraList.length == nvrCheckList.length) {
            setNvrCheckList([]);
            setIsAllChoose(false);
        } else {
            for (let index = 0; index < NVRcameraList.length; index++) {
                chooseList.push(NVRcameraList[index].id);
            }
            setNvrCheckList(chooseList);
            setIsAllChoose(true);
        }
    }
    function playVideo (e, id) {
        //nvr播放视频
        if (cameraData.gbId == id || !cameraData.gbId) {
            let data = NVRcameraList.find((item) => item.id == id)
            setVideoObj({
                type: "nvr",
                audio: false,
                serialNo: data.streamid,
                topSerialNo: cameraDataNvr ? cameraDataNvr.serialNo : addNvr ? nvrNumber : equipmentNum,
                playUrlSd: data?.playUrl?.liveUrl?.sd["WS-RAW"],
                content:data?.camera?.cameraRemarks.map((item) => item.remark)
            })
            setVideoPlay(true);
        }

        e.stopPropagation();
    }
    function onDisabled (id) {
        if (cameraData.gbId == id || !cameraData.gbId) {
            return false;
        } else {
            return true;
        }
    }
    useImperativeHandle(nvrRef, () => ({
        //传给父组件方法
        //aa即为子组件暴露给父组件的方法
        resetFluoriteCamera: form.current.reset,
        equipmentNum: cameraDataNvr ? cameraDataNvr.serialNo : addNvr ? nvrNumber : equipmentNum,
        NVRcameraList: NVRcameraList.filter((v) =>
            nvrCheckList.some((e) => e == v.id)
        ),
    }));
    return (
        <>
            <Form
                allowEmpty
                labelPosition="left"
                labelAlign="left"
                labelWidth="115px"
                onValueChange={(values) => {
                    setEquipmentNum(values.serialNo);
                }}
                getFormApi={(formApi) => (form.current = formApi)}
            >
                <div style={{ display: "flex" }}>
                    <Form.Input
                        field="serialNo"
                        maxLength="39"
                        label="设备编号:"
                        disabled={cameraDataNvr ? true : addNvr ? true : false}
                        initValue={cameraDataNvr ? cameraDataNvr.serialNo : addNvr ? nvrNumber : ""}
                        placeholder="请输入设备编号"
                        style={{ width: 307 }}
                        rules={[
                            { required: true, message: "请输入设备编号" },
                            { pattern: "^[A-Za-z0-9]+$", message: "只能输入数字或者字母" },
                        ]}
                    />
                    <Button
                        disabled={!equipmentNum.length > 0}
                        theme="solid"
                        type="primary"
                        onClick={() => {
                            getVideoList();
                        }}
                        style={{ marginLeft: 8, marginTop: 12 }}
                    >
                        视频流获取
                    </Button>
                    {stepp !== 'none' ? (
                        <div
                            style={{ display: "flex", alignItems: "center", marginLeft: 211 }}
                        >
                            <Radio
                                checked={isAllChoose}
                                mode="advanced"
                                disabled={cameraData.gbId ? true : false}
                                onChange={(e) => allChoose(e)}
                                aria-label="全选"
                            >
                                全选
                            </Radio>
                        </div>
                    ) : (
                        ""
                    )}
                </div>
                <Row>
                    <CheckboxGroup
                        type="pureCard"
                        direction="vertical"
                        aria-label="视频流获取"
                        value={nvrCheckList}
                        onChange={(nvrCheck) => {
                            setNvrCheckList(nvrCheck);
                            if (NVRcameraList.length == nvrCheck.length) {
                                setIsAllChoose(true);
                            } else {
                                setIsAllChoose(false);
                            }
                        }}
                    >
                        <div
                            id="video_streaming"
                            style={{ maxHeight: 300, position: "relative" }}
                        >
                            <Spin tip={loadingTip} spinning={isloading}>
                                <div style={{ display: stepp }}>
                                    {NVRcameraList.length > 0
                                        ? NVRcameraList.map((item, index) => (
                                            <Col
                                                key={index}
                                                span={12}
                                                style={{
                                                    display: "flex",
                                                    justifyContent: "center",
                                                    marginTop: 12,
                                                }}
                                            >
                                                <Checkbox
                                                    value={item.id}
                                                    disabled={onDisabled(item.id)}
                                                    extra={
                                                        <div>
                                                            <div
                                                                style={{
                                                                    display: "flex",
                                                                    alignItems: "center",
                                                                    justifyContent: "space-between",
                                                                    height: 30,
                                                                }}
                                                            >
                                                                <div>
                                                                    通道名称：
                                                                    {item.change ? (
                                                                        <Input
                                                                            autofocus
                                                                            style={{ width: 100 }}
                                                                            value={item.name}
                                                                            onChange={(e) => inputchange(e, index)}
                                                                            onBlur={() => nvronBlur(index)}
                                                                            onClick={(e) => e.stopPropagation()}
                                                                        ></Input>
                                                                    ) : (
                                                                        item.name.length > 12 ? `${item.name.substr(0,12)}...` : item.name
                                                                    )}
                                                                </div>
                                                                <div
                                                                    style={{
                                                                        display: "flex",
                                                                        alignItems: "center",
                                                                    }}
                                                                >
                                                                    <IconEdit
                                                                        style={{
                                                                            fontSize: 16,
                                                                            marginLeft: 18,
                                                                            cursor: "pointer",
                                                                            color: "#1859C1",
                                                                        }}
                                                                        onClick={(e) =>
                                                                            NvrChangeName(e, index, item.id)
                                                                        }
                                                                    />
                                                                </div>
                                                            </div>
                                                            <div style={{ marginTop: 8, width: 246 }}>
                                                                设备编号：{item.streamid}
                                                            </div>
                                                            <div
                                                                style={{
                                                                    marginTop: 12,
                                                                    display: "flex",
                                                                    justifyContent: "space-between",
                                                                    alignItems: "center",
                                                                }}
                                                            >
                                                                <IconPlayCircle
                                                                    size="extra-large"
                                                                    style={{ color: "#1859C1" }}
                                                                    onClick={(e) => playVideo(e, item.id)}
                                                                />
                                                                <Radio
                                                                    checked={item.support}
                                                                    mode="advanced"
                                                                    disabled={onDisabled(item.id)}
                                                                    onChange={(e) => toggle(e, index)}
                                                                    aria-label="单选"
                                                                >
                                                                    云台支持
                                                                </Radio>
                                                            </div>
                                                        </div>
                                                    }
                                                    style={{ width: 280, border: "1px solid #F9F9F9" }}
                                                ></Checkbox>
                                            </Col>
                                        ))
                                        : ""}
                                </div>
                                <div style={{ height: 50, width: "100%", display: step }}></div>
                            </Spin>

                        </div>
                    </CheckboxGroup>
                </Row>
            </Form>
            {videoPlay ?
                <VideoPlayModal
                    visible={true}
                    videoObj={videoObj}
                    close={() => {
                        setVideoPlay(false)
                    }} />
                : ""
            }
        </>
    );
}
function mapStateToProps (state) {
    const { auth, global, members } = state;
    return {
        loading: members.isRequesting,
        user: auth.user,
        actions: global.actions,
        members: members.data,
    };
}

export default connect(mapStateToProps)(nvrCamera);
