import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import { Button, Card, Divider, Input, message, Select, Table, Typography } from "antd"
import { PlusOutlined, SearchOutlined } from "@ant-design/icons"
import { useAjax } from "@/Hook/useAjax"
import { ApplicationTypeProps, delApplicationApi, getApplicationAllApi, getApplicationDetailApi, getApplicationListApi, GetApplicationListProps } from "@/services/adqV3/global"
import { getErpUserAll } from "@/services/launchAdq/adq"
import Modify from "./modify"
import columns from "./tableConfig"
const { Text, Paragraph } = Typography;

/**
 * 推广应用
 * @returns 
 */
const Application: React.FC = () => {

    /**********************************/
    const [queryForm, setQueryForm] = useState<GetApplicationListProps>({ pageNum: 1, pageSize: 20 })
    const [queryFormNew, setQueryFormNew] = useState<GetApplicationListProps>({ pageNum: 1, pageSize: 20 })
    const [visible, setVisible] = useState<boolean>(false)
    const [initialValues, setInitialValues] = useState<any>()

    const getApplicationList = useAjax((params) => getApplicationListApi(params))
    const allOfMember = useAjax(() => getErpUserAll())
    const delApplication = useAjax((params) => delApplicationApi(params))
    /**********************************/


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

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

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

    const update = (data: any) => {
        setInitialValues(data)
        setVisible(true)
    }

    return <Card
        className="cardResetCss"
        title={<div className="flexStart" style={{ gap: 8 }}>
            <Select
                showSearch
                placeholder="请选择创建人"
                onChange={(e) => setQueryForm({ ...queryForm, createBy: e, pageNum: 1 })}
                filterOption={(input, option) =>
                    (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                allowClear
                style={{ width: 140 }}
                options={allOfMember?.data?.map((item: { userId: any; nickname: string }) => ({
                    value: item.userId,
                    label: item.nickname,
                }))}
            />
            <Select
                showSearch
                placeholder="推广应用类型"
                onChange={(e) => setQueryForm({ ...queryForm, type: e, pageNum: 1 })}
                filterOption={(input, option) =>
                    (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                allowClear
                style={{ width: 140 }}
                options={[{ label: 'Ios', value: 'IOS' }, { label: 'Android', value: 'ANDROID' }]}
            />
            <Input style={{ width: 150 }} placeholder="推广应用名称" value={queryForm?.name} allowClear onChange={(e) => setQueryForm({ ...queryForm, name: e.target.value, pageNum: 1 })} />
            <Input style={{ width: 150 }} placeholder="推广应用ID" value={queryForm?.applicationId} allowClear onChange={(e) => setQueryForm({ ...queryForm, applicationId: e.target.value, pageNum: 1 })} />

            <Button type="primary" icon={<SearchOutlined />} onClick={() => setQueryFormNew({ ...queryForm })}>搜索</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => { setVisible(true) }}>新增推广应用</Button>
        </div>}
    >
        <Table
            columns={columns(del, update)}
            dataSource={getApplicationList.data?.records}
            size="small"
            loading={getApplicationList?.loading}
            scroll={{ y: 600, x: 1100 }}
            bordered
            rowKey={'id'}
            pagination={{
                defaultPageSize: 20,
                current: getApplicationList.data?.current || 1,
                pageSize: getApplicationList.data?.size || 10,
                total: getApplicationList.data?.total || 0
            }}
            onChange={(pagination) => {
                const { current, pageSize } = pagination
                setQueryForm({ ...queryForm, pageNum: current || 1, pageSize: pageSize || 10 })
                setQueryFormNew({ ...queryForm, pageNum: current || 1, pageSize: pageSize || 10 })
            }}
        />

        {/* 新增 修改 */}
        {visible && <Modify
            visible={visible}
            initialValues={initialValues}
            onChange={() => {
                setVisible(false)
                setInitialValues(undefined)
                getApplicationList.refresh()
            }}
            onClose={() => {
                setVisible(false)
                setInitialValues(undefined)
            }}
        />}
    </Card>
}

export default Application



/**
 * 选择应用
 * @param param0 
 * @returns 
 */
export const SelectApplication: React.FC<{ value?: number, onChange?: (value?: number) => void, type?: ApplicationTypeProps }> = ({ value, onChange, type }) => {

    /*******************************/
    const [visible, setVisible] = useState<boolean>(false)
    const getApplicationAll = useAjax((params) => getApplicationAllApi(params))
    /*******************************/

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

    return <>
        <Select
            showSearch
            allowClear
            placeholder="请选择应用"
            filterOption={(input: any, option: any) => {
                return option!.name?.toString().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/application'
                    }}>前往管理</Button>
                    <Button type="link" style={{ paddingLeft: 0, paddingRight: 0 }} onClick={() => {
                        setVisible(true)
                    }}>新增</Button>
                    {/* <Link href="/#/launchSystemV3/tencenTasset/application" target="_blank">
                    前往管理
                </Link> */}
                </div>
            </>}
            value={value}
            onChange={(e) => onChange?.(e)}
        >
            {getApplicationAll?.data?.map((item: { id: number, applicationId: string, name: string }) => {
                return <Select.Option value={item.id} key={item.id} name={item.name + `(${item.applicationId})`}><Text strong>{item.name}</Text><Text type="secondary">{`(${item.applicationId})`}</Text></Select.Option>
            })}
        </Select>

        {/* 新增 */}
        {visible && <Modify
            visible={visible}
            onClose={() => {
                setVisible(false)
            }}
            onChange={() => {
                setVisible(false)
                getApplicationAll.refresh()
            }}
        />}
    </>
}


/**
 * 展示应用详情
 * @param param0 
 * @returns 
 */
export const ShowApplication: React.FC<{ id: number }> = ({ id }) => {

    /*******************************/
    const getApplicationDetail = useAjax((params) => getApplicationDetailApi(params))
    /*******************************/

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

    return <Paragraph style={{ fontSize: 12, wordBreak: 'break-all', marginBottom: 0 }} ellipsis={{ rows: 2 }}>
        {getApplicationDetail.data ? <>
            <Text strong>应用：{getApplicationDetail.data?.name}</Text><Text type="secondary">{`(${getApplicationDetail.data?.applicationId})`}</Text>
        </> : id}
    </Paragraph>
}