import Tables from "@/components/Tables"
import { useAjax } from "@/Hook/useAjax"
import SelectCloud from "@/pages/launchSystemNew/components/selectCloud"
import { addSysBrandApi, delSysBrandApi, editSysBrandApi, getSysBrandApi } 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 { useModel } from "umi"
import { brandColumns } from "./tableConfig"

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

/**
 * 品牌形象
 * @returns 
 */
const BrandImage: 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 getSysBrand = useAjax(() => getSysBrandApi())
    const addSysBrand = useAjax((params) => addSysBrandApi(params))
    const editSysBrand = useAjax((params) => editSysBrandApi(params))
    const delSysBrand = useAjax((params) => delSysBrandApi(params))
    /****************************/

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


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

    /** 删除 */
    const del = (id: number) => {
        delSysBrand.run({ sysBrandId: id }).then(res => {
            if (res) {
                message.success('删除成功')
                getSysBrand.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>
            </>}
        >
            {
                getSysBrand?.data?.map((item: any) => {
                    return <Select.Option value={item.name + '_' + item.brandImgUrl} key={item.id}>
                        <Space>
                            <img src={item.brandImgUrl} style={{ width: 20 }} />
                            <span>{item.name}</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={brandColumns(del, edit)}
                    dataSource={getSysBrand?.data}
                    size="small"
                    loading={getSysBrand?.loading}
                    scroll={{ y: 300 }}
                    bordered
                />
            </Space>
        </Modal>}

        {addVisible && <Modal title="上传品牌形象" open={addVisible} confirmLoading={addSysBrand.loading} onOk={handleOk} onCancel={() => setAddVisible(false)}>
            <Form
                name="basic"
                form={form}
                layout='vertical'
                autoComplete="off"
                initialValues={{ ...initialValues }}
            >
                <Form.Item label={<strong>头像</strong>} name="brandImgUrl" rules={[{ required: true, message: '请选择头像!' }]}>
                    <UploadImage />
                </Form.Item>
                <Form.Item label={<strong>名称</strong>} name="name" rules={[{ required: true, message: '请输入名称!' }]}>
                    <Input placeholder="请输入名称" maxLength={12}/>
                </Form.Item>
            </Form>
        </Modal>}
    </div>
}


interface ImageProps {
    onChange?: (value: string) => void,
    value?: string
}
/**
 * 处理选择图片Form
 * @returns 
 */
export const UploadImage: React.FC<ImageProps> = (props) => {

    /*********************/
    const { onChange, value } = props
    const [selectImgVisible, setSelectImgVisible] = useState<boolean>(false)
    const [sliderImgContent, setSliderImgContent] = useState<{ url: string, width?: number, height?: number }[]>([])  // 保存回填数据
    const { init } = useModel('useLaunchAdq.useBdMediaPup')
    /*********************/

    useEffect(() => {
        if (value) {
            setSliderImgContent([{ url: value }])
        } else {
            setSliderImgContent([])
        }
    }, [value])

    const setImg = (content: any[]) => {
        onChange && onChange(content[0]?.url)
        setSelectImgVisible(false)
    }

    const selectImg = () => {
        init({ mediaType: 'IMG', cloudSize: [[{ relation: '=', width: 512, height: 512 }]], maxSize: 50 * 1024 })
        setTimeout(() => { setSelectImgVisible(true) }, 50)
    }

    return <>
        {value ? <img src={value} onClick={selectImg} width={100} height={100} /> : <Button onClick={selectImg}>选择图片</Button>}
        <div style={{ fontSize: 12, color: 'rgba(0,0,0,.5)' }}>
            <div>图片尺寸：512×512 像素</div>
            <div>图片格式：大小要求在 50KB 以内，仅支持 jpg 和 png 格式</div>
        </div>

        {/* 选择素材 */}
        {selectImgVisible && <SelectCloud visible={selectImgVisible} sliderImgContent={sliderImgContent} onClose={() => setSelectImgVisible(false)} onChange={setImg} />}
    </>
}

export default React.memo(BrandImage)