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

let equipmentScrollbar;
function cascadeCamera ({ dRef, dispatch, actions, cameraData, parentCamera, testComplete, close, ashTrue, ashFalse }) {
    const form = useRef();
    const { equipmentWarehouse } = actions;
    const [sip, setSip] = useState([]);
    const [cascadeList, setCascadeList] = useState([]); //nvr视频流列表
    const [CheckList, setCheckList] = useState([]); //nvr视频流多选
    const [isAllChoose, setIsAllChoose] = useState(false); //全选
    const [formData, setFormData] = useState() //表单数据
    const [videoPlay, setVideoPlay] = useState(false);//播放
    const [videoObj, setVideoObj] = useState(); //播放条件

    useEffect(() => {
        dispatch(equipmentWarehouse.getCascadeSIP()).then((res) => {
            setSip(res.payload.data);
            if (cameraData.id) {
                let sip = res.payload.data.find((item) => item.streamid == cameraData.topSerialNo)
                console.log(sip);
                dispatch(equipmentWarehouse.getCascadeStream({ streamId: sip.streamid })).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;
                        }
                        if (item.id == cameraData.gbId) {
                            item = oneData;
                        }
                        if (index == 0) {
                            item = modifyData;
                        }
                        return item;
                    })
                    setCascadeList(data)
                    setCheckList([data[0].id])
                });
            }
        });
        const videoStreaming = document.getElementById("video_streaming");
        if (videoStreaming && equipmentScrollbar) {
            equipmentScrollbar.update();
        }
    }, []);

    useEffect(() => {
        cascadeList
            ? (equipmentScrollbar = new PerfectScrollbar("#video_streaming", {
                suppressScrollX: true,
            }))
            : "";
    }, [cascadeList]);

    useEffect(() => {
        //测试成功后获取级联视频流
        if (testComplete) {
            console.log(formData);
            dispatch(equipmentWarehouse.getCascadeStream({ streamId: formData.streamId })).then((res) => {
                console.log(res.payload.data);
                let chooseList = [];
                let data = res.payload.data.map((item, index) => {
                    if (item.camera) {
                        item.name = item.camera.name;
                    }
                    return item;
                })
                setCascadeList(data)
                for (let index = 0; index < data.length; index++) {
                    chooseList.push(data[index].id);
                }
                setCheckList(chooseList);
                setIsAllChoose(true);
            });
        }
        close()
    }, [testComplete])


    //内存卡列表
    const memoryList = [
        {
            id: 1,
            value: "8g",
        },
        {
            id: 2,
            value: "16g",
        },
        {
            id: 3,
            value: "32g",
        },
        {
            id: 4,
            value: "64g",
        },
        {
            id: 5,
            value: "128g",
        },
        {
            id: 6,
            value: "256g",
        },
        {
            id: 7,
            value: ">256g",
        },
    ];

    function NvrChangeName (e, index, id) {
        //级联摄像头视频流获取修改名称
        let NvrchangeList = JSON.parse(JSON.stringify(cascadeList));
        if (!cameraData.gbId || cameraData.gbId == id) {
            NvrchangeList[index].change = true;
            setCascadeList(NvrchangeList);
        }
        e.stopPropagation();
    }
    function nvronBlur (index) {
        //nvr摄像头名称修改失去焦点
        let NvrchangeList = JSON.parse(JSON.stringify(cascadeList));
        NvrchangeList[index].change = false;
        setCascadeList(NvrchangeList);
    }
    function inputchange (e, index) {
        //nvr摄像头名称修改
        let NvrchangeList = JSON.parse(JSON.stringify(cascadeList));
        NvrchangeList[index].name = e;
        setCascadeList(NvrchangeList);
    }
    function allChoose (e) {
        //全选/全不选
        let chooseList = [];
        if (cascadeList.length == CheckList.length) {
            setCheckList([]);
            setIsAllChoose(false);
        } else {
            for (let index = 0; index < cascadeList.length; index++) {
                chooseList.push(cascadeList[index].id);
            }
            setCheckList(chooseList);
            setIsAllChoose(true);
        }
    }
    function playVideo (e, id) {
        //nvr播放视频
        if (cameraData.gbId == id || !cameraData.gbId) {
            let data = cascadeList.find((item) => item.id == id)
            console.log(formData);
            setVideoObj({
                type: 'cascade',
                audio: false,
                serialNo: data.streamid,
                topSerialNo: cameraData.id ? cameraData.topSerialNo : formData?.streamId,
                playUrlSd: data?.playUrl?.liveUrl?.sd["WS-RAW"],
            })
            setVideoPlay(true);
        }
        e.stopPropagation();
    }
    function onDisabled (id) {
        if (id == cameraData.gbId || !cameraData.gbId) {
            return false;
        } else {
            return true;
        }
    }

    useImperativeHandle(dRef, () => ({
        //传给父组件方法
        //子组件暴露给父组件的方法
        cascadeCameraForm: form.current.validate,
        resetCascadeCamera: form.current.reset,
        cascadeList: cascadeList.filter((v) =>
            CheckList.some((e) => e == v.id)
        ),
        toempty: () => {
            setCascadeList([])
        }
    }));
    return (
        <>
            <Form
                labelPosition="left"
                labelAlign="left"
                labelWidth="115px"
                onValueChange={(values) => {
                    setFormData(values)
                    let setting = ["externalDomain", "cascadeType", "streamId"]
                    let b = {}
                    setting.map((item) => {
                        if (values.hasOwnProperty(item)) {
                            return b.true = values.hasOwnProperty(item)
                        } else {
                            return b.false = values.hasOwnProperty(item)
                        }
                    })
                    Object.keys(b).length == 1 ? ashTrue() : ashFalse()

                }}
                initValues={{
                    externalDomain: cameraData.externalDomain || ""
                }}
                getFormApi={(formApi) => (form.current = formApi)}
            >
                <Row>
                    <Col span={12}>
                        <Form.Input
                            field="externalDomain"
                            label="外域名称:"
                            maxLength="36"
                            placeholder="请输入外域 名称，例如“xxx市级平台”"
                            style={{ width: 307 }}
                            rules={[{ required: true, message: "请输入外域名称" }]}
                        />
                    </Col>
                    <Col span={12}>
                        <Form.Select
                            label="级联方式:"
                            field="cascadeType"
                            initValue={cameraData.cascadeType || "上级域"}
                            style={{ width: 307 }}
                            rules={[{ required: true, message: "请选择输入级联方式" }]}
                        >
                            <Form.Select.Option value="上级域">
                                上级域
                            </Form.Select.Option>
                        </Form.Select>
                    </Col>
                    <Col span={14}>
                        <Form.Select
                            label="SIP编号:"
                            field="streamId"
                            disabled={cameraData.id ? true : false}
                            initValue={cameraData?.topSerialNo || ""}
                            placeholder="请选择SIP编号"
                            style={{ width: 307 }}
                            rules={[{ required: true, message: "请选择SIP编号" }]}
                        >
                            {sip.map((item, index) => (
                                <Form.Select.Option key={index} value={item.streamid}>
                                    {item.streamid}
                                </Form.Select.Option>
                            ))}
                        </Form.Select>
                    </Col>
                </Row>
                <Row>

                    <div
                        id="video_streaming"
                        style={{ maxHeight: 300, position: "relative" }}
                    >
                        {cascadeList.length > 0 ? (
                            <div
                                style={{ display: "flex", justifyContent: "flex-end", marginRight: 50 }}
                            >
                                <Radio
                                    checked={isAllChoose}
                                    mode="advanced"
                                    disabled={cameraData.gbId ? true : false}
                                    onChange={(e) => allChoose(e)}
                                    aria-label="全选"
                                >
                                    全选
                                </Radio>
                            </div>
                        ) : (
                            ""
                        )}
                        <CheckboxGroup
                            type="pureCard"
                            direction="vertical"
                            aria-label="视频流获取"
                            value={CheckList}
                            onChange={(nvrCheck) => {
                                setCheckList(nvrCheck);
                                if (cascadeList.length == nvrCheck.length) {
                                    setIsAllChoose(true);
                                } else {
                                    setIsAllChoose(false);
                                }
                            }}>
                            {cascadeList.length > 0
                                ? cascadeList.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
                                                            )}
                                                        </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)}
                                                        />
                                                    </div>
                                                </div>
                                            }
                                            style={{ width: 280, border: "1px solid #F9F9F9" }}
                                        ></Checkbox>
                                    </Col>
                                ))
                                : ""}
                        </CheckboxGroup>
                    </div>

                </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)(cascadeCamera);
