import { useAjax } from "@/Hook/useAjax"
import { DeleteOutlined, FormOutlined, PlusOutlined } from "@ant-design/icons"
import { App, Button, Input, Popconfirm, Space, Spin } from "antd"
import React, { useEffect, useRef, useState } from "react"
import style from './index.less'
import { addGroupApi, delGroupApi, editGroupApi, getGroupListApi } from "../../API/corpUserManage"


interface Props {
    onChange?: (groupId?: number) => void
    value?: number
}

/**
 * 分组管理Left 菜单
 */
const GroupLeft: React.FC<Props> = ({ onChange, value }) => {

    /*************************/
    const { message } = App.useApp()
    const [isNewGrouping, setIsNewGrouping] = useState<boolean>(false);  // 是否新增分组
    const inputRef = useRef<any>(null);
    const [groupData, setGroupData] = useState<{ groupName: string, remark?: string, groupId?: number }>({ groupName: '' }) // 分组添加
    const [groupId, setGroupId] = useState<number>(value || 0)

    const addGroup = useAjax((params) => addGroupApi(params))
    const editGroup = useAjax((params) => editGroupApi(params))
    const delGroup = useAjax((params) => delGroupApi(params))
    const getGroupList = useAjax(() => getGroupListApi())
    /*************************/

    useEffect(() => {
        getGroupList.run()
    }, [])

    useEffect(() => {
        if (value) {
            setGroupId(value || 0)
        }
    }, [value])

    /** 点击新增处理聚焦 */
    useEffect(() => {
        if (isNewGrouping && inputRef?.current) {
            inputRef.current!.focus({
                cursor: 'end',
            });
        }
    }, [inputRef, isNewGrouping])

    /** 新增修改分组 */
    const addEditHandle = () => {
        if (groupData?.groupName) {
            if (groupData?.groupId) {
                editGroup.run(groupData).then((res: any) => {
                    message.success('修改成功')
                    setGroupData({ groupName: '' })
                    setIsNewGrouping(false)
                    getGroupList.refresh()
                })
            } else {
                addGroup.run(groupData).then((res: any) => {
                    message.success('添加成功')
                    setGroupData({ groupName: '' })
                    setIsNewGrouping(false)
                    getGroupList.refresh()
                })
            }
        } else {
            message.error('请填写分组名称')
        }
    }

    /** 删除分组 */
    const delGroupHandle = (id: number) => {
        delGroup.run({ groupId: id }).then(res => {
            message.success('删除成功')
            getGroupList.refresh()
            if (groupId === id) {
                setGroupId(0)
                onChange?.(undefined)
            }
        })
    }

    return <div className={style.groupLeft}>
        <div className={style.groupLeft_header}>
            <div>全部分组</div>
            <Button type="link" icon={<PlusOutlined />} className="stop" onClick={(e) => {
                e.stopPropagation()
                setGroupData({ groupName: '' })
                setIsNewGrouping(true)
            }}>新增分组</Button>
        </div>
        <div className={style.groupLeft_content}>
            {isNewGrouping && <div className={style.groupLeft_content_item}>
                <div className={`${style.edit}`}>
                    <Space direction="vertical">
                        <Space>
                            <div style={{ width: 30 }}>组名</div>
                            <Input placeholder="输入分组名称（最多10个字）" maxLength={10} ref={inputRef} onChange={(e) => { setGroupData({ ...groupData, groupName: e.target.value }) }} value={groupData?.groupName} />
                        </Space>
                        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                            <Space>
                                <Button size="small" onClick={() => { setIsNewGrouping(false); setGroupData({ groupName: '' }) }}>取消</Button>
                                <Button type="primary" size="small" onClick={addEditHandle} loading={getGroupList?.loading}>确定</Button>
                            </Space>
                        </div>
                    </Space>
                </div>
            </div>}
            <Spin spinning={getGroupList.loading}>
                <div className={style.groupLeft_content_item}>
                    <div className={`${style.con} ${groupId === 0 ? style.select : ''}`} onClick={() => { setGroupId(0); onChange?.(undefined); }}>
                        <div className={style.left}>
                            <div className={style.title}>全部</div>
                        </div>
                    </div>
                </div>
                {getGroupList && Array.isArray(getGroupList?.data?.data) && getGroupList?.data?.data?.map((item: { groupName: string, groupId: number }, index: number) => <div className={style.groupLeft_content_item} key={item.groupId || index}>
                    {groupData?.groupId && groupData?.groupId === item?.groupId ? <div className={style.edit}>
                        <Space direction="vertical">
                            <Space>
                                <div style={{ width: 40 }}>组名</div>
                                <Input placeholder="输入分组名称（最多10个字）" maxLength={10} ref={inputRef} onChange={(e) => { setGroupData({ ...groupData, groupName: e.target.value }) }} value={groupData?.groupName} />
                            </Space>
                            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                                <Space>
                                    <Button size="small" onClick={() => { setIsNewGrouping(false); setGroupData({ groupName: '' }) }}>取消</Button>
                                    <Button type="primary" size="small" onClick={addEditHandle} loading={editGroup?.loading}>修改</Button>
                                </Space>
                            </div>
                        </Space>
                    </div> : <div className={`${style.con} ${groupId === item.groupId ? style.select : ''}`} onClick={() => { setGroupId(item.groupId); onChange?.(item.groupId); }} key={item.groupId || index}>
                        <div className={style.left}>
                            <div className={style.title}>{item.groupName}</div>
                        </div>
                        <div className={style.right}>
                            <Space>
                                <FormOutlined onClick={(e) => { e.stopPropagation(); setGroupData({ ...item }); setIsNewGrouping(false) }} />
                                <Popconfirm
                                    title="确定删除?"
                                    onConfirm={() => { delGroupHandle(item.groupId) }}
                                    okText="确定"
                                    cancelText="取消"
                                >
                                    <DeleteOutlined style={{ color: 'red' }} />
                                </Popconfirm>
                            </Space>
                        </div>
                    </div>}
                </div>)}
            </Spin>
        </div>
    </div>
}


export default React.memo(GroupLeft)