import React, { useState, useEffect, useRef } from "react";
import { connect } from "react-redux";
import moment from "moment";
import qs from "qs";
import {
    Button,
    Form,
    Table,
    Pagination,
    Popover,
    Tag,
    Skeleton,
    Popconfirm,
    Row,
} from "@douyinfe/semi-ui";
import { SimpleFileDownButton, VideoPlayModal } from "$components";
import "../style.less";
import CameraModal from "../components/cameraModal";
import RemarksModal from "../components/remarksModal";
import Setup from "../components/setup";
import SideSheets from "../components/sideSheet";
import { skeletonScreen } from "../components/skeletonScreen";
import { accessType } from "./nvr";

const CameraHeader = (props) => {
    const { dispatch, actions, user, loading, equipmentWarehouseCamera } = props;
    const [cameraModal, setCameraModal] = useState(false);
    const [remarksModal,setRemarksModal] = useState(false);
    const [videoPlay, setVideoPlay] = useState(false);
    const [modalName, setModalName] = useState("");
    const [setup, setSetup] = useState(false);
    const [sideSheet, setSideSheet] = useState(false);
    const [cameraSetup, setcameraSetup] = useState(false);
    const [setupp, setSetupp] = useState([]);
    const [venderList, setvenderList] = useState([]); //厂商信息
    const [query, setQuery] = useState({ limit: 10, page: 0 }); //页码信息
    const [search, setSearch] = useState({}); //搜索条件
    const [rowId, setRowId] = useState(); //表格数据id
    const [cameraData, setCameraData] = useState({}); //表格传递数据
    const [modify, setModify] = useState(false); //修改
    const [parentCamera, setParentCamera] = useState(""); //级联摄像头父级设备
    const [addNvr, setAddNvr] = useState(false); //nvr页面传递参数打开NVR摄像头添加弹框
    const [nvrNumber, setNvrNumber] = useState();
    const [videoObj, setVideoObj] = useState(); //播放条件
    const [axyData, setAxyData] = useState();
    const [cameraRemarks, setCameraRemarks] = useState([]);//备注
    const { equipmentWarehouse } = actions;
    const api = useRef();
    const searchData = useRef({})
    const limits = useRef(); //每页实际条数
    const page = useRef(query.page);
    const deviceClickb = useRef(true)
    const CAMERAS = "cameras";

    useEffect(() => {
        //安心云传参
        let isAxyData = props.location.search
        if (isAxyData) {
            setAxyData(qs.parse(isAxyData.slice(1)))
            setCameraModal(true)
        }
        //NVR传来的参数
        if (props.location.query) {
            setAddNvr(props.location.query.addNvr)
            setNvrNumber(props.location.query.serialNo)
            setCameraModal(true);
        }
        dispatch(actions.equipmentWarehouse.getVender()).then((res) => {
            setvenderList(res.payload.data);
            attribute(res.payload.data);
        });
        //初始化表格显示设置
        localStorage.getItem(CAMERAS) == null
            ? localStorage.setItem(
                CAMERAS,
                JSON.stringify(["state", "type", "manufactor"])
            )
            : "";
    }, []);

    useEffect(() => {
        equipmentGetCamera();
    }, [query, search]);

    const equipmentGetCamera = () => {
        searchData.current = { ...query, ...search }
        dispatch(equipmentWarehouse.getCamera(searchData.current)).then((res) => {
            limits.current = res.payload.data.data.length
        });
    }
    function equipmentStatus (data) {
        switch (data) {
            case "ON":
                return "在线"
            case "ONLINE":
                return "在线"
            case "OFF":
                return "离线"
            default:
                return "未知"
        }
    }

    function colorStatus (data) {
        switch (data) {
            case "ON":
                return "#04B234"
            case "ONLINE":
                return "#04B234"
            case "OFF":
                return "rgba(0, 0, 0, 0.45)"
            default:
                return "#1859C1"
        }
    }
    const columns = [
        {
            title: "序号",
            dataIndex: "",
            render: (text, r, index) => {
                return index + 1;
            },
        },
        {
            title: "设备名称",
            dataIndex: "name",
            render: (_, row) => {
                return (
                    <div>
                        {row.name}
                        <span style={{ color: "#1859C1" }}
                            onClick={() => {
                                if (deviceClickb.current) {
                                    if (row.type == "nvr") {
                                        setSearch({ ...search, nvrId: row.nvr.id })
                                    } else {
                                        setSearch({ ...search, externalDomain: row.externalDomain })
                                    }
                                    deviceClickb.current = false
                                } else {
                                    if (row.type == "nvr") {
                                        setSearch({ ...search, nvrId: null })
                                    } else {
                                        setSearch({ ...search, externalDomain: null })
                                    }
                                    deviceClickb.current = true
                                }
                            }}
                        >
                            {row.type == "nvr" ? `@${row.nvr.name}` : row.type == "cascade" ? `@${row.externalDomain}` : ""}
                        </span>
                    </div >
                );
            },
        },
        {
            title: "操作",
            width: "20%",
            dataIndex: "",
            render: (_, row) => {
                return (
                    <div style={{ display: "flex" }}>
                        <Button
                            theme="borderless"
                            onClick={() => {
                                setCameraData(row);
                                if (row.type == "cascade") {
                                    dispatch(equipmentWarehouse.getParentCamera({ cameraSerialNo: row.serialNo })).then((res) => {
                                        setParentCamera(res.payload.data.topSerialNo)
                                        if (res.success) {
                                            setCameraModal(true);
                                            setModify(true)
                                        }
                                    })
                                } else {
                                    setCameraModal(true);
                                    setModify(true)
                                }
                            }}
                        >
                            修改

                        </Button>
                        <Button
                            theme="borderless"
                            onClick={() => {
                                setSideSheet(true);
                                setcameraSetup(true);
                                setRowId(row.id);
                            }}
                        >
                            查看
                        </Button>
                        <Button
                            theme="borderless"
                            onClick={() => {
                                let data = row?.cameraRemarks.map((item)=>item.remark)
                                if (row.type == "yingshi") {
                                    setVideoObj({
                                        type: row.type,
                                        serialNo: row.serialNo,
                                        yingshiToken: row.secretYingshi?.token,
                                        playUrlSd: row.gbCamera?.playUrl?.liveUrl?.sd?.ezopen,
                                        playUrlHd: row.gbCamera?.playUrl?.liveUrl?.hd?.ezopen,
                                        content:data,
                                    })
                                } else {
                                    setVideoObj({
                                        type: row.type,
                                        audio: false,
                                        serialNo: row.serialNo,
                                        topSerialNo: row.topSerialNo,
                                        playUrlSd: row.gbCamera?.playUrl?.liveUrl?.sd["WS-RAW"],
                                        content:data,
                                    })
                                }
                                setVideoPlay(true)

                            }}
                        >
                            播放
                        </Button>
                        {row.forbidden ? (
                            <Button
                                theme="borderless"
                                onClick={() => {
                                    dispatch(
                                        equipmentWarehouse.putForbidden(
                                            {
                                                cameraId: row.id,
                                                forbidden: !row.forbidden,
                                            },
                                            row.forbidden
                                        )
                                    ).then(() => {
                                        dispatch(equipmentWarehouse.getCamera(searchData.current))
                                    });
                                }}
                            >
                                启用
                            </Button>
                        ) : (
                            <Popconfirm
                                title="禁用后下级业务系统将无法获取该视频流的所有信息。"
                                arrowPointAtCenter={false}
                                showArrow={true}
                                position="topRight"
                                onConfirm={() => {
                                    dispatch(
                                        equipmentWarehouse.putForbidden(
                                            {
                                                cameraId: row.id,
                                                forbidden: !row.forbidden,
                                            },
                                            row.forbidden
                                        )
                                    ).then(() => {
                                        dispatch(equipmentWarehouse.getCamera(searchData.current))
                                    });
                                }}
                            >
                                <Button theme="borderless">禁用</Button>
                            </Popconfirm>
                        )}

                        <Popconfirm
                            title="删除后设备视频流会被中断，是否确定删除？"
                            arrowPointAtCenter={false}
                            showArrow={true}
                            position="topRight"
                            onConfirm={() => {
                                dispatch(
                                    equipmentWarehouse.delCamera(row.id)
                                ).then(() => {
                                    if (page.current > 0 && limits.current < 2) {
                                        setQuery({ limit: 10, page: page.current - 1 })
                                    } else {
                                        setQuery({ limit: 10, page: page.current })
                                    }
                                });
                            }}
                        >
                            <Button theme="borderless">删除</Button>
                        </Popconfirm>
                        <Button
                            theme="borderless"
                            onClick={() => {
                                setCameraRemarks(row.cameraRemarks||[])
                                setRowId(row.id);
                                setRemarksModal(true)
                            }}
                        >
                            备注
                        </Button>
                    </div>
                );
            },
        },
    ];

    //获取表格属性设置
    function attribute (data) {
        const arr = localStorage.getItem(CAMERAS)
            ? JSON.parse(localStorage.getItem(CAMERAS))
            : [];

        const column = [
            {
                title: "设备厂家",
                dataIndex: "venderId",
                key: "manufactor",
                render: (_, r, index) => {
                    let manufactorName = data.find((item) => item.id == r.venderId);
                    return manufactorName ? manufactorName.name : "未知";
                },
            },
            {
                title: "接入类型",
                dataIndex: "cameraAbility.type",
                key: "type",
                render: (_, r, index) => {
                    let access = accessType.find((item) => item.key == r.type);
                    return access ? access.name : "";
                },
            },
            {
                title: "设备状态",
                dataIndex: "channelCount",
                key: "state",
                render: (_, r, index) => {
                    let status = r.gbCamera;
                    return (
                        <div>
                            <span
                                style={{
                                    width: 8,
                                    height: 8,
                                    display: "inline-block",
                                    borderRadius: "50%",
                                    backgroundColor: r.forbidden ? "red" : status ? colorStatus(status.online) : "",
                                    margin: "0 8px 0 0",
                                }}
                            />
                            {r.forbidden ? "禁用" : status ? equipmentStatus(status.online) : ""}
                        </div>
                    );
                },
            },
            {
                title: "云台支持",
                dataIndex: "cloudControl",
                key: "support",
                render: (text, r, index) => {
                    return r.cloudControl ? "支持" : "不支持";
                },

            },
            {
                title: "内存卡信息",
                dataIndex: "memoryCard",
                key: "memoryCard",
            },
            {
                title: "设备创建时间",
                dataIndex: "createTime",
                key: "time",
                render: (_, r, index) => {
                    return moment(r.createTime).format("YYYY-MM-DD HH:MM:SS");
                },
            },
            {
                title: "设备添加账号",
                dataIndex: "size",
                key: "account",
                render: (text, r, index) => {
                    return r.createUser?.namePresent
                },
            },
            {
                title: "项目名称",
                dataIndex: "updateTime",
                key: "name",
                render: (_, r, index) => {
                    return r.station.length == 0
                        ? ""
                        : station(r, "name", _, "projects")
                },
            },
            {
                title: "pcode",
                dataIndex: "updateTime",
                key: "pcode",
                render: (_, r, index) => {
                    return r.station.length == 0
                        ? ""
                        : station(r, "url", _, "projects")
                },
            },
            {
                title: "结构物",
                dataIndex: "",
                key: "structure",
                render: (_, r, index) => {
                    return r.station.length == 0
                        ? ""
                        : station(r, "name", r.station[0].structure.name, _, "structure")
                },
            },
            {
                title: "测点",
                dataIndex: "updateTime",
                key: "measuringPoint",
                render: (_, r, index) => {
                    return r.station.length == 0
                        ? ""
                        : station(r, "name", r.station[0].name, _, "point")
                },
            },
            {
                title: "监测因素",
                dataIndex: "updateTime",
                key: "factor",
                render: (_, r, index) => {
                    return r.station.length == 0
                        ? ""
                        : station(r, "name", r.station[0].factor.name)
                },
            },
        ];
        for (let i = 0; i < arr.length; i++) {
            let colum = column.filter((item) => {
                return item.key === arr[i];
            });
            columns.splice(i + 2, 0, colum[0]);
        }
        setSetupp(columns);
    }

    //表格请求数据中station属性数据的展示
    function station (r, name, data, projects, exhibition) {
        let datas = []
        if (projects == "projects") {
            r.station.map((v) => {
                if (v.structure.projects.length > 0) {
                    v.structure.projects.map((item) => datas.push(item[name]))
                }
            })
        } else {
            r.station.map((v) => {
                if (exhibition == "structure") {
                    datas.push(v.structure.name)
                } else {
                    if (exhibition == "point") {
                        datas.push(v.name)
                    } else {
                        datas.push(v.factor.name)
                    }
                }
            })
        }
        let dataSet = [...(new Set(datas))]
        return dataSet.length > 0 ? <Popover
            key="updateTime"
            position="top"
            content={dataSet.length > 1 ?
                <article style={{ padding: 12 }}>
                    {dataSet.map((v, index) => <div key={index}>{v}</div>)}
                </article>
                : ""
            }
        >
            <Tag>{dataSet.length > 1 ? `${dataSet[0]}...` : dataSet.length > 0 ? dataSet[0] : ""}</Tag>
        </Popover> : ""

    }
    //条件赛选样式
    const screen = {
        width: 193,
        marginRight: 20,
        marginBottom: 16,
        color: "rgba(0, 0, 0, 0.65)",
    };

    return (
        <>
            <div style={{ position: "" }}>
                <video
                    id="cameraBanner"
                    autoPlay
                    loop
                    muted
                    style={{ width: "100%", objectFit: "cover", height: 171 }}
                    src="/assets/video/camera_banner.mp4"
                    type="video/mp4"
                />
                <div style={{ position: "absolute", top: 12 }}>
                    <div
                        style={{
                            fontSize: 22,
                            paddingTop: 15,
                            marginLeft: 21,
                        }}
                    >
                        摄像头管理
                    </div>
                    <div
                        style={{
                            fontSize: 14,
                            paddingTop: 18,
                            marginLeft: 20,
                        }}
                    >
                        对监控摄像设备设备添加、修改、删除的硬件管理页面。
                    </div>
                    <div
                        style={{
                            fontSize: 14,
                            marginTop: 28,
                            marginLeft: 21,
                            width: 89,
                            height: 32,
                            lineHeight: 32 + "px",
                            textAlign: "center",
                            backgroundColor: "#D9EAFF",
                            color: "#1859C1",
                            cursor: "pointer",
                        }}
                        onClick={() => {
                            setModalName("add");
                            setCameraModal(true);
                        }}
                    >
                        添加摄像头
                    </div>
                </div>
            </div>

            <div
                style={{
                    width: "100%",
                    background: "#FFFFFF",
                    borderRadius: 3,
                    padding: "8px 20px",
                    marginTop: 20,
                }}
            >
                <div
                    style={{
                        height: 22,
                        fontSize: 16,
                        fontFamily: "PingFangSC-Medium, PingFang SC",
                        fontWeight: "bold",
                        color: " rgba(0, 0, 0, 0.85)",
                        lineHeight: "22px",
                        marginBottom: 16,
                    }}
                >
                    筛选条件
                </div>
                <div style={{ display: "flex" }}>
                    <Form
                        onSubmit={(values) => console.log(values)}
                        // onValueChange={values=>console.log(values)}
                        getFormApi={(formApi) => (api.current = formApi)}
                        layout="horizontal"
                        style={{ position: "relative", width: "100%", flex: 1 }}
                    >
                        <Form.Input
                            label="设备搜索："
                            field="keyword"
                            maxLength="36"
                            placeholder="请输入设备名称"
                            labelPosition="left"
                            style={screen}
                        />
                        <Form.Select
                            label="接入类型："
                            labelPosition="left"
                            field="type"
                            style={screen}
                            placeholder="全部"
                            showClear
                        >
                            {accessType.map((item) => {
                                return (
                                    <Form.Select.Option key={item.key} value={item.key}>
                                        {item.name}
                                    </Form.Select.Option>
                                );
                            })}
                        </Form.Select>
                        <Form.Select
                            label="厂家筛选："
                            labelPosition="left"
                            style={screen}
                            field="venderId"
                            placeholder="全部"
                            showClear
                        >
                            {venderList.map((item) => {
                                return (
                                    <Form.Select.Option key={item.id} value={item.id}>
                                        {item.name}
                                    </Form.Select.Option>
                                );
                            })}
                        </Form.Select>
                        <Form.Select
                            label="状态查询："
                            labelPosition="left"
                            field="state"
                            style={screen}
                            placeholder="全部"
                            showClear
                        >
                            <Form.Select.Option value="ON">在线</Form.Select.Option>
                            <Form.Select.Option value="OFF">离线</Form.Select.Option>
                            <Form.Select.Option value="UNKONW">未知</Form.Select.Option>
                            <Form.Select.Option value="DISABLED">禁用</Form.Select.Option>
                        </Form.Select>
                        {/* <Form.Select
                 label="关联项目："
              labelPosition="left"
              field="type3"
              style={screen}
              placeholder="全部"
               showClear
            >
              <Form.Select.Option value="智慧环保">
                飞尚科技1
              </Form.Select.Option>
              <Form.Select.Option value="智慧水务">
                飞尚科技2
              </Form.Select.Option>
            </Form.Select> */}
                    </Form>
                    <div
                        style={{
                            width: 150,
                            display: "flex",
                            justifyContent: "flex-end",
                            alignItems: "flex-end",
                        }}
                    >
                        <Button
                            theme="solid"
                            type="primary"
                            style={{
                                width: 65,
                                height: 30,
                                borderRadius: 3,
                                marginBottom: 20,
                                marginRight: 20,
                            }}
                            onClick={() => {
                                api.current.validate().then((v) => {
                                    setSearch(v);
                                    setQuery({ limit: 10, page: 0 })
                                });
                            }}
                        >
                            搜素
                        </Button>
                        <Button
                            theme="light"
                            type="primary"
                            style={{
                                width: 65,
                                height: 30,
                                backGround: "#FFFFFF",
                                borderRadius: 3,
                                border: "1px solid #D9D9D9",
                                marginBottom: 20,
                            }}
                            onClick={() => {
                                api.current.reset();
                                setSearch({});
                                setQuery({ limit: 10, page: 0 })
                            }}
                        >
                            重置
                        </Button>
                    </div>
                </div>
            </div>
            <div style={{ background: "#FFFFFF", marginTop: 5 }}>
                <div
                    style={{
                        width: "100%",
                        display: "flex",
                        justifyContent: "space-between",
                        padding: "13px 20px",
                    }}
                >
                    <div
                        style={{
                            width: 64,
                            height: 22,
                            fontSize: 16,
                            fontfAmily: "PingFangSC-Medium, PingFang SC",
                            fontWeight: "bold",
                            color: "rgba(0, 0, 0, 0.85)",
                            lineHeight: "22px",
                        }}
                    >
                        设备列表
                    </div>
                    <div>
                        <Button
                            style={{
                                width: 32,
                                height: 32,
                                background: "#D9D9D9",
                                borderadius: 3,
                                marginRight: 20,
                            }}
                            type="primary"
                            key="primary"
                            onClick={() => {
                                setSetup(true);
                                setcameraSetup(true);
                            }}
                        >
                            <img
                                src="/assets/images/background/setup.png"
                                alt="设置"
                                style={{ width: 18, height: 18 }}
                            />
                        </Button>
                        <SimpleFileDownButton src="camera/export" />
                    </div>
                </div>
                <Skeleton
                    loading={loading}
                    active={true}
                    placeholder={skeletonScreen()}
                >
                    <Table
                        columns={setupp.filter((s) => s)}
                        dataSource={equipmentWarehouseCamera.data}
                        bordered={false}
                        empty="暂无数据"
                        style={{
                            padding: "0px 20px",
                        }}
                        pagination={false}
                    />
                </Skeleton>
                <div
                    style={{
                        display: "flex",
                        justifyContent: "flex-end",
                        padding: "20px 20px",
                    }}
                >
                    <span style={{ lineHeight: "30px" }}>
                        共{equipmentWarehouseCamera.total}个设备
                    </span>
                    <Pagination
                        className="22"
                        total={equipmentWarehouseCamera.total}
                        showSizeChanger
                        currentPage={query.page + 1}
                        pageSizeOpts={[10, 20, 30, 40]}
                        onChange={(currentPage, pageSize) => {
                            setQuery({ limit: pageSize, page: currentPage - 1 });
                            page.current = currentPage - 1
                        }}
                    />
                </div>

                {setup ? (
                    <Setup
                        visible={true}
                        CAMERAS={CAMERAS}
                        cameraSetup={cameraSetup}
                        close={() => {
                            setSetup(false);
                            attribute(venderList);
                            setcameraSetup(false);
                        }}
                    />
                ) : (
                    ""
                )}

                {sideSheet ? (
                    <SideSheets
                        visible={true}
                        rowId={rowId}
                        venderList={venderList}
                        accessType={accessType}
                        cameraSetup={cameraSetup}
                        close={() => {
                            setSideSheet(false);
                            setcameraSetup(false);
                        }}
                    />
                ) : (
                    []
                )}
            </div>

            {cameraModal ? (
                <CameraModal
                    visible={true}
                    venderList={venderList}
                    cameraData={cameraData}
                    modify={modify}
                    addNvr={addNvr}
                    nvrNumber={nvrNumber}
                    parentCamera={parentCamera}
                    axyData={axyData}
                    close={() => {
                        setCameraModal(false);
                        setCameraData({});
                        setModify(false)
                        setParentCamera("")
                        setAddNvr(false)
                        setNvrNumber("")
                        setAxyData("")
                        equipmentGetCamera()
                    }}
                    modalName={modalName}
                />
            ) : (
                ""
            )}
            {videoPlay ?
                <VideoPlayModal
                    visible={true}
                    videoObj={videoObj}
                    close={() => {
                        setVideoPlay(false)
                    }} />
                : ""
            }
            {
                remarksModal?
                <RemarksModal
                visible={true}
                rowId={rowId}
                cameraRemarks={cameraRemarks}
                close={() => {
                    setRemarksModal(false);
                    setRowId();
                    equipmentGetCamera();
                }} >
                </RemarksModal>:''
            }
        </>
    );
};

function mapStateToProps (state) {
    const { auth, global, members, equipmentWarehouseCamera } = state;
    return {
        loading:
            equipmentWarehouseCamera.isRequesting && !equipmentWarehouseCamera.data,
        user: auth.user,
        actions: global.actions,
        members: members.data,
        equipmentWarehouseCamera: equipmentWarehouseCamera.data || [],
    };
}

export default connect(mapStateToProps)(CameraHeader);
