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 './index.less'

/**
 * 分组管理Left
 */
interface Props {

}
const GroupLeft: React.FC<Props> = (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 [queryForm, setQueryForm] = useState<{ groupId?: number, pageNum: number, pageSize: number }>({ pageNum: 1, pageSize: 20 })
    const { groupId = 0 } = queryForm

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

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

    /** 获取分组 */
    useEffect(() => {
        getGroupList.run()
    }, [])

    /** 新增修改分组 */
    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 = (groupId: number) => {
        delGroup.run({ groupId }).then(res => {
            message.success('删除成功')
            getGroupList.refresh()
            if (queryForm.groupId === groupId) {
                setQueryForm({ ...queryForm, groupId: 0 })
            }
        })
    }

    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>
                        {/* <Space className="stop">
                            <div style={{ width: 70 }} className="stop">分组备注：</div>
                            <Input placeholder="请输入分组备注（最多10个字）" className="stop" maxLength={10} onChange={(e) => { setGroupData({ ...groupData, remark: e.target.value }) }} value={groupData?.remark} />
                        </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={() => { setQueryForm({ ...queryForm, groupId: 0 }); setSelectAccData([]) }}>
                        <div className="left">
                            <div className="title">默认分组</div>
                        </div>
                    </div>
                </div>
                {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>
                            {/* <Space className="stop">
                                <div style={{ width: 70 }} className="stop">分组备注：</div>
                                <Input placeholder="请输入分组备注（最多10个字）" className="stop" maxLength={10} onChange={(e) => { setGroupData({ ...groupData, remark: e.target.value }) }} value={groupData?.remark} />
                            </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={() => { setQueryForm({ ...queryForm, groupId: item.groupId, pageNum: 1 }); setSelectAccData([]) }} key={item.groupId || index}>
                        <div className="left">
                            <div className="title">{item.groupName}</div>
                            {/* {item?.remark && <div className="subTitle">{item?.remark}</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)