import { useAjax } from "@/Hook/useAjax";
import { addAppApi, updateAppApi } from "@/services/iaaSystem/application";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { Button, Form, message, Modal, Select, Space, Switch } from "antd";
import { DefaultOptionType } from "antd/lib/select";
import React from "react"


interface Props {
    appAllList: DefaultOptionType[]
    userList: DefaultOptionType[]
    apptypeEnum: { [x: string]: string }
    onChange?: () => void
    visible?: boolean
    onClose?: () => void
    initialValues?: any
}

/**
 * 新增修改应用权限
 * @returns 
 */
const ModalApp: React.FC<Props> = ({ appAllList, userList, apptypeEnum, onChange, visible, onClose, initialValues }) => {

    /*******************************/
    const [form] = Form.useForm();
    const authMemberAppList = Form.useWatch('authMemberAppList', form)

    const addApp = useAjax((params) => addAppApi(params))
    const updateApp = useAjax((params) => updateAppApi(params))
    /*******************************/

    const handleOk = async () => {
        form.submit()
        let data = await form.validateFields()
        if (initialValues?.id) {
            data.id = initialValues?.id
            updateApp.run(data).then(res => {
                if (res?.data) {
                    message.success('修改成功')
                    onChange && onChange()
                }
            })
        } else {
            addApp.run(data).then(res => {
                if (res?.data) {
                    message.success('新增成功')
                    onChange && onChange()
                }
            })
        }

    }

    return <Modal
        title={<strong>{initialValues?.id ? `修改 ${initialValues?.userName} 应用权限` : '新增应用权限'}</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        confirmLoading={addApp.loading || updateApp.loading}
        width={600}
    >
        <Form
            name="basicApp"
            layout="vertical"
            form={form}
            autoComplete="off"
            colon={false}
            initialValues={initialValues ? { ...initialValues } : { authMemberAppList: [{}] }}
        >
            {initialValues?.id ? <>
                <Form.Item
                    label={<strong>应用</strong>}
                    name={'iaaAppId'}
                    rules={[{ required: true, message: '请选选择应用' }]}
                >
                    <Select
                        showSearch
                        allowClear
                        placeholder="选择应用"
                        filterOption={(input, option) =>
                            (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        options={appAllList}
                    />
                </Form.Item>
                <Form.Item
                    label={<strong>是否包含自然量</strong>}
                    name={'defaultAgent'}
                    valuePropName="checked"
                    initialValue={false}
                >
                    <Switch checkedChildren="是" unCheckedChildren="否" />
                </Form.Item>
            </> : <>
                <Form.Item label={<strong>用户</strong>} name="userIdList" rules={[{ required: true, message: '请选择用户!' }]}>
                    <Select
                        mode="multiple"
                        allowClear
                        placeholder="请选择用户"
                        options={userList}
                        filterOption={(input, option) =>
                            (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    />
                </Form.Item>
                <Form.List name="authMemberAppList">
                    {(fields, { add, remove }) => {
                        return <>
                            {fields.map(({ key, name, ...restField }) => (
                                <Space key={key} style={{ display: 'flex', marginBottom: 8, width: '100%' }} align="start">
                                    <Form.Item
                                        {...restField}
                                        label={<strong>应用类型</strong>}
                                        name={[name, 'appType']}
                                        rules={[{ required: true, message: '请选选择应用' }]}
                                    >
                                        <Select
                                            style={{ width: 130 }}
                                            showSearch
                                            allowClear
                                            placeholder="选择应用类型"
                                            filterOption={(input, option) =>
                                                (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                            options={Object.keys(apptypeEnum).map(key => ({ label: apptypeEnum[key], value: key }))}
                                        />
                                    </Form.Item>
                                    <Form.Item
                                        {...restField}
                                        label={<strong>应用</strong>}
                                        name={[name, 'iaaAppIdList']}
                                        rules={[{ required: true, message: '请选选择应用' }]}
                                    >
                                        <Select
                                            style={{ width: 280 }}
                                            showSearch
                                            allowClear
                                            placeholder="选择应用"
                                            mode="multiple"
                                            filterOption={(input, option) =>
                                                (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                            options={appAllList?.filter(item => authMemberAppList?.[key]?.appType ? item.appType === authMemberAppList[key]?.appType : true)}
                                        />
                                    </Form.Item>
                                    <Form.Item
                                        {...restField}
                                        label={<strong>是否包含自然量</strong>}
                                        name={[name, 'defaultAgent']}
                                        valuePropName="checked"
                                        initialValue={false}
                                    >
                                        <Switch checkedChildren="是" unCheckedChildren="否" />
                                    </Form.Item>
                                    <MinusCircleOutlined style={{ color: 'red' }} onClick={() => remove(name)} />
                                </Space>
                            ))}
                            <Form.Item>
                                <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                    增加
                                </Button>
                            </Form.Item>
                        </>
                    }}
                </Form.List>
            </>}

        </Form>
    </Modal>
}

export default React.memo(ModalApp)