import {CurdColumn, CurdPage} from "../../../components/curd";
import {useCallback, useMemo, useState} from "react";
import {LDAP, LDAPApis} from "../../../api/ldap.ts";
import {ICurdConfig} from "../../../components/curd/types.ts";
import {Button, Form, Input, Modal, Switch, Table} from "antd";
import './index.less'
import {Message} from "auto-antd";
import {Link} from "react-router-dom";

const columns: CurdColumn[] = [
    {
        key: 'id',
        title: 'ID',
        type: 'string',
        disabled: true,
        required: false,
        width: 50
    },
    {
        key: 'key',
        title: '服务编码',
        type: 'string',
        disabled: true,
        placeholder: '服务唯一编码，自动生成',
        required: false,
        width: 120
    },
    {
        key: 'url',
        title: '服务Url',
        type: 'string',
        placeholder: 'eg. ldap://192.168.1.1:389',
        width: 150
    },
    {
        key: 'userName',
        title: '管理员账号',
        type: 'string',
        width: 150
    },
    {
        key: 'password',
        title: '管理员密码',
        type: 'password',
        hidden: true,
    },
    {
        key: 'baseDN',
        type: 'string',
        title: 'baseDN',
        placeholder: 'eg. ou=users,dc=xxxx,dc=cn'
    },
    {
        key: 'filter',
        title: '过滤配置',
        type: 'string',
        placeholder: '默认：(objectClass=*)',
        required: false,
        width: 180
    },
    {
        title: '组织ObjectClass',
        key: 'organizeClass',
        type: 'string',
    },
    {
        key: 'remark',
        title: '备注',
        type: 'textarea',
        required: false,
    }
]

const serverConfig: ICurdConfig<LDAP.Server> = {
    editDialogWidth: 500,
    labelSpan: 6,
}

type VerifyData = Partial<LDAP.Server> & {
    search?: string
}

export const Server = () => {

    const [verifyData, setVerifyData] = useState<VerifyData>()
    const [loading, setLoading] = useState(false)

    const [searchUsers, setSearchUsers] = useState<LDAP.User[]>([])

    const getList = useCallback((query: any) => {
        return LDAPApis.getServerList(query).then(res => {
            console.log('server', res)
            return res.data.data
        })

    }, [])

    const getDetail = (data: Partial<LDAP.Server>) => {
        if (!data.id) {
            return Promise.resolve({} as LDAP.Server)
        }
        return LDAPApis.getServer(data.id).then(res => {
            if (res) {
                return res;
            }
            throw new Error('该服务不存在！')
        })
    }

    const onSaveServer = (data: Partial<LDAP.Server>) => {
        return LDAPApis.saveServer(data)
            .then(res => {
                return res.data.data as LDAP.Server;
            })
    }

    const operationRender = (record: LDAP.Server, _: number) => {

        return (<>
            <Button onClick={() => setVerifyData(record)} size="small">验证</Button>
            <Button size="small">
                <Link to={`server/${record.id}/user`}>用户</Link>
            </Button>
        </>)
    }

    const config = useMemo(() => {

        return {
            ...serverConfig,
            operationRender
        } as ICurdConfig<LDAP.Server>

    }, [])

    const onChange = (data: Partial<VerifyData>) => {
        setVerifyData(verify => ({...verify, ...data}))
    }

    const onVerify = () => {
        if (!verifyData?.id) {
            return
        }
        setLoading(true)
        LDAPApis.verifyServer({id: verifyData.id, active: verifyData.active, username: verifyData.search})
            .then(res => {
                setLoading(false)
                setSearchUsers(res.data || [])
                Message.success('操作成功！')
            })
            .finally(() => {
                setLoading(false)
            })
    }


    return (<>
        <CurdPage columns={columns} getList={getList} getDetail={getDetail}
                  onSave={onSaveServer}
                  onSuccess={data => setVerifyData(data)}
                  config={config}/>
        <Modal open={!!verifyData} title="LDAP服务验证" onCancel={() => setVerifyData(undefined)}
               confirmLoading={loading} width={600}
               onOk={onVerify}>
            <Form className="verify-form">
                <Form.Item name="id" label="URL">
                    <span>{verifyData?.url}</span>
                </Form.Item>
                <Form.Item name="id" label="UserName">
                    <span>{verifyData?.userName}</span>
                </Form.Item>
                <Form.Item name="baseDN" label="baseDN">
                    <span>{verifyData?.baseDN}</span>
                </Form.Item>
                <Form.Item name="active" label="设置为活动服务">
                    <Switch checked={verifyData?.active} onChange={ev => onChange({active: ev})}></Switch>
                </Form.Item>
                <Form.Item name="username" label="搜索用户名">
                    <Input value={verifyData?.search} onChange={ev => onChange({search: ev.target.value})}/>
                </Form.Item>
                <Form.Item label="搜索结果">
                    <div className="search-results">
                        <Table dataSource={searchUsers} pagination={false} rowKey="uid">
                            <Table.Column dataIndex="account" title="uid"/>
                            <Table.Column dataIndex="userName" title="姓名"/>
                            <Table.Column dataIndex="dn" title="DN"/>
                        </Table>
                    </div>
                </Form.Item>
            </Form>
        </Modal>
    </>)
}
