import { useAjax } from "@/Hook/useAjax"
import { addGroupApi, delGroupApi, editGroupApi, getGroupListApi } from "@/services/launchAdq/subgroup"
import { DeleteOutlined, FormOutlined, PlusOutlined } from "@ant-design/icons"
import { Button, Input, message, Popconfirm, Space, Spin } from "antd"
import React, { useEffect, useRef, useState } from "react"
import { useModel } from "umi"
import './index.less'

/**
 * 分组管理Left 菜单
 */
interface Props {
    onChange?: (groupId?: number) => void
    value?: number
}
const GroupLeft: React.FC<Props> = (props) => {

    /*************************/
    const { onChange, value } = props
    const [isNewGrouping, setIsNewGrouping] = useState<boolean>(false);  // 是否新增分组
    const inputRef = useRef<any>(null);
    const [groupData, setGroupData] = useState<{ groupName: string, remark?: string, groupId?: number }>({ groupName: '' }) // 分组添加
    const [selectAccData, setSelectAccData] = useState<{ id: number, mpName: string }[]>([])  // 选中
    const [groupId, setGroupId] = useState<number>(value || 0)
    const { getGroupList } = useModel('useLaunchAdq.useAdAuthorize')

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

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