import { useAjax } from "@/Hook/useAjax";
import { addProfilesApi, delProfilesApi, getProfilesApi } from "@/services/adqV3/global";
import { PlusOutlined, SearchOutlined } from "@ant-design/icons";
import { Button, Card, Form, Input, Modal, Select, Space, Table, message, Image, Divider } from "antd";
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import profilesColumns from "./tableConfig";
import SelectCloudNew from "../../material/cloudNew/selectCloudNew";

/**
 * 头像昵称跳转页
 * @returns 
 */
const Profiles: React.FC = () => {


    /***************************************/
    const [addVisible, setAddVisible] = useState<boolean>(false)
    const [initialValues, setInitialValues] = useState<any>({})
    const [form] = Form.useForm()
    const [queryForm, setQueryForm] = useState<{ profileName?: string }>({})

    const getProfiles = useAjax((params) => getProfilesApi(params))
    const addProfiles = useAjax((params) => addProfilesApi(params))
    const delProfiles = useAjax((params) => delProfilesApi(params))
    /***************************************/

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

    // 新增修改
    const handleOk = async () => {
        form.submit()
        let { imageData, ...data } = await form.validateFields()
        addProfiles.run({ ...imageData, ...data }).then(res => {
            if (res) {
                message.success('新增成功')
                setAddVisible(false)
                getProfiles.refresh()
            }
        })
        setInitialValues({})
    }

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

    return <Card
        className="cardResetCss"
        title={<div className="flexStart" style={{ gap: 8 }}>
            <Input style={{ width: 200 }} placeholder="请输入头像昵称跳转页" value={queryForm?.profileName} allowClear onChange={(e) => setQueryForm({ ...queryForm, profileName: e.target.value })} />
            <Button type="primary" icon={<SearchOutlined />} onClick={() => getProfiles.refresh()}>搜索</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => { setAddVisible(true); setInitialValues({}), form.resetFields() }}>上传头像昵称跳转页</Button>
        </div>}
    >
        <Table
            columns={profilesColumns(del)}
            dataSource={getProfiles?.data}
            size="small"
            loading={getProfiles?.loading}
            scroll={{ y: 600 }}
            bordered
            rowKey={'id'}
        />

        {addVisible && <Modal className="modalResetCss" title="上传头像昵称跳转页" open={addVisible} confirmLoading={addProfiles.loading} onOk={handleOk} onCancel={() => setAddVisible(false)}>
            <Form
                name="basicProfiles"
                form={form}
                layout='vertical'
                autoComplete="off"
                initialValues={{ ...initialValues }}
            >
                <Form.Item label={<strong>头像</strong>} name="imageData" rules={[{ required: true, message: '请选择头像!' }]}>
                    <UploadImageOrMd5 />
                </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">
                    <Input.TextArea placeholder="请输入详细描述" maxLength={120} />
                </Form.Item>
            </Form>
        </Modal>}
    </Card>
}

export default React.memo(Profiles)


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

    /*********************/
    const { onChange, value } = props
    const [selectImgVisible, setSelectImgVisible] = useState<boolean>(false)
    const [selectCloudData, setSelectCloudData] = useState<{
        defaultParams: {
            sizeQueries?: {
                width: number,
                height: number,
                relation: string
            }[],
            materialType: 'image' | 'video'
            fileSize: number
        }
        num: number
    }>()
    /*********************/

    const setImg = (content: any[]) => {
        console.log(content)
        onChange && onChange({ imageUrl: content[0]?.oss_url, imageMd5: content[0]?.md5 })
        setSelectImgVisible(false)
    }

    const selectImg = () => {
        setSelectCloudData({
            defaultParams: {
                sizeQueries: [{ relation: '=', width: 512, height: 512 }],
                fileSize: 400 * 1024,
                materialType: 'image'
            },
            num: 1
        })
        setSelectImgVisible(true)
    }

    return <>
        {value?.imageUrl ? <img src={value?.imageUrl} 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>图片格式：大小要求在 400KB 以内，仅支持 jpg 和 png 格式</div>
        </div>

        {/* 选择素材 */}
        {(selectImgVisible && selectCloudData) && <SelectCloudNew
            {...selectCloudData}
            visible={selectImgVisible}
            onClose={() => {
                setSelectImgVisible(false)
                setSelectCloudData(undefined)
            }}
            onChange={setImg}
        />}
    </>
}



export const SelectProfiles: React.FC<{ value?: number, onChange?: (value?: number) => void }> = ({ value, onChange }) => {

    /*******************************/
    const getProfiles = useAjax((params) => getProfilesApi(params))
    /*******************************/

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

    return <Select
        showSearch
        allowClear
        placeholder="选择头像昵称跳转页"
        filterOption={(input, option) =>
            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
        }
        style={{ width: 480 }}
        dropdownRender={menu => <>
            {menu}
            <Divider style={{ margin: '8px 0' }} />
            <div>
                <Button type="link" onClick={() => {
                    window.location.href = '/#/launchSystemV3/tencenTasset/profiles'
                }}>前往管理</Button>
                {/* <Link href="/#/launchSystemV3/tencenTasset/profiles" target="_blank">
                    前往管理
                </Link> */}
            </div>
        </>}
        value={value}
        onChange={(e) => onChange?.(e)}
    >
        {getProfiles?.data?.map((item: { id: number; headImageUrl: string; profileName: string; }) => <Select.Option value={item.id} key={item.id}>
            <Space>
                <Image width={20} style={{ borderRadius: 4 }} src={item.headImageUrl} />
                <span>{item.profileName}</span>
            </Space>
        </Select.Option>)}
    </Select>
}