import React, { useState, useRef, useEffect } from "react";
import { connect } from "react-redux";
import { Modal, Spin } from "@douyinfe/semi-ui";
import { IconChevronLeft, IconChevronRight } from "@douyinfe/semi-icons";
import moment from "moment";
import FluoriteCamera from "./fluoriteCamera";
import NvrCamera from "./nvrCamera";
import IpcCamera from "./ipcCamera";
import CascadeCamera from "./cascadeCamera";
import "./cameraModal.less";

function cameraModal (props) {
    const {
        dispatch,
        actions,
        modalName,
        visible,
        close,
        venderList,
        CameraKind,
        CameraAbility,
        cameraData, //修改时传来的值
        modify,
        parentCamera,
        addNvr,
        nvrNumber,
        axyData,
    } = props;
    const { equipmentWarehouse } = actions;
    const fluoriteRef = useRef();
    const ipcRef = useRef();
    const cascadeRef = useRef();
    const nvrRef = useRef();
    const [isloading, setloading] = useState(false); //是否显示loading
    const [loadingTip, setloadingTip] = useState("测试中..."); //loading tip的值
    const [okText, setokText] = useState("确定"); //ok弹框text  右边
    const [cancelText, setcancelText] = useState("取消"); //取消弹框text  左边
    const [ash, setAsh] = useState(false); //置灰
    const testComplete = useRef(false)  //测试完成
    const [clickNum, setclickNum] = useState(
        cameraData.type == "yingshi"
            ? 1
            : cameraData.type == "ipc"
                ? 3
                : cameraData.type == "nvr" || addNvr
                    ? 2
                    : cameraData.type == "cascade"
                        ? 4
                        : 1
    ); //点击的第几个

    useEffect(() => {
        dispatch(equipmentWarehouse.getCameraKind());
        dispatch(equipmentWarehouse.getAbility());
        cameraData.type == "nvr" || addNvr ? setcameraList(cameraList.slice(1, 4)) : "";
        //axyData安心云参数
        if (axyData) {
            console.log(axyData)
            switch (axyData.openCamera) {
                case "nvr":
                    setcameraList(cameraList.slice(1, 4))
                    setclickNum(2)
                    break
                case "ipc":
                    setcameraList(cameraList.slice(0, 3))
                    setclickNum(3)
                    break
                case "yingshi":
                    setcameraList(cameraList.slice(0, 3))
                    setclickNum(1)
                    break
                default:
                    break
            }
        }
        cameraData.id ? setAsh(true) : ""
    }, []);
    const cameraList = [
        //循环摄像头列表
        {
            id: 1,
            img: "/assets/images/background/ysy.png",
            title: "萤石云平台摄像头",
            text: "通过萤石云平台rtmp地址配置完成推流的平台摄像头。",
        },
        {
            id: 3,
            img: "/assets/images/background/ipc.png",
            title: "IPC网络摄像头",
            text: "通过网络与监控设备直连完成视频流推送的摄像头设备",
        },
        {
            id: 4,
            img: "/assets/images/background/cascade.png",
            title: "级联摄像头",
            text: "通过GB/T28181协议级联的平台摄像头，常用于平台对接推送",
        },
        {
            id: 2,
            img: "/assets/images/background/nvr.png",
            title: "NVR摄像头",
            text: "通过连接NVR(网络硬盘录像机)进行视频流推送的摄像头",
        },
    ];
    const [showcameraList, setcameraList] = useState(cameraList.slice(0, 3)); //轮播图
    function handleOk () {
        //点击弹框确定  右边按钮
        if (clickNum == 1) {
            //萤石云平台摄像头
            fluoriteRef.current.fluoriteCameraForm().then((values) => {
                values = JSON.parse(JSON.stringify(values));
                values.longitude = values.position.split(",")[0];
                values.latitude = values.position.split(",")[1];
                delete values.position;
                if (cameraData.id) {
                    values.id = cameraData.id;
                }
                dispatch(equipmentWarehouse.postCameraYingshi(values)).then((res) => {
                    if (res.success) {
                        onReset();
                    }
                });
            });
        } else if (clickNum == 2) {
            //NVR摄像头
            let data = nvrRef.current.NVRcameraList.map((v) => {
                return { streamid: v.streamid, name: v.name, cloudControl: v.support };
            });
            dispatch(
                equipmentWarehouse.postCameraNvr({
                    serialNo: nvrRef.current.equipmentNum,
                    data: data,
                })
            ).then((res) => {
                if (res.success) {
                    onReset();
                }
            });
        } else if (clickNum == 3) {
            //IPC网络摄像头
            ipcRef.current.ipcCameraForm().then((values) => {
                values = JSON.parse(JSON.stringify(values));
                values.longitude = values.position.split(",")[0];
                values.latitude = values.position.split(",")[1];
                delete values.position;
                if (cameraData.id) {
                    values.id = cameraData.id;
                }
                console.log(values);
                dispatch(equipmentWarehouse.postCameraIpc(values)).then((res) => {
                    if (res.success) {
                        onReset();
                    }
                });
            });
        } else if (clickNum == 4) {
            //级联摄像头
            let data = cascadeRef.current.cascadeList.map((v) => {
                return { id: v.id, name: v.name, };
            });
            console.log(cascadeRef.current.cascadeList)
            console.log(data)
            cascadeRef.current.cascadeCameraForm().then((values) => {
                console.log(values);
                dispatch(equipmentWarehouse.postAddCascade({ ...values, camera: data })).then((res) => {
                    console.log(res);
                    if (res.success) {
                        onReset();
                    }
                });
            });
        }
    }
    function handleAfterClose () {
        //在关闭之后
    }
    function handleCancel () {
        onReset();
        //点击弹框取消  左边按钮
    }
    function handleChoose (id) {
        //选择摄像头接入类型
        if (!addNvr && !modify && !axyData) {
            setclickNum(id);
        }
    }
    function turnLift () {
        //轮播图向左
        if (!addNvr && !modify && !axyData) {
            setcameraList(cameraList.slice(0, 3));
        }
    }
    function turnRight () {
        //轮播图向右
        if (!addNvr && !modify && !axyData) {
            setcameraList(cameraList.slice(1, 4));
        }
    }
    function onReset () {
        if (clickNum == 1) {
            fluoriteRef.current.resetFluoriteCamera();
            fluoriteRef.current.toempty();
            close();
        } else if (clickNum == 3) {
            ipcRef.current.resetIpcCamera();
            ipcRef.current.toempty();
            close();
        } else if (clickNum == 4) {
            cascadeRef.current.resetCascadeCamera();
            testComplete.current = false
            close();
        } else {
            nvrRef.current.resetFluoriteCamera();
            close();
        }
    }
    //重置
    function reset () {
        if (clickNum == 1) {
            fluoriteRef.current.resetFluoriteCamera();
            fluoriteRef.current.toempty();
        } else if (clickNum == 3) {
            ipcRef.current.resetIpcCamera();
            ipcRef.current.toempty();
        } else if (clickNum == 4) {
            cascadeRef.current.resetCascadeCamera();
            cascadeRef.current.toempty()
        } else {
            nvrRef.current.resetFluoriteCamera();
            ipcRef.current.toempty()
        }
    }

    //表单验证
    function toTest () {
        if (clickNum == 1) {
            fluoriteRef.current
                .fluoriteCameraForm()
                .then((values) => {
                    //表单校验成功
                    var front = new moment(); //验证前时间
                    setloading(true);
                    dispatch(
                        equipmentWarehouse.postVerifyYingshi({
                            serialNo: values.serialNo,
                        })
                    ).then((res) => {
                        var after = new moment();  //验证后时间
                        var duration = moment.duration(after.diff(front))._data.milliseconds;
                        if (res.success) {
                            setTimeout(() => {
                                setloadingTip("测试完成");
                                setTimeout(() => {
                                    setloading(false);
                                    setloadingTip("测试中...");
                                }, 800);
                            }, duration > 2000 ? 0 : 2000 - duration)
                        } else {
                            setTimeout(() => {
                                setloadingTip("测试失败");
                                setTimeout(() => {
                                    setloading(false);
                                    setloadingTip("测试中...");
                                }, 800);
                            }, duration > 2000 ? 0 : 2000 - duration)
                        }
                    })
                })
                .catch((errors) => {
                    //表单校验失败
                    console.log("errors", errors);
                });
        } else if (clickNum == 3) {
            ipcRef.current
                .ipcCameraForm()
                .then((values) => {
                    //表单校验成功
                    console.log(values);
                    var front = new moment(); //验证前时间
                    setloading(true);
                    dispatch(
                        equipmentWarehouse.postVerifyIpc({
                            serialNo: values.serialNo,
                        })
                    ).then((res) => {
                        var after = new moment();  //验证后时间
                        var duration = moment.duration(after.diff(front))._data.milliseconds;
                        if (res.success) {
                            setTimeout(() => {
                                setloadingTip("测试完成");
                                setTimeout(() => {
                                    setloading(false);
                                    setloadingTip("测试中...");
                                }, 800);
                            }, duration > 2000 ? 0 : 2000 - duration)
                        } else {
                            setTimeout(() => {
                                setloadingTip("测试失败");
                                setTimeout(() => {
                                    setloading(false);
                                    setloadingTip("测试中...");
                                }, 800);
                            }, duration > 2000 ? 0 : 2000 - duration)
                        }
                    })
                })
                .catch((errors) => {
                    //表单校验失败
                    console.log();
                });
        } else if (clickNum == 4) {
            cascadeRef.current
                .cascadeCameraForm()
                .then((values) => {
                    console.log(values);
                    var front = new moment(); //验证前时间
                    setloading(true);
                    dispatch(
                        equipmentWarehouse.postVerifyCascade({
                            sip: values.sip,
                        })
                    ).then((res) => {
                        var after = new moment();  //验证后时间
                        var duration = moment.duration(after.diff(front))._data.milliseconds;
                        if (res.success) {
                            setTimeout(() => {
                                setloadingTip("测试完成");
                                testComplete.current = true
                                setTimeout(() => {
                                    setloading(false);
                                    setloadingTip("测试中...");

                                }, 800);
                            }, duration > 2000 ? 0 : 2000 - duration)
                        } else {
                            setTimeout(() => {
                                setloadingTip("测试失败");
                                setTimeout(() => {
                                    setloading(false);
                                    setloadingTip("测试中...");
                                }, 800);
                            }, duration > 2000 ? 0 : 2000 - duration)
                        }
                    })

                })
                .catch((errors) => {
                    //表单校验失败
                    console.log("errors", errors);
                });
        }
    }

    return (
        <>
            <Modal
                title={modalName == "add" ? "添加摄像头" : "修改摄像头"}
                okText={okText}
                cancelText={cancelText} //取消按钮
                visible={visible}
                onOk={handleOk}
                width={966}
                afterClose={handleAfterClose}
                onCancel={handleCancel}
            >
                <>
                    <div
                        style={{ marginLeft: "-24px", marginRight: "-24px", marginTop: 8 }}
                    >
                        <div
                            style={{
                                marginLeft: 29,
                                color: "#1859C1",
                                fontSize: 14,
                                fontWeight: 500,
                            }}
                        >
                            接入类型
                        </div>
                        <div
                            style={{
                                marginTop: 5,
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "space-between",
                            }}
                        >
                            <IconChevronLeft
                                style={{
                                    color: "rgba(0, 0, 0, 0.45)",
                                    fontSize: 16,
                                    marginLeft: 29,
                                    cursor: "pointer",
                                }}
                                onClick={turnLift}
                            />
                            <div
                                style={{ display: "flex", alignItems: "center", height: 146 }}
                            >
                                {showcameraList.map((item, index) => (
                                    <div
                                        key={item.id}
                                        style={{
                                            width: 266,
                                            height: 146,
                                            marginRight: 12,
                                            border:
                                                clickNum === item.id
                                                    ? "1px solid #1859C1"
                                                    : "1px solid #F9F9F9",
                                            borderRadius: 3,
                                            display: "flex",
                                            flexDirection: "column",
                                            alignItems: "center",
                                            cursor: "pointer",
                                            position: "relative",
                                        }}
                                        onClick={() => handleChoose(item.id)}
                                    >
                                        {modify || addNvr || axyData ? item.id == clickNum ? "" : <div style={{
                                            width: 266,
                                            height: 146,
                                            borderRadius: 3,
                                            backgroundColor: "rgba(151, 151, 151, 0.1)",
                                            position: "absolute",
                                            top: 0,
                                        }}></div> : ""}
                                        <div
                                            style={{
                                                marginTop: 5,
                                                height: 65,
                                                width: 116,
                                                display: "flex",
                                                justifyContent: "center",
                                                alignItems: "center",
                                            }}
                                        >
                                            <img src={item.img} alt="设置" />
                                        </div>
                                        <div
                                            style={{
                                                marginTop: 2,
                                                fontSize: 14,
                                                color: "rgba(0, 0, 0, 0.85)",
                                            }}
                                        >
                                            {item.title}
                                        </div>
                                        <div
                                            style={{
                                                width: 210,
                                                height: 34,
                                                marginTop: 9,
                                                fontSize: 12,
                                                color: "rgba(0, 0, 0, 0.45)",
                                                textAlign: "center",
                                            }}
                                        >
                                            {item.text}
                                        </div>
                                        {clickNum === item.id ? (
                                            <div
                                                style={{
                                                    position: "absolute",
                                                    top: "-3px",
                                                    right: "-5px",
                                                }}
                                            >
                                                <img
                                                    src="/assets/images/background/topchoose.png"
                                                    alt="1"
                                                />
                                            </div>
                                        ) : (
                                            ""
                                        )}
                                    </div>

                                ))}

                            </div>
                            <IconChevronRight
                                style={{
                                    color: "rgba(0, 0, 0, 0.45)",
                                    fontSize: 16,
                                    marginRight: 18,
                                    cursor: "pointer",
                                }}
                                onClick={turnRight}
                            />
                        </div>
                    </div>
                    <div
                        style={{
                            height: 30,
                            marginLeft: "-24px",
                            marginRight: "-24px",
                            marginTop: 48,
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "space-between",
                        }}
                    >
                        <div
                            style={{
                                marginLeft: 29,
                                color: "#1859C1",
                                fontSize: 14,
                                fontWeight: 500,
                            }}
                        >
                            配置属性
                        </div>
                        {clickNum !== 2 ? (
                            <div style={{ display: "flex", marginRight: 43 }}>
                                <div
                                    style={{
                                        height: 30,
                                        width: 64,
                                        border: "1px solid #D9D9D9",
                                        borderRadius: "3px",
                                        color: "rgba(0, 0, 0, 0.65)",
                                        display: "flex",
                                        justifyContent: "center",
                                        alignItems: "center",
                                        cursor: "pointer",
                                        marginRight: 16,
                                    }}
                                    onClick={reset}
                                >
                                    <img
                                        src="/assets/images/background/Reset.png"
                                        alt="1"
                                        style={{ marginRight: 4 }}
                                    />
                                    重置
                                </div>
                                <div
                                    style={{
                                        height: 30,
                                        width: 64,
                                        border: "1px solid #1859C1",
                                        borderRadius: "3px",
                                        color: "#1859C1",
                                        backgroundColor: ash ? "" : "rgba(151, 151, 151, .2)",
                                        display: "flex",
                                        justifyContent: "center",
                                        alignItems: "center",
                                        cursor: "pointer",
                                    }}
                                    onClick={toTest}
                                >
                                    <img
                                        src="/assets/images/background/test.png"
                                        alt="1"
                                        style={{ marginRight: 4 }}
                                    />
                                    测试
                                </div>
                            </div>
                        ) : (
                            ""
                        )}
                    </div>
                    <div>
                        {clickNum == 1 ? (
                            <Spin tip={loadingTip} spinning={isloading}>
                                <FluoriteCamera
                                    cRef={fluoriteRef}
                                    CameraKind={CameraKind}
                                    CameraAbility={CameraAbility}
                                    cameraData={cameraData}
                                    ashTrue={() => setAsh(true)}
                                    ashFalse={() => setAsh(false)}
                                />
                            </Spin>
                        ) : clickNum == 2 ? (
                            <Spin tip={loadingTip} spinning={isloading}>
                                <NvrCamera nvrRef={nvrRef} cameraData={cameraData} addNvr={addNvr} nvrNumber={nvrNumber} />
                            </Spin>
                        ) : clickNum == 3 ? (
                            <Spin tip={loadingTip} spinning={isloading}>
                                <IpcCamera
                                    aRef={ipcRef}
                                    CameraKind={CameraKind}
                                    CameraAbility={CameraAbility}
                                    venderList={venderList}
                                    cameraData={cameraData}
                                    ashTrue={() => setAsh(true)}
                                    ashFalse={() => setAsh(false)}
                                />
                            </Spin>
                        ) : (
                            <Spin tip={loadingTip} spinning={isloading}>
                                <CascadeCamera
                                    dRef={cascadeRef}
                                    cameraData={cameraData}
                                    parentCamera={parentCamera}
                                    testComplete={testComplete.current}
                                    close={() => testComplete.current = false}
                                    ashTrue={() => setAsh(true)}
                                    ashFalse={() => setAsh(false)}
                                />
                            </Spin>
                        )}
                    </div>
                </>
            </Modal>
        </>
    );
}
function mapStateToProps (state) {
    const { auth, global, members, CameraKind, CameraAbility } = state;
    return {
        loading: members.isRequesting,
        user: auth.user,
        actions: global.actions,
        CameraKind: CameraKind.data || [],
        CameraAbility: CameraAbility.data || [],
    };
}

export default connect(mapStateToProps)(cameraModal);
