/*
 * @Author: cclu
 * @Date: 2022-04-29 15:23:46
 * @LastEditTime: 2025-03-28 17:43:25
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 菜单模块管理
 * @FilePath: \cloud-platform\src\pages\Setting\Module\cate.tsx
 */
// 菜单管理列表
import ProTable from '@ant-design/pro-table';
import React, { useState, useRef } from 'react';
import type { ConnectState } from "@/models/connect";
import { connect } from "umi";
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import { Button, message, TreeSelect, Form, Space } from 'antd';
import { ModalForm, ProFormText, ProFormDigit, ProFormTextArea, ProFormRadio } from '@ant-design/pro-form';
import * as Icon from '@ant-design/icons'

import type { FormInstance } from 'antd';
import type { ModuleItem, SystemMenuModel } from './data';
import type { ProColumns, ActionType } from '@ant-design/pro-table';

import { getSystemMenu, deleteSystemMenu, updataSystemMenu, updataModule } from './service'
import './modelStyle.less'
import { CurrentUser } from 'umi';

/**
 * @en-US Add node
 * @zh-CN 新增或更新菜单数据
 * @param fields 菜单数据对象
 */
const handleAddUpdate = async (fields: SystemMenuModel | ModuleItem) => {
    const hide = message.loading('正在提交...');
    try {
        const result = fields?.SYSTEMMENU_NAME ? await updataSystemMenu(fields as SystemMenuModel) : await updataModule(fields as ModuleItem)

        hide();
        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`)
            return false
        }
        message.success(fields.SYSTEMMENU_ID ? "更新成功！" : "新建成功！")
        return true
    } catch (error) {
        hide();
        message.error("提交失败")
        return false
    }
}
/**
 * @en-US delete node
 * @zh-CN 删除节点
 * @param fields
 */
const handleDelete = async (nodeId: number) => {
    const hide = message.loading('正在更新...');
    try {
        const result = await deleteSystemMenu(nodeId)

        hide();
        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Code}:状态更新失败`)
            return false
        }
        message.success("状态更新成功！")
        return true
    } catch (error) {
        hide();
        message.error("状态更新失败")
        return false
    }
}

/**
 * @description: 菜单管理
 * @param {*}
 * @return {*}
 */
