import { Button, Card, Form, Input, message, Modal, Radio, Space, Transfer } from "antd"
import React, { useEffect } from "react"
import '../../tencentAdPutIn/index.less'
import { useAjax } from "@/Hook/useAjax"
import { getUserAllApi } from "@/services/operating/account"
import { addFolderApi, getFolderDetailsApi, updateFolderApi } from "@/services/adqV3/cloudNew"

interface Props {
    parentIdStr: string
    visible?: boolean
    onChange?: (res: any) => void
    onClose?: () => void
    initialValues?: any
}

/**
 * 新增文件夹
 * @param param0 
 * @returns 
 */
const ManageFolder: React.FC<Props> = ({ parentIdStr = '0', visible, onChange, onClose, initialValues }) => {

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

    const getUserAll = useAjax(() => getUserAllApi())
    const addFolder = useAjax((params) => addFolderApi(params))
    const updateFolder = useAjax((params) => updateFolderApi(params))
    const getFolderDetails = useAjax((params) => getFolderDetailsApi(params))
    /************************************/

    useEffect(() => {
        if (initialValues?.id) {
            getFolderDetails.run(initialValues.id).then(res => {
                if (res) {
                    form.setFieldsValue({ ...res, permissionUserId: res.permissionUserId || undefined })
                }
            })
        }
    }, [initialValues?.id])

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

    const handleOk = (values: any) => {
        console.log(values)
        const parentIdArr = parentIdStr.split('-')
        const parentIdArrLength = parentIdArr.length
        const parentId = Number(parentIdArr[parentIdArrLength - 1])
        if (initialValues?.id) {
            updateFolder.run({ ...values, parentId, id: initialValues.id }).then(res => {
                if (res) {
                    message.success('修改成功')
                    onChange?.(res)
                }
            })
        } else {
            addFolder.run({ ...values, parentId }).then(res => {
                if (res) {
                    message.success('新增成功')
                    onChange?.(res)
                }
            })
        }
    }


    return <Modal
        title={<strong>{initialValues?.id ? '修改文件夹' : '新增文件夹'}</strong>}
        open={visible}
        onCancel={onClose}
        footer={null}
        className="modalResetCss"
        bodyStyle={{ padding: '0 0 40px', position: 'relative', borderRadius: '0 0 8px 8px' }}
        maskClosable={false}
        width={600}
    >
        <Form
            form={form}
            name="newFolder"
            labelAlign='left'
            labelCol={{ span: 4 }}
            layout="horizontal"
            colon={false}
            style={{ backgroundColor: '#f1f4fc', maxHeight: 650, overflow: 'hidden', overflowY: 'auto', padding: '10px', borderRadius: '0 0 8px 8px' }}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            onFinish={handleOk}
            initialValues={{
                isPublic: true
            }}
        >
            <Card className="cardResetCss">
                <Form.Item name="folderName" label={<strong>名称</strong>} required={false} rules={[{ required: true, message: '请输入文件夹名称!' }]}>
                    <Input placeholder="文件夹名称" />
                </Form.Item>
                {parentIdStr === '0' && <>
                    <Form.Item name="isPublic" label={<strong>权限</strong>}>
                        <Radio.Group buttonStyle="solid">
                            <Radio.Button value={true}>所有人可见</Radio.Button>
                            <Radio.Button value={false}>仅自己可见/指定人员可见</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    {isPublic === false && <Form.Item name="permissionUserId" label={<strong>人员</strong>} valuePropName="targetKeys">
                        <Transfer
                            dataSource={getUserAll?.data?.filter((item: { userId: string | null }) => item.userId?.toString() !== localStorage.getItem('userId')) || []}
                            rowKey={record => record.userId}
                            render={item => item.nickname}
                            titles={['未选', '已选']}
                            oneWay
                            showSearch
                            listStyle={({ direction }) => (direction === 'left' ? { height: 350, width: 240 } : { height: 350 })}
                        />
                    </Form.Item>}
                </>}
                <Form.Item name="description" label={<strong>备注</strong>}>
                    <Input.TextArea placeholder="备注" />
                </Form.Item>
            </Card>
            <Form.Item className="submit_pull">
                <Space>
                    <Button onClick={onClose}>取消</Button>
                    <Button type="primary" htmlType="submit" loading={addFolder.loading || updateFolder.loading} className="modalResetCss">
                        确定
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(ManageFolder)