import {
    postDeviceGroupGetDeviceGroupList,
    postDeviceGroupGetDeviceGroupTree
} from '@/services/device/DeviceGroup';

import {PlusOutlined, RedoOutlined} from '@ant-design/icons';
import type {ActionType} from '@ant-design/pro-components';
import {
    PageContainer, ProCard, ProColumns, ProDescriptions, ProList, ProTable
} from '@ant-design/pro-components';
import {useIntl, useAccess} from '@umijs/max';
import {Button, message, Tag, Tree} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {DataNode} from "antd/es/tree";
import {Access, FormattedMessage, history} from "@@/exports";
import {postGetProjectByGroupId} from "@/services/project/Project";
import {postModelVersionGetModelVersionListByIds} from "@/services/resource/ModelVersion";
import {dateFormat} from "@/utils/common";
import UpdateForm from "./components/UpdateForm";


const AlgorithmSetting: React.FC = () => {
    /**
     * @en-US Pop-up window of new window
     * @zh-CN 新建窗口的弹窗
     *  */

    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const access = useAccess();
    const intl = useIntl();
    const actionRef = useRef<ActionType>();
    const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);


    const [hasInit, setHasInit] = useState<boolean>(false)
    const [nodeTreeData, setNodeTreeData] = React.useState<DataNode[]>([]);
    const [selectNodes, setSelectNodes] = React.useState<any[]>([]);
    const [currentRow, setCurrentRow] = useState<API.DeviceGroup>();
    const [currentCard, setCurrentCard] = useState<API.DeviceModelInGroup>();

    const [selectedRowsState, setSelectedRows] = useState<API.DeviceGroup[]>([]);
    const [tabs, setTabs] = useState([]);
    const [cardActionProps, setCardActionProps] = useState<'actions' | 'extra'>(
        'extra',
    );
    const [modelVersionData, setModelVersionData] = useState<any[]>([]);
    const [projectData, setProjectData] = useState<any>({});

    const handleUpdateModal = ()=>{
        if (updateModalOpen) {
            setUpdateModalOpen(false)
            setCurrentCard(undefined)
        } else {
            setUpdateModalOpen(true)
        }
    }

    const data = [
        '苏胜天人物识别算法',
        '苏胜天交警识别识别',
        '苏胜天车牌识别算法',
        '苏胜天语音识别算法',
        '苏胜天轨迹识别算法',
    ].map((item) => ({
        title: '苏胜天算法模型',
        subTitle: <Tag color="#5BD8A6">经典算法</Tag>,
        actions: [<a key="run">模型版本选择</a>],
        avatar:
            'https://gw.alipayobjects.com/zos/antfincdn/UCSiy1j6jx/xingzhuang.svg',
        content: (
            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: 'center',
                    width: '100%'
                }}
            >
                <div style={{fontSize: '24px', fontWeight: 'bold'}}>{item}</div>
                <div><img src="/images/model.png" alt="" style={{width: '160px'}}/></div>
                <div>版本：<span style={{fontSize: 18, fontWeight: "bold"}}>V1.2.4</span></div>
                <div>更新时间：<span style={{fontSize: 18, fontWeight: "bold"}}>2022-12-12</span></div>
            </div>
        ),
    }));

    const [tab, setTab] = useState('');
    const columns1: ProColumns<API.DeviceGroup>[] = [
        {
            title: (<FormattedMessage
                id="device.device_group.table.list.name"
                defaultMessage="$$$"/>),
            dataIndex: "name",
            hideInSearch: true,
        },

    ];

    const columns = [

        {
            title: (<FormattedMessage
                id="device.device_group.table.list.id"
                defaultMessage="id"/>),
            dataIndex: "id",
            sorter: true,
        },

        {
            title: (<FormattedMessage
                id="device.device_group.table.list.name"
                defaultMessage="$$$"/>),
            dataIndex: "name",
            hideInSearch: true,
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.code"
                defaultMessage="$$$"/>),
            dataIndex: "code",
            hideInSearch: true,
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.address"
                defaultMessage="$$$"/>),
            dataIndex: "address",
            hideInSearch: true,
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.telephone"
                defaultMessage="$$$"/>),
            dataIndex: "telephone",
            hideInSearch: true,
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.lon"
                defaultMessage="$$$"/>),
            dataIndex: "lon",
            hideInSearch: true,
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.lat"
                defaultMessage="$$$"/>),
            dataIndex: "lat",
            hideInSearch: true,
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.managerName"
                defaultMessage="$$$"/>),
            dataIndex: "managerName",
            hideInSearch: true,
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.managerPhone"
                defaultMessage="$$$"/>),
            dataIndex: "managerPhone",
            hideInSearch: true,
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.isEnable"
                defaultMessage="$$$"/>),
            dataIndex: "isEnable",
            filters: true, onFilter: true,
            hideInSearch: true,
            valueType: 'switch',
        },

        {
            title: (<FormattedMessage
                id="device.device_group.table.list.remark"
                defaultMessage="$$$"/>),
            dataIndex: "remark",
            hideInSearch: true,
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.createTime"
                defaultMessage="$$$"/>),
            dataIndex: "createTime",
            sorter: true,
            hideInSearch: true,
            valueType: 'dateTime',
        },


        {
            title: (<FormattedMessage
                id="device.device_group.table.list.updateTime"
                defaultMessage="$$$"/>),
            dataIndex: "updateTime",
            sorter: true,
            hideInSearch: true,
            valueType: 'dateTime',
        },
    ];


    useEffect(() => {


        postDeviceGroupGetDeviceGroupTree().then((resp) => {
            setNodeTreeData(resp.data.tree)
            setHasInit(true)
        }).catch(() => {
            message.error(intl.formatMessage({id: 'common.failure', defaultMessage: '$$$'}))
        })
    }, [])



    return (
        <PageContainer>
            <ProCard split="vertical">
                <ProCard title="网点选择" colSpan="30%" extra={<Button icon={<RedoOutlined/>} onClick={() => {
                    setSelectNodes([]);
                    actionRef.current?.reload()
                }}>重置</Button>}>
                    <ProTable<API.DeviceGroup>
                        headerTitle={intl.formatMessage({
                            id: 'pages.searchTable.title',
                            defaultMessage: '$$$',
                        })}
                        options={{search: true, fullScreen: false, setting: false, density: false, reload: false}}
                        actionRef={actionRef}
                        search={false}
                        rowKey="key"
                        onRow={(record) => {
                            return {
                                onClick: () => {
                                    if (record.id) {
                                        setCurrentRow(record);

                                        postGetProjectByGroupId({id: record.id}).then((resp) => {
                                            let tab_data = (resp?.data?.list || []).map((v: any) => {
                                                let model_data = (v?.models || []).map((item: any) => ({
                                                    title: '苏胜天算法模型',
                                                    subTitle: <Tag color="#5BD8A6">经典算法</Tag>,
                                                    actions: [<a key={item.id} onClick={()=>{
                                                        setCurrentCard({groupFkId: record.id, modelFkId: item.id})
                                                        handleUpdateModal()
                                                    }}>绑定设备</a>],
                                                    avatar:
                                                        'https://gw.alipayobjects.com/zos/antfincdn/UCSiy1j6jx/xingzhuang.svg',

                                                    content: (
                                                        <div
                                                            style={{
                                                                display: "flex",
                                                                flexDirection: "column",
                                                                alignItems: 'center',
                                                                width: '100%'
                                                            }}
                                                        >
                                                            <div style={{fontSize: '24px', fontWeight: 'bold'}}>{item.name}</div>
                                                            <div><img src="/images/model.png" alt="" style={{width: '160px'}}/></div>
                                                            <div>版本：<span style={{fontSize: 18, fontWeight: "bold"}}>{item.remark}</span></div>
                                                            <div>更新时间：<span style={{fontSize: 18, fontWeight: "bold"}}>{dateFormat(item.updateTime)}</span></div>
                                                        </div>
                                                    )
                                                }));
                                                console.log(88, model_data, data)
                                                // setProjectData({...projectData, [v.id]: v})
                                                return {
                                                    label: `项目：${v.name}`,
                                                    key: v.id,
                                                    children: (<ProList<any>
                                                        ghost={true}
                                                        itemCardProps={{
                                                            ghost: true,
                                                        }}
                                                        pagination={{
                                                            defaultPageSize: 8,
                                                            showSizeChanger: false,
                                                        }}
                                                        showActions="hover"
                                                        grid={{ gutter: 8, column: 4 }}
                                                        metas={{
                                                            title: {},
                                                            subTitle: {},
                                                            type: {},
                                                            avatar: {},
                                                            content: {},
                                                            actions: {
                                                                cardActionProps,
                                                            },
                                                        }}
                                                        headerTitle="项目模型列表"
                                                        dataSource={model_data}
                                                    />),


                                                }
                                            })
                                            if (tab_data.length) {
                                                setTab(tab_data[0].key)
                                            }
                                            setTabs(tab_data)
                                        })
                                    }
                                },
                            };
                        }}
                        pagination={{
                            showSizeChanger: false,
                            pageSize: 10,
                        }}
                        columnsState={{
                            persistenceKey: 'device_group_list',
                            persistenceType: 'localStorage'
                        }}
                        request={async (params = {}, sort) => {
                            const {current, ...rest} = params
                            const reqParams = {
                                page: current,
                                desc: false,
                                orderKey: "",
                                ...rest,
                            }
                            if (sort && Object.keys(sort).length) {
                                reqParams.orderKey = Object.keys(sort)[0]
                                let sort_select = sort[reqParams.orderKey]
                                reqParams.desc = sort_select === 'descend';
                            }
                            let resp = await postDeviceGroupGetDeviceGroupList({...reqParams, name: params?.keyword || ''})
                            return {
                                data: resp.data.list.map((v: API.DeviceGroup)=>{
                                    return {...v, key: v.id}
                                }),
                                success: resp.success,
                                total: resp.data.total,
                                current: resp.data.page,
                                pageSize: resp.data.pageSize
                            };

                        }}
                        columns={columns1}
                        rowSelection={{
                            onChange: (_, selectedRows) => {
                                // setSelectedRows(selectedRows);
                            },
                        }}
                    />
                </ProCard>
                <ProCard title="" colSpan="70%" headerBordered split={'horizontal'}>
                    <ProCard>
                        <ProDescriptions
                            column={2}
                            dataSource={currentRow}
                            title="网点详细信息"
                            tooltip="包含了从服务器请求，columns等功能"
                            columns={columns}
                        >
                        </ProDescriptions>
                    </ProCard>

                    <ProCard
                        tabs={{
                            activeKey: tab,
                            items: tabs,
                            onChange: (key) => {
                                let model_ids = projectData[key]?.inferConfig?.models || []
                                postModelVersionGetModelVersionListByIds({ids: model_ids}).then((resp)=>{
                                    let version_model_data = (resp?.data?.list || []).map((item) => {
                                        return {
                                            title: '苏胜天算法模型',
                                            subTitle: <Tag color="#5BD8A6">经典算法</Tag>,
                                            actions: [<a key="run" onClick={()=>{handleUpdateModal()}}>模型版本选择</a>],
                                            avatar:
                                                'https://gw.alipayobjects.com/zos/antfincdn/UCSiy1j6jx/xingzhuang.svg',
                                            content: (
                                                <div
                                                    style={{
                                                        display: "flex",
                                                        flexDirection: "column",
                                                        alignItems: 'center',
                                                        width: '100%'
                                                    }}
                                                >
                                                    <div style={{fontSize: '24px', fontWeight: 'bold'}}>{item}</div>
                                                    <div><img src="/images/model.png" alt="" style={{width: '160px'}}/></div>
                                                    <div>版本：<span style={{fontSize: 18, fontWeight: "bold"}}>V1.2.4</span></div>
                                                    <div>更新时间：<span style={{fontSize: 18, fontWeight: "bold"}}>2022-12-12</span></div>
                                                </div>
                                            ),
                                        }
                                    });
                                    setModelVersionData(version_model_data)
                                    console.log(99, modelVersionData)
                                })
                                setTab(key);
                            },
                        }}
                    ></ProCard>

                </ProCard>
            </ProCard>
            <UpdateForm
                updateModalOpen={updateModalOpen}
                values={currentCard || {}}
                handleModal={handleUpdateModal}
                reload={actionRef.current?.reload}
            />
        </PageContainer>
    );
};

export default AlgorithmSetting;
