import { useAjax } from "@/Hook/useAjax";
import { delWechatAppletApi, downloadTemplateApi, getWechatAppletAllApi, getWechatAppletApi, getWechatAppletDetailApi, importExcelApi } from "@/services/adqV3/global";
import { CloudDownloadOutlined, CloudUploadOutlined, PlusOutlined, SearchOutlined } from "@ant-design/icons";
import { Button, Card, Divider, Input, message, Select, Table, Typography, Upload } from "antd";
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import Modify from "./modify";
import columns from "./tableConfig";
import { downloadFile1, formatDate } from "@/utils/downloadFile";
const { Text, Paragraph } = Typography;

/**
 * 微信小程序
 * @returns 
 */
const MiniProgramWechat: React.FC = () => {

    /**********************************/
    const [queryForm, setQueryForm] = useState<{ pageNum: number, pageSize: number, appletName?: string, appletIdList?: string[] }>({ pageNum: 1, pageSize: 20 })
    const [queryFormNew, setQueryFormNew] = useState<{ pageNum: number, pageSize: number, appletName?: string, appletIdList?: string[] }>({ pageNum: 1, pageSize: 20 })
    const [visible, setVisible] = useState<boolean>(false)
    const [initialValues, setInitialValues] = useState<any>({})
    const [downLoading, setDownLoading] = useState<boolean>(false)
    const [btnUploadLoding, setBtnUploadLoding] = useState<boolean>(false)//按钮loding

    const getWechatApplet = useAjax((params) => getWechatAppletApi(params))
    const delWechatApplet = useAjax((params) => delWechatAppletApi(params))
    const importExcel = useAjax((params) => importExcelApi(params))
    /**********************************/

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

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

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

    return <Card
        className="cardResetCss"
        title={<div className="flexStart" style={{ gap: 8 }}>
            <Input style={{ width: 200 }} placeholder="请输入小程序名称" value={queryForm?.appletName} allowClear onChange={(e) => setQueryForm({ ...queryForm, appletName: e.target.value, pageNum: 1 })} />
            <Input.TextArea
                style={{ width: 300 }}
                placeholder="请输入小程序原始ID（多个逗号隔开）"
                allowClear
                rows={1}
                onChange={(e) => {
                    let value = e.target.value
                    let arr: string[] = []
                    if (value) {
                        value = value.replace(/[,，\s]/g, ',')
                        arr = value.split(',').filter((a: string) => a)
                    }
                    setQueryForm({ ...queryForm, appletIdList: arr, pageNum: 1 })
                }}
            />
            <Button type="primary" icon={<SearchOutlined />} onClick={() => setQueryFormNew({ ...queryForm })}>搜索</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => { setVisible(true) }}>新增小程序</Button>
            <Button
                icon={<CloudDownloadOutlined />}
                loading={downLoading}
                onClick={() => {
                    setDownLoading(true)
                    downloadTemplateApi().then(res => {
                        setDownLoading(false)
                        downloadFile1(res, 'octet-stream', formatDate(new Date()) + ".xlsx")
                    }).catch(() => setDownLoading(false))
                }}
            >下载模板</Button>
            <Upload
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                action=""
                listType="text"
                onChange={() => { }}
                multiple={true}
                showUploadList={false}
                customRequest={(options) => {
                    setBtnUploadLoding(true)
                    let formData = new FormData();
                    formData.append("file", options.file);
                    importExcel.run(formData).then(res => {
                        setBtnUploadLoding(false)
                        if (res) {
                            message.success('导入成功')
                            getWechatApplet.refresh()
                        }
                    }).catch(() => {
                        setBtnUploadLoding(false)
                    })
                }}
            >
                <Button type="primary" ghost loading={btnUploadLoding} icon={<CloudUploadOutlined />} onClick={() => { }}>上传Excel</Button>
            </Upload>
        </div>}
    >

        <Table
            columns={columns(del, edit)}
            dataSource={getWechatApplet.data?.records}
            size="small"
            loading={getWechatApplet?.loading}
            scroll={{ y: 600 }}
            bordered
            rowKey={'id'}
            pagination={{
                defaultPageSize: 20,
                current: getWechatApplet.data?.current || 1,
                pageSize: getWechatApplet.data?.size || 10,
                total: getWechatApplet.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}
            onClose={() => {
                setVisible(false)
                setInitialValues({})
            }}
            onChange={() => {
                setVisible(false)
                getWechatApplet.refresh()
                setInitialValues({})
            }}
        />}
    </Card>
}


/**
 * 选择小程序
 * @param param0 
 * @returns 
 */
export const SelectMiniProgramWechat: React.FC<{ value?: number, onChange?: (value?: number) => void }> = ({ value, onChange }) => {

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

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

    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/miniProgramWechat'
                    }}>前往管理</Button>
                    <Button type="link" style={{ paddingLeft: 0, paddingRight: 0 }} onClick={() => {
                        setVisible(true)
                    }}>新增</Button>
                    {/* <Link href="/#/launchSystemV3/tencenTasset/miniProgramWechat" target="_blank">
                    前往管理
                </Link> */}
                </div>
            </>}
            value={value}
            onChange={(e) => onChange?.(e)}
        >
            {getWechatAppletAll?.data?.map((item: { id: number, appletId: string, appletName: string, appletLink: string }) => {
                return <Select.Option value={item.id} key={item.id} name={item.appletName + `(${item.appletId}_${item.appletLink})`}><Text strong>{item.appletName}</Text><Text type="secondary">{`(${item.appletId}_${item.appletLink})`}</Text></Select.Option>
            })}
        </Select>
        {/* 新增修改 */}
        {visible && <Modify
            visible={visible}
            initialValues={{}}
            onClose={() => {
                setVisible(false)
            }}
            onChange={() => {
                setVisible(false)
                getWechatAppletAll.refresh()
            }}
        />}
    </>
}


/**
 * 展示小程序详情
 * @param param0 
 * @returns 
 */
export const ShowMiniProgramWechatDetail: React.FC<{ id: number }> = ({ id }) => {

    /*******************************/
    const getWechatAppletDetail = useAjax((params) => getWechatAppletDetailApi(params))
    /*******************************/

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

    return <Paragraph style={{ fontSize: 12, wordBreak: 'break-all', marginBottom: 0 }} ellipsis={{ rows: 2 }}>
        {getWechatAppletDetail.data ? <>
            <Text strong>微信小程序：{getWechatAppletDetail.data?.appletName}</Text><Text type="secondary">{`(${getWechatAppletDetail.data?.appletId}_${getWechatAppletDetail.data?.appletLink})`}</Text>
        </> : id}
    </Paragraph>
}

export default MiniProgramWechat