import React, { useState, useEffect, useRef } from "react";
import { connect } from "react-redux";
import moment from "moment";
import { Button, Form, Table, Pagination, Skeleton, Popconfirm, SideSheet, Tag, } from "@douyinfe/semi-ui";
import "../style.less";
import { ApiTable } from "$utils";
import { Setup } from "$components";
import PushModal from "../components/pushModal";
import PushSideSheet from "../components/pushSideSheet";
// import SideSheets from "../components/sideSheet";

export const accessType = [
    { name: "萤石云", key: "yingshi" },
    { name: "NVR", key: "nvr" },
    { name: "IPC", key: "ipc" },
    { name: "级联", key: "cascade" },
];

const Carrierpigeon = (props) => {
    const { history, dispatch, actions, user, loading, StatusPushList } = props;
    const { offline } = actions;
    const [setup, setSetup] = useState(false);
    const [setupp, setSetupp] = useState([]);
    const [query, setQuery] = useState({ limit: 10, page: 0 }); //页码信息
    const [search, setearch] = useState({}); //搜索条件
    const [rowId, setRowId] = useState(); //表格数据id
    const [pigeonPush, setPigeonPush] = useState(false); //推送弹框
    const [pushTitle, setPushTitle] = useState(''); //提醒弹框
    const api = useRef();
    const searchData = useRef(search)
    const limits = useRef(); //每页实际条数
    const page = useRef(query.page);
    const PIGEON = "pigeon";
    const cameraList = useRef([]);//第三阶段监听范围摄像头列表
    const [sideSheetVisible, setSideSheetVisible] = useState(false);
    const [pushData, setPushData] = useState({});
    const [journal, setJournal] = useState([]);
    const tableList = [//表格属性
        {
            title: '推送信息',
            list: [
                { name: "策略类型", value: "pushWay" },
                { name: "推送机制", value: "noticeWay" },
                { name: "监听设备数量", value: "monitorCount" },
                { name: "累计推送次数", value: "logCount" },
            ]
        },
    ];
    const noticeWayObj = {
        'offline':'离线及时通知',
        'online':'上线及时通知',
        'timing':'定时统计',
    }
    useEffect(() => {
        attribute();
        dispatch(offline.getCameraListAll()).then((res) => {//第三步
            let mycameraList = res.payload.data
            for (let index = 0; index < mycameraList.length; index++) {
                mycameraList[index].label=mycameraList[index].name
                mycameraList[index].key=index+1
                mycameraList[index].value=String(mycameraList[index].id)
                if(mycameraList[index].type=='cascade'){
                    mycameraList[index].color='#808FD3'
                    mycameraList[index].abbr='级联'
                }
                else if(mycameraList[index].type=='nvr'){
                    mycameraList[index].color='#F6D86F'
                    mycameraList[index].abbr='NVR'
                }
                else if(mycameraList[index].type=='ipc'){
                    mycameraList[index].color='#1859C1'
                    mycameraList[index].abbr='IPC'
                }
                else{
                    mycameraList[index].color='#57CBD3'
                    mycameraList[index].abbr='莹石'
                }
            }
            cameraList.current=mycameraList
        });
        //初始化表格显示设置
        localStorage.getItem(PIGEON) == null
            ? localStorage.setItem(
                PIGEON,
                JSON.stringify(['pushWay','noticeWay','logCount','monitorCount'])
            )
            : "";
    }, []);

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

    const equipmentGetStatusPush = () => {
        searchData.current = { ...query, ...search }
        dispatch(offline.getStatusPush(searchData.current)).then((res) => {
            limits.current = res.payload.data.length
        });
    }
    const columns = [
        {
            title: "序号",
            render: (_, record, index) => {
                return index + 1;
            },
        },
        {
            title: "策略名称",
            dataIndex: "name",
            render: (_, r, index) => {
                return r.name
            },
        },
        {
            title: "操作",
            width: "20%",
            dataIndex: "",
            render: (_, row) => {
                return (
                    <div style={{ display: "flex" }}>
                        <Button
                            theme="borderless"
                            onClick={() => {
                                setPigeonPush(true);
                                // setTableNews(row);
                                setPushTitle('修改推送');
                                setPushData(row);
                                setRowId(row.id);
                            }}
                        >
                            修改
                        </Button>
                        {row.forbidden ? (
                            <Button
                                theme="borderless"
                                onClick={() => {
                                    dispatch(
                                        offline.putPushBanned(
                                            {
                                                configId: row.id,
                                                forbidden: !row.forbidden,
                                            },
                                            row.forbidden
                                        )
                                    ).then(() => {
                                        equipmentGetStatusPush();
                                    });
                                }}
                            >
                                启用
                            </Button>
                        ) : (
                            <Popconfirm
                                title="禁用期间产生的通知将不会触达收信端"
                                arrowPointAtCenter={false}
                                showArrow={true}
                                position="topRight"
                                onConfirm={() => {
                                    dispatch(
                                        offline.putPushBanned(
                                            {
                                                configId: row.id,
                                                forbidden: !row.forbidden,
                                            },
                                            row.forbidden
                                        )
                                    ).then(() => {
                                        equipmentGetStatusPush();
                                    });
                                }}
                            >
                                <Button theme="borderless">禁用</Button>
                            </Popconfirm>
                        )}
                        <Popconfirm
                            title="是否确定删除？"
                            arrowPointAtCenter={false}
                            showArrow={true}
                            position="topRight"
                            onConfirm={() => {
                                dispatch(offline.delPush(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 onClick={()=>{
                            dispatch(offline.getPushCopy(row.id)).then(() => {
                                equipmentGetStatusPush();
                            });
                        }} theme="borderless">
                            复制
                        </Button>
                        <Button onClick={()=>{
                            dispatch(offline.getPushLog(row.id)).then((res) => {
                                if(res.success){
                                    setJournal(res.payload.data);
                                }
                                else{
                                    setJournal([]);
                                }
                                setPushData(row);
                                setSideSheetVisible(true);
                            });
                        }} theme="borderless">
                            查看
                        </Button>
                    </div>
                );
            },
        },
    ];

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

        const column = [
            {
                title: "推送机制",
                dataIndex: "noticeWay",
                key: "noticeWay",
                render: (_, r, index) => {
                    let noticeWayValue=[]
                    for (let index = 0; index < r.noticeWay.length; index++) {
                        let val = r.noticeWay[index]
                        noticeWayValue.push(noticeWayObj[val])
                    }
                    let noticeWayString=noticeWayValue.join(';')
                    return noticeWayString;
                },
            },
            {
                title: "累计推送次数",
                dataIndex: "logCount",
                key: "logCount",
                render: (_, r, index) => {
                    return (r.logCount + '次')
                },
            },
            {
                title: "监听设备数量",
                dataIndex: "monitorCount",
                key: "monitorCount",
                render: (_, r, index) => {
                    return r.monitorCount
                },
            },
            {
                title: "策略类型",
                dataIndex: "pushWay",
                key: "pushWay",
                render: (_, r, index) => {
                    return r.pushWay=='email' ? '邮件通知' : '短信通知';
                },
            },
        ];
        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);
    }
    //条件赛选样式
    const screen = {
        width: 193,
        marginRight: 20,
        marginBottom: 16,
        color: "rgba(0, 0, 0, 0.65)",
    };

    return (
        <>
            <div>
                <video
                    id="nvrBanner"
                    autoPlay
                    loop
                    muted
                    style={{ width: "100%", objectFit: "cover", height: 171 }}
                    src="/assets/video/nvr_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: "32px",
                            textAlign: "center",
                            backgroundColor: "#D9EAFF",
                            color: "#1859C1",
                            cursor: "pointer",
                        }}
                        onClick={() => {
                            setPigeonPush(true);
                            setPushTitle('创建推送')
                        }}
                    >
                        创建推送
                    </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="name"
                            maxLength="36"
                            placeholder="请输入策略名称"
                            labelPosition="left"
                            style={screen}
                        />
                        <Form.Select
                            label="策略类型："
                            labelPosition="left"
                            field="pushWay"
                            style={screen}
                            placeholder="全部"
                            showClear
                        >
                            <Form.Select.Option value="">全部</Form.Select.Option>
                            <Form.Select.Option value="phone">短信通知</Form.Select.Option>
                            <Form.Select.Option value="email">邮件通知</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) => {
                                    setearch(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();
                                setearch({});
                                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);
                            }}
                        >
                            <img
                                src="/assets/images/background/setup.png"
                                alt="设置"
                                style={{ width: 18, height: 18 }}
                            />
                        </Button>
                    </div>
                </div>
                <Skeleton
                    loading={loading}
                    active={true}
                >
                    <Table
                        columns={setupp.filter((s) => s)}
                        dataSource={StatusPushList.rows}
                        bordered={false}
                        empty="暂无数据"
                        style={{
                            padding: "0px 20px",
                        }}
                        pagination={false}
                    />
                </Skeleton>

                <div
                    style={{
                        display: "flex",
                        justifyContent: "flex-end",
                        padding: "20px 20px",
                    }}
                >
                    <span style={{ lineHeight: "30px" }}>
                        共{StatusPushList.count}条策略
                    </span>
                    <Pagination
                        total={StatusPushList.count}
                        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
                        tableType={PIGEON}
                        tableList={tableList}
                        close={() => {
                            setSetup(false);
                            attribute();
                        }}
                    />
                ) : (
                    ""
                )}
                {pigeonPush&&<PushModal
                    rowId={rowId}
                    title={pushTitle}
                    pushData={pushData}
                    cameraList={cameraList.current}
                    close={() => {
                        setPigeonPush(false);
                        setRowId();
                        setPushData({})
                        equipmentGetStatusPush();
                    }}
                />}
                {sideSheetVisible&&<PushSideSheet
                    pushData={pushData}
                    journal={journal}
                    close={() => {
                        setSideSheetVisible(false);
                        setPushData({})
                    }}
                />}
            </div>
        </>
    );
};

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

export default connect(mapStateToProps)(Carrierpigeon);