const DataDictionary: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modelFormRef = useRef<FormInstance>();
    const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 新建菜单窗口的弹窗
    const [createModelVisible, handleModelVisible] = useState<boolean>(false); // 发布模块更新窗口的弹窗
    const [menuTree, setMenuTree] = useState<[]>(); // 树结构数据菜单 用于弹出编辑时选择上级

    const [currentRow, setCurrentRow] = useState<SystemMenuModel | ModuleItem | any>();
    // 菜单表格列配置
    const columns: ProColumns<SystemMenuModel>[] = [

        {
            title: '菜单名称',
            dataIndex: 'SYSTEMMENU_NAME',
            // width: 580,
            hideInSearch: true,

        },
        {
            title: '菜单图标',
            dataIndex: 'SYSTEMMENU_ICO',
            hideInSearch: true,
            // width: 120,
            render: (_, record) => {
                const reg = /<(.*) \/>/;

                if (record?.SYSTEMMENU_ICO) {
                    // console.log(reg.exec(record?.SYSTEMMENU_ICO))

                    const [iconName] = reg.exec(record?.SYSTEMMENU_ICO)?.reverse() || ['']
                    return iconName && Icon[iconName] ? React.createElement(Icon[iconName]) : '-'
                }
                return '-'

            }
        },
        {
            title: '菜单索引',
            dataIndex: 'SYSTEMMENU_INDEX',
            hideInSearch: true,
            width: 180,
        },
        {
            title: '状态',
            dataIndex: 'SYSTEMMENU_STATUS',
            hideInSearch: true,
            width: 180,
            valueEnum: {
                0: { text: '无效', status: 'Default' },
                1: { text: '有效', status: 'Processing' },
                2: { text: '隐藏', status: 'warning' },
            },
        },
        {
            title: '菜单状态',
            dataIndex: 'MenuStatus',
            // hideInSearch: true,
            hideInTable: true,
            valueEnum: {
                0: { text: '无效', status: 'Default' },
                1: { text: '有效', status: 'Processing' },
                2: { text: '隐藏', status: 'warning' },
            },
        },
        {
            title: '说明',
            dataIndex: 'SYSTEMMENU_DESC',
            width: 200,
            hideInSearch: true
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            hideInDescriptions: true,
            width: 260,
            render: (_, record) => <Space>
                <a
                    key="edit"
                    onClick={() => {
                        setCurrentRow(record);
                        handleModalVisible(true);
                    }}
                >
                    编辑
                </a>
                <a
                    key="editable"
                    onClick={() => {
                        setCurrentRow({ SYSTEMMENU_ID: record.SYSTEMMENU_ID, SYSTEMMODULE_STATUS: 1 })
                        handleModelVisible(true)
                        // history.push(`/setting/module/detail/${record?.SYSTEMMENU_ID}`)
                    }}
                >
                    新增子模块
                </a>
                {!!record.SYSTEMMENU_STATUS &&
                    <a onClick={async () => {
                        if (record) {

                            const { SYSTEMMENU_ID } = record
                            const success = (SYSTEMMENU_ID ? await handleDelete(SYSTEMMENU_ID) : false)
                            if (success) {
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }

                            }
                        }
                    }}>无效</a>
                }
                {!record.SYSTEMMENU_STATUS && <a onClick={async () => {
                    const success = (record.SYSTEMMENU_ID ? await handleAddUpdate({ ...record, SYSTEMMENU_STATUS: 1 }) : false)
                    if (success) {
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }

                    }
                }}>有效</a>}
            </Space>
        }

    ]
    // 模块列表
    const expandedRowRender = (data: any) => {

        return (data.SystemModuleList && data.SystemModuleList.length > 0 ?
            <ProTable<ModuleItem>
                rowKey="SYSTEMMODULE_ID"
                columns={[
                    {
                        title: '模块名称',
                        dataIndex: 'SYSTEMMODULE_NAME',
                    },

                    {
                        title: '模块地址',
                        dataIndex: 'SYSTEMMODULE_URL',
                        // width:390,
                        hideInSearch: true
                    },
                    {
                        title: '菜单索引',
                        dataIndex: 'SYSTEMMODULE_INDEX',
                        width: 180,
                        hideInSearch: true
                    },

                    {
                        title: '状态',
                        dataIndex: 'SYSTEMMODULE_STATUS',
                        hideInSearch: true,
                        width: 180,
                        valueEnum: {

                            0: { text: '无效', status: 'Default' },
                            1: { text: '有效', status: 'Processing' },
                            2: { text: '隐藏', status: 'warning' },
                        },
                    },
                    {
                        title: '说明',
                        dataIndex: 'SYSTEMMODULE_DESC',
                        hideInSearch: true,
                        width: 200,
                    },
                    {
                        title: 'AI说明',
                        dataIndex: 'SYSTEMMODULE_ICO',
                        hideInSearch: true,
                        width: 200,
                    },
                    {
                        title: '操作',
                        valueType: 'option',
                        dataIndex: 'option',
                        hideInDescriptions: true,
                        width: 236,
                        render: (text, record) => <Space>
                            <a
                                key="editable"
                                onClick={() => {

                                    handleModelVisible(true);

                                    setCurrentRow({ ...record });
                                }}
                            >
                                编辑
                            </a>
                            {!!record.SYSTEMMODULE_STATUS &&
                                <a onClick={async () => {
                                    if (record) {

                                        const { SYSTEMMODULE_ID } = record
                                        const success = (SYSTEMMODULE_ID ? await handleAddUpdate({ ...record, SYSTEMMODULE_STATUS: 0 }) : false)
                                        if (success) {
                                            if (actionRef.current) {
                                                actionRef.current.reload();
                                            }

                                        }
                                    }
                                }}>无效</a>
                            }
                            {!record.SYSTEMMODULE_STATUS && <a onClick={async () => {
                                const success = (record.SYSTEMMODULE_ID ? await handleAddUpdate({ ...record, SYSTEMMODULE_STATUS: 1 }) : false)
                                if (success) {
                                    if (actionRef.current) {
                                        actionRef.current.reload();
                                    }
                                }
                            }}>有效</a>}
                        </Space>
                    }

                ]
                }

                search={false}
                headerTitle={false}
                options={false}
                dataSource={data.SystemModuleList}
                pagination={false}
            />
            : []
        );
    };
    return (
        <PageContainer header={{
            title: '',
            breadcrumb: {},
        }}>
            <ProTable<SystemMenuModel>
                headerTitle="菜单管理"
                rowKey="SYSTEMMENU_ID"
                actionRef={actionRef}
                scroll={{ x: '100%', y: 'calc(100vh - 430px)' }}
                pagination={{ defaultPageSize: 20 }}
                request={async (params) => {
                    console.log('currentUsercurrentUsercurrentUser', currentUser);

                    const data: any = await getSystemMenu({
                        ...params,
                        ShowModule: true,
                        SystemMenuPID: currentUser?.ID === 4653 ? '95' : '-1'
                    })
                    setMenuTree(data)

                    return { data, success: true }
                }}
                // search={false}
                columns={columns}
                toolbar={{
                    actions: [
                        <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => { handleModalVisible(true) }}>
                            菜单
                        </Button>
                    ]
                }}
                tableClassName="mune-table"
                rowClassName={(record) => record?.SYSTEMMENU_PID != -1 ? 'child-cell' : ''}
                expandable={{ expandedRowRender }}
            />
            {/* 编辑菜单详情弹出窗口 */}
            <ModalForm
                layout={'horizontal'}
                wrapperCol={{ span: 16 }}
                labelCol={{ span: 6 }}
                title={currentRow ? '更新菜单' : '新建菜单'}
                width={600}
                visible={createModalVisible}
                formRef={formRef}
                onVisibleChange={(value) => {
                    handleModalVisible(value)
                    if (value) {
                        formRef.current?.setFieldsValue(
                            currentRow ? { ...currentRow, systemmenuPid: currentRow.systemmenuPid === -1 ? null : currentRow.systemmenuPid } : { systemmenuStatus: 1 },
                        );
                    } else {
                        formRef.current?.resetFields();
                        setCurrentRow(undefined);
                    }
                }}

                onFinish={async (value) => {
                    let newValue: any = { ...value }

                    if (currentRow) { // 编辑数据
                        newValue = { ...currentRow, ...newValue }
                    }
                    newValue.systemmenuPid = value.systemmenuPid || -1
                    // newValue.SYSTEMMENU_STATUS = value.SYSTEMMENU_STATUS ? 1 : 0
                    const success = await handleAddUpdate(newValue as SystemMenuModel);

                    if (success) {
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                        // handleModalVisible(false);
                        return true
                    }
                    return false
                }}

            >
                <ProFormText
                    name="SYSTEMMENU_NAME"
                    label="菜单名称"
                    placeholder="请输入菜单名称"
                    rules={[
                        {
                            required: true,
                            message: '请输入菜单名称',
                        },
                    ]}
                />

                <Form.Item
                    name="SYSTEMMENU_PID"
                    label="上级菜单"

                >
                    <TreeSelect
                        placeholder="请选择上级菜单"
                        dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                        treeDefaultExpandAll

                        treeData={menuTree}
                        fieldNames={{
                            label: 'SYSTEMMENU_NAME',
                            value: "SYSTEMMENU_ID",
                            children: "children"
                        }}
                    >

                    </TreeSelect >

                </Form.Item>
                <ProFormText
                    name="SYSTEMMENU_ICO"
                    label="菜单图标"
                    placeholder="请输入菜单图标字段"
                    initialValue={"<ProfileOutlined />"}
                    fieldProps={
                        {
                            addonAfter: <a href='https://ant.design/components/icon-cn/' target='_blank'>去复制</a>
                        }
                    }

                />
                <ProFormDigit
                    name="SYSTEMMENU_INDEX"
                    label="索引"
                    placeholder="请输入索引"

                    min={0}
                    max={9999}
                    fieldProps={{ precision: 0 }}
                />
                <ProFormRadio.Group
                    name="SYSTEMMENU_STATUS"
                    label="状态"
                    options={[
                        {
                            label: '有效',
                            value: 1,
                        },
                        {
                            label: '无效',
                            value: 0,
                        },
                        {
                            label: '隐藏',
                            value: 2,
                        },
                    ]} />
                {/* <Form.Item
                    name="SYSTEMMENU_STATUS"
                    label="是否有效"
                >
                    <Switch
                        checkedChildren="有"
                        unCheckedChildren="无"
                        defaultChecked={currentRow ? !!currentRow.SYSTEMMENU_STATUS : true}
                    />
                </Form.Item> */}

                {/* <ProFormSwitch
                        name="SYSTEMMENU_STATUS"
                        label="是否有效"
                        checkedChildren="有"
                        unCheckedChildren="无"
                        fieldProps={{
                            defaultChecked: currentRow ? !!currentRow.SYSTEMMENU_STATUS: true
                        }}
                    /> */}
                <ProFormTextArea
                    name="SYSTEMMENU_DESC"
                    label="备注说明"
                    placeholder="请输入说明"
                />

            </ModalForm>
            {/* end */}

            {/* 编辑新增模块弹出框 */}
            <ModalForm<ModuleItem>
                layout={'horizontal'}
                wrapperCol={{ span: 16 }}
                labelCol={{ span: 6 }}
                title={currentRow ? '模块编辑' : '模块新增'}
                width={600}
                visible={createModelVisible}
                formRef={modelFormRef}
                onVisibleChange={(value) => {
                    handleModelVisible(value)
                    if (value) {
                        modelFormRef.current?.setFieldsValue(
                            currentRow ? { ...currentRow } : { SYSTEMMODULE_STATUS: 1 },
                        );
                    } else {
                        modelFormRef.current?.resetFields();
                        setCurrentRow(undefined);
                    }
                }}
                onFinish={async (value) => {
                    let newValue: any = { ...value }
                    if (currentRow) { // 编辑数据
                        newValue = { ...currentRow, ...newValue }
                    }
                    // newValue.SYSTEMMODULE_STATUS = value.SYSTEMMODULE_STATUS ? 1 : 0
                    const success = await handleAddUpdate(newValue as ModuleItem)

                    if (success) {
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                        // handleModalVisible(false)
                        return true
                    }
                    return false
                }}
            >

                <Form.Item
                    name="SYSTEMMENU_ID"
                    label="所属菜单"
                    rules={[
                        {
                            required: true,
                            message: '请选择所属菜单',
                        },
                    ]}
                >
                    <TreeSelect
                        placeholder="请选择所属菜单"
                        dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                        treeDefaultExpandAll
                        treeData={menuTree}
                        fieldNames={{
                            label: 'SYSTEMMENU_NAME',
                            value: "SYSTEMMENU_ID",
                            children: "children"
                        }}
                    >

                    </TreeSelect >

                </Form.Item>
                <ProFormText
                    name="SYSTEMMODULE_NAME"
                    label="模块名称"
                    placeholder="请输入模块名称"
                    rules={[
                        {
                            required: true,
                            message: '请输入模块名称',
                        },
                    ]}
                />
                <ProFormTextArea
                    name="SYSTEMMODULE_URL"
                    label="模块地址"
                    placeholder="请输入模块地址"
                    rules={[
                        {
                            required: true,
                            message: '请输入模块地址',
                        },
                    ]}
                />
                <ProFormDigit
                    name="SYSTEMMODULE_INDEX"
                    label="索引"
                    placeholder="请输入索引"

                    min={0}
                    max={9999}
                    fieldProps={{ precision: 0 }}
                />
                <ProFormRadio.Group
                    name="SYSTEMMODULE_STATUS"
                    label="状态"
                    options={[
                        {
                            label: '有效',
                            value: 1,
                        },
                        {
                            label: '无效',
                            value: 0,
                        },
                        {
                            label: '隐藏',
                            value: 2,
                        },
                    ]} />
                {/* <ProFormSwitch // 当前组件依赖临时过渡使用form.item
                        name="SYSTEMMODULE_STATUS"
                        label="是否有效"
                        checkedChildren="有"
                        unCheckedChildren="无"

                    /> */}

                {/* <Form.Item
                    name="SYSTEMMODULE_STATUS"
                    label="是否有效"
                >
                    <Switch
                        checkedChildren="有"
                        unCheckedChildren="无"
                        defaultChecked={currentRow ? !!currentRow.SYSTEMMODULE_STATUS : true}
                    />
                </Form.Item> */}

                <ProFormTextArea
                    name="SYSTEMMODULE_DESC"
                    label="备注说明"
                    placeholder="请输入说明"
                />
                <ProFormTextArea
                    name="SYSTEMMODULE_ICO"
                    label="AI说明"
                    placeholder="请输入AI说明"
                />

            </ModalForm>

        </PageContainer>
    )
}

export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(DataDictionary);

// export default DataDictionary;
