import React, { useState, useEffect, useRef } from "react";
import { connect } from "react-redux";
import moment from "moment";
import { Button, Form, Table, Pagination, Skeleton, Popconfirm, Popover, Tag, } from "@douyinfe/semi-ui";
import { IconSort,IconCaretdown,IconCaretup } from '@douyinfe/semi-icons';
import "../style.less";
import {Setup} from "$components";

import ProgrammeModal from "../components/programmeModal";
import NotesModal from "../components/notesModal";

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

const Statuscode = (props) => {
    const { history, dispatch, actions, user, loading, StatusList } = props;
    const { offline } = actions;
    const [setup, setSetup] = useState(false);//表格设置弹框
    const [programme, setProgramme] = useState(false);//方案弹框
    const [notes, setNotes] = useState(false);//释义弹框
    const [setupp, setSetupp] = useState([]);
    const [query, setQuery] = useState({ limit: 10, page: 0 }); //页码信息
    const [search, setearch] = useState({}); //搜索条件
    const [rowId, setRowId] = useState(); //表格数据id
    const api = useRef();
    const searchData = useRef(search)
    const page = useRef(query.page);
    const CODE = "code";
    const [nodesAll, setNodesAll] = useState(true);//是否批量
    const [mysorter, setMysorter] = useState(true);//排序
    const sorter = useRef(false);//排序
    const [resolve, setResolve] = useState([]);//解决方案
    const [tableNews, setTableNews] = useState([]);//表格当前行数据
    const tableList = [//表格属性
        {
            title:'状态码信息',
            list:[
                { name: "常规解决方案", value: "resolve" },
                { name: "状态频率", value: "logCount" },
            ]
        },
    ];
    useEffect(() => {
        //初始化表格显示设置
        attribute();
        localStorage.getItem(CODE) == null
            ? localStorage.setItem(
                CODE,
                JSON.stringify(["resolve", "logCount"])
            )
            : "";
    }, [sorter.current]);

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

    const codegetStatus = () => {
        searchData.current = { ...query, ...search }
        dispatch(offline.getStatus(searchData.current)).then((res) => {
        });
    }
    function banned(row){
        dispatch(offline.putStatueBanned({statusId: row.id,forbidden: !row.forbidden,})).then(() => {
            dispatch(offline.getStatus(searchData.current))
        });
    }
    const columns = [
        {
            title: "状态码",
            dataIndex: "status",
            render: (_, record, index) => {
                return record.status
            },
        },
        {
            title: "平台",
            dataIndex: "platform",
            render: (_, r, index) => {
                let platform=r.platform
                return accessType[platform]
                 
            },
        },
        
        {
            title: "错误描述",
            dataIndex: "describe",
            render: (_, r, index) => {
                return r.describe
            },
        },
        {
            title: "官方释义",
            dataIndex: "paraphrase",
            render: (_, r, index) => {
                return r.paraphrase
            },
        },
        {
            title: "我的自定义释义",
            dataIndex: "paraphraseCustom",
            render: (_, r, index) => {
                return r.paraphraseCustom
            },
        },
        {
            title: "操作",
            width: "20%",
            dataIndex: "",
            render: (_, row) => {
                return (
                    <div style={{ display: "flex" }}>
                        {row.forbidden ? (
                            <Button
                                theme="borderless"
                                onClick={() => banned(row)}
                            >
                                启用
                            </Button>
                        ) : (
                            <Popconfirm
                                title="禁用后，您的自定义释义将会失效。"
                                arrowPointAtCenter={false}
                                showArrow={true}
                                position="topRight"
                                onConfirm={() => banned(row)}
                            >
                                <Button theme="borderless">禁用</Button>
                            </Popconfirm>
                        )}
                        <Button
                            theme="borderless"
                            onClick={() => {
                                setNotes(true);
                                setNodesAll(false);
                                setTableNews(row);
                                setRowId(row.id);
                            }}
                        >
                            释义
                        </Button>
                        <Button theme="borderless"
                            onClick={() => {
                                setProgramme(true);
                                setRowId(row.id);
                                setResolve(row.resolve);
                        }}>
                            方案
                        </Button>
                    </div>
                );
            },
        },
    ];
    function tosorter(){
        setMysorter(false)
        if(sorter.current=="descend"){
            searchData.current = { ...query, ...search, orderDirection:'ASC',orderBy:'logCount'}
            dispatch(offline.getStatus(searchData.current)).then((res) => {
                    sorter.current='ascend'
                    setMysorter('ascend')
            });
        }
        else if(sorter.current=="ascend"){
            searchData.current = { ...query, ...search}
            dispatch(offline.getStatus(searchData.current)).then((res) => {
                sorter.current=''
                setMysorter('')
            });
        }
        else{
            searchData.current = { ...query, ...search, orderDirection:'DESC',orderBy:'logCount'}
            dispatch(offline.getStatus(searchData.current)).then((res) => {
                sorter.current='descend'
                setMysorter('descend')
            });
        }
    }
    //获取表格属性设置
    function attribute () {
        const arr = localStorage.getItem(CODE)
            ? JSON.parse(localStorage.getItem(CODE))
            : [];
        const column = [
            {
                title: "常规解决方案",
                dataIndex: "resolve",
                key:'resolve',
                render: (_, r, index) => {
                    let myresolve=''
                    if(r.resolve.length>0){
                        let myresolveList=[];
                        for (let index = 0; index < r.resolve.length; index++) {
                            if(r.resolve[index]&&r.resolve[index].resolve){
                                myresolveList.push(r.resolve[index].resolve)
                            }
                        }
                        myresolve=myresolveList.join(';');
                    }
                    return myresolve
                },
            },
            {
                title:(<span onClick={tosorter}>
                        状态频率（近30日）
                        {mysorter=='descend'?<IconCaretdown />:mysorter=='ascend'?<IconCaretup />:<IconSort />}
                        </span>),
                dataIndex: "logCount",
                key:'logCount',
                render: (_, r, index) => {
                    return r.logCount
                },
            },
        ];
        let mycolumns=columns
        for (let i = 0; i < arr.length; i++) {
            let colum = column.filter((item) => {
                return item.key === arr[i];
            });
            mycolumns.splice(i + 5, 0, colum[0]);
        }
        setSetupp(mycolumns);
    }
    //条件赛选样式
    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>
            </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"
                            style={screen}
                            field="forbidden"
                            placeholder="全部"
                            showClear
                        >
                            <Form.Select.Option value="">全部</Form.Select.Option>
                            <Form.Select.Option value="false">启用</Form.Select.Option>
                            <Form.Select.Option value="true">禁用</Form.Select.Option>
                        </Form.Select>
                        <Form.Select
                            label="自定义释义："
                            labelPosition="left"
                            field="paraphraseCustom"
                            style={screen}
                            placeholder="全部"
                            showClear
                        >
                            <Form.Select.Option value="">全部</Form.Select.Option>
                            <Form.Select.Option value="false">已设置</Form.Select.Option>
                            <Form.Select.Option value="true">未设置</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: 84,
                            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>
                        <Button
                            theme="solid"
                            type="primary"
                            style={{
                                width: 65,
                                height: 32,
                                borderRadius: 3,
                            }}
                            onClick={() => {
                                setNotes(true);
                                setNodesAll(true);
                                setTableNews([]);
                            }}
                        >
                            批量设置
                        </Button>
                    </div>
                </div>
                <Skeleton
                    loading={loading}
                    active={true}
                >
                <Table
                        columns={setupp.filter((s) => s)}
                        dataSource={StatusList.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" }}>
                        共{StatusList.count}个状态码
                    </span>
                    <Pagination
                        total={StatusList.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={CODE}
                        tableList={tableList}
                        close={() => {
                            setSetup(false);
                            attribute();
                        }}
                    />
                ) : (
                    ""
                )}
                {programme&&<ProgrammeModal
                    rowId={rowId}
                    resolve={resolve}
                    close={() => {
                        setProgramme(false);
                        setRowId();
                        codegetStatus();
                    }}
                />}
                {notes&&<NotesModal
                    rowId={rowId}
                    nodesAll={nodesAll}
                    tableNews={tableNews}
                    close={() => {
                        setNotes(false);
                        setRowId();
                        codegetStatus();
                    }}
                />}
            </div>
        </>
    );
};

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

export default connect(mapStateToProps)(Statuscode);
