import Tables from "@/components/Tables"
import { useAjax } from "@/Hook/useAjax"
import { addSysProfileApi, delSysProfileApi, editSysProfileApi, getSysProfileApi } from "@/services/launchAdq/global"
import { PlusOutlined } from "@ant-design/icons"
import { Button, Divider, Form, Input, message, Modal, Select, Space } from "antd"
import React, { useEffect, useState } from "react"
import { UploadImage } from "./brandImage"
import { profileColumns } from "./tableConfig"

interface Props {
    onChange?: (data: any) => void,
    value?: any
}

/**
 * 头像及昵称跳转页
 * @returns 
 */
const HeadNickJump: React.FC<Props> = (props) => {

    /****************************/
    const { onChange, value } = props

    const [visible, setVisible] = useState<boolean>(false)
    const [addVisible, setAddVisible] = useState<boolean>(false)
    const [form] = Form.useForm()
    const [initialValues, setInitialValues] = useState<any>({})

    const getSysProfile = useAjax(() => getSysProfileApi())
    const addSysProfile = useAjax((params) => addSysProfileApi(params))
    const editSysProfile = useAjax((params) => editSysProfileApi(params))
    const delSysProfile = useAjax((params) => delSysProfileApi(params))
    /****************************/

    // 获取列表
    useEffect(() => {
        getSysProfile.run()
    }, [])


    // 新增修改
    const handleOk = async () => {
        form.submit()
        let data = await form.validateFields()
        if (Object.keys(initialValues).length > 0) { // 修改
            editSysProfile.run({ ...data, sysProfileId: initialValues.id }).then(res => {
                if (res) {
                    message.success('修改成功')
                    setAddVisible(false)
                    getSysProfile.refresh()
                }
            })
        } else { // 新增
            addSysProfile.run(data).then(res => {
                if (res) {
                    message.success('新增成功')
                    setAddVisible(false)
                    getSysProfile.refresh()
                }
            })
        }
        setInitialValues({})
        form.resetFields()
    }

    /** 删除 */
    const del = (id: number) => {
        delSysProfile.run({ sysProfileId: id }).then(res => {
            if (res) {
                message.success('删除成功')
                getSysProfile.refresh()
            }
        })
    }

    /** 修改 */
    const edit = (data: any) => {
        setInitialValues(data)
        setAddVisible(true)
    }

    return <div>
        <Select
            showSearch
            placeholder="请选择一个品牌跳转页，与广告创意一起展示"
            optionFilterProp="children"
            style={{ width: 400 }}
            onChange={(e) => { onChange && onChange(e) }}
            allowClear
            value={value}
            filterOption={(input, option) => {
                return (option!.value as unknown as string).toLowerCase().includes(input.toLowerCase())
            }}
            dropdownRender={menu => <>
                {menu}
                <Divider style={{ margin: '8px 0' }} />
                <div>
                    <Button type="link" onClick={() => { setAddVisible(true); setInitialValues({}) }}>新增</Button>
                    <Button type="link" onClick={() => setVisible(true)}>前往管理</Button>
                </div>
            </>}
        >
            {
                getSysProfile?.data?.map((item: any) => {
                    return <Select.Option value={item.profileName + '_' + item.headImageUrl + '_' + item.description} key={item.id}>
                        <Space>
                            <img src={item.headImageUrl} style={{ width: 20 }} />
                            <span>{item.profileName}</span>
                        </Space>
                    </Select.Option>
                })
            }
        </Select>

        {visible && <Modal title="头像及昵称跳转页" width={1000} open={visible} footer={null} onCancel={() => setVisible(false)}>
            <Space direction='vertical' style={{ width: '100%' }}>
                <Button type="primary" icon={<PlusOutlined />} onClick={() => { setAddVisible(true); setInitialValues({}) }}>上传品牌形象</Button>
                <Tables
                    columns={profileColumns(del, edit)}
                    dataSource={getSysProfile?.data}
                    size="small"
                    loading={getSysProfile?.loading}
                    scroll={{ y: 300 }}
                    bordered
                />
            </Space>
        </Modal>}
        {addVisible && <Modal title={`${Object.keys(initialValues).length > 0 ? '修改' : '上传'}头像及昵称跳转页`} open={addVisible} confirmLoading={addSysProfile.loading || editSysProfile.loading} onOk={handleOk} onCancel={() => setAddVisible(false)}>
            <Form
                name="basic"
                form={form}
                layout='vertical'
                autoComplete="off"
                initialValues={{ ...initialValues }}
            >
                <Form.Item label={<strong>头像</strong>} name="headImageUrl" rules={[{ required: true, message: '请选择头像!' }]}>
                    <UploadImage />
                </Form.Item>
                <Form.Item label={<strong>名称</strong>} name="profileName" rules={[{ required: true, message: '请输入名称!' }]}>
                    <Input placeholder="请输入名称" maxLength={12} />
                </Form.Item>
                <Form.Item label={<strong>详细描述</strong>} name="description" rules={[{ required: true, message: '请输入详细描述!' }]}>
                    <Input.TextArea placeholder="请输入详细描述" maxLength={120} />
                </Form.Item>
            </Form>
        </Modal>}
    </div>
}

export default React.memo(HeadNickJump)