
import HocError from '@/Hoc/HocError'
import React, { useCallback, useEffect, useState } from 'react'
import Tables from '@/components/Tables'
import columns from './tableConfig'
import columnsDraw from './tableConfigDrawer'
import './index.less'
import AddLandingPage from '../../../components/addLandingPage'
import SelectAccount from '../../../components/addLandingPage/selectAccount'
import LookLanding from '../../../components/lookLanding'
import { Space, Input, Button, Drawer, Table, message, Card, Popconfirm } from 'antd'
import { SearchOutlined, SyncOutlined } from '@ant-design/icons'
import AdLogin from '../../../components/adLogin'
import BathLauCopy from './bathLauCopy'
import { useModel } from 'umi'

/** 落地页 */
function LandingPage(props: { checkLogin: (fn: () => void) => void }) {
    const { checkLogin } = props
    const [visible, setVisible] = useState<boolean>(false) // 创建弹窗控制
    const [lookVisible, setLookVisible] = useState<boolean>(false) // 查看弹窗控制
    const [selectAccShow, setSelectAccShow] = useState<boolean>(false) // 同步弹窗展示
    const [typesetting, setTypesetting] = useState<any>({})  // 落地页具体内容
    const [queryForm, setQueryForm] = useState<{ pageNum: number, pageSize: number, title?: string | undefined, novelName?: string, name?: string }>({ pageNum: 1, pageSize: 20 })
    const [channelAccounts, setChannelAccounts] = useState<{ MP?: any, ADQ?: any }>({})
    const [pageIds, setPageIds] = useState<number[]>([])  // 保存选择的id
    const [drawvisible, setDrawvisible] = useState<boolean>(false)  // 记录窗户
    const [drawTitle, setDrawTitle] = useState<string>('')
    const [authData, setAuthData] = useState<{ base64: string, code: string }>({ base64: '', code: '' })
    const [pageData, setPageData] = useState<any[]>([])
    const [disabled, setDisabled] = useState<boolean>(true)  // 是否需要过滤
    const [accountsInfo, setAccountsInfo] = useState<any[]>([])  // 同步过账号信息
    const [copysShow, setCopysShow] = useState<boolean>(false)  // 批量复制弹窗控制
    const [copysData, setCopysData] = useState<any>({})


    const { getSharePage, getSharePageDetail, addAndCreate, delSharePage } = useModel('useLaunch.useAdAuthorize')
    
    useEffect(() => {
        getSharePage?.run(queryForm)
    }, [])

    /**分页 */
    const pageChange = useCallback((page: string | number, pageSize?: string | number) => {
        setQueryForm({ ...queryForm, pageNum: page as number, pageSize: pageSize as number })
        getSharePage?.run({ ...queryForm, pageNum: page, pageSize: pageSize })
    }, [queryForm])

    // 获取同步的公众号信息
    const getAccount = (id: number) => {
        getSharePageDetail.run(id).then((res: any) => {
            if (res?.code === 200) {

                let { createRecords } = res?.data
                let accData: { id: number, accountName: string, MP?: any[], ADQ?: any[] }[] = []
                if (createRecords && createRecords?.length > 0) {
                    createRecords?.forEach((mp: any) => {
                        if (mp?.createStatus !== -1) {
                            let channelAccountMpInfo = mp?.channelAccountMpInfo
                            let channelAccountAdqInfo = mp?.channelAccountAdqInfo
                            if (channelAccountMpInfo && JSON.stringify(channelAccountMpInfo) !== '{}') {
                                let { channel, ...data } = channelAccountMpInfo
                                let index = accData.findIndex(item => item?.id === channel?.id)
                                if (index !== -1) {
                                    if (accData[index]?.MP) {
                                        let MP = accData[index].MP
                                        MP?.push({ ...data })
                                        accData[index] = {
                                            ...accData[index],
                                            MP
                                        }
                                    } else {
                                        accData[index] = {
                                            ...accData[index],
                                            MP: [{ ...data }]
                                        }
                                    }
                                } else {
                                    accData.push({
                                        id: channel?.id,
                                        accountName: channel?.accountName,
                                        MP: [{ ...data }]
                                    })
                                }
                            }
                            if (channelAccountAdqInfo && JSON.stringify(channelAccountAdqInfo) !== '{}') {

                            }
                        }
                    })
                }
                setAccountsInfo(accData)
            }
        })
    }

    /** 复制 */
    const copy = useCallback((e: any) => {
        e.type = 'copy'
        getAccount(e?.id)
        setTypesetting(e)
        setVisible(true)
    }, [typesetting, visible, accountsInfo])

    /** 批量复制 */
    const copys = useCallback((value: any) => {
        getAccount(value?.id)
        setCopysShow(true)
        setCopysData(value)
    }, [copysShow, copysData])

    /** 查看 */
    const look = useCallback((e) => {
        setTypesetting(e)
        setLookVisible(true)
    }, [])
    /** 批量删除 删除 */
    const del = useCallback((sharePageIds: string) => {
        delSharePage.run(sharePageIds.toString()).then((res: any) => {
            message.success('删除成功');
            setPageData([])
            setPageIds([])
            getSharePage.refresh()
        })
    }, [pageData, pageIds, getSharePage])

    /** 输入推广页名称 */
    const searchTgy = useCallback((value: any) => {
        // setLayout_name(value)
        setQueryForm({ ...queryForm, title: value || undefined })
    }, [queryForm])
    /** 查询 */
    const fun = useCallback(() => {
        setQueryForm({ ...queryForm, pageNum: 1 })
        getSharePage?.run({ ...queryForm, pageNum: 1 })
    }, [queryForm])
    /** 新建推广页 */
    const foundLandingPage = useCallback(() => {
        setAccountsInfo([])
        setTypesetting({})
        setVisible(true)
    }, [typesetting, accountsInfo])
    /** 记录里同步按钮 */
    const uploadRecord = useCallback((value: any) => {
        let channelAdqAccounts: number[] = value?.channelAccountAdqInfo ? [value?.channelAccountAdqInfo?.id] : []
        let channelMpAccounts: number[] = value?.channelAccountMpInfo ? [value?.channelAccountMpInfo?.id] : []
        addAndCreate.run({ channelMpAccounts, channelAdqAccounts, pageIds: [value?.sharePageId] }).then((res: any) => {
            if (res?.code === 200) {
                getSharePage?.refresh()
                message.success('同步成功, 正在创建落地页。。，创建成功会钉钉通知')
                getSharePageDetail.refresh()
            } else if (res?.code === 1003 && res?.data?.base64) {
                setAuthData(res?.data)
            }
        })
    }, [authData])
    /** 同步按钮触发 */
    const upload = useCallback((value: any) => {
        getSharePageDetail.run(value?.id).then((res: any) => {
            if (res?.code === 200) {
                setDisabled(true)
                setSelectAccShow(true)
                setPageIds([value?.id])
                let { createRecords } = res?.data
                let MP: number[] = []
                let ADQ: number[] = []
                if (createRecords && createRecords?.length > 0) {
                    createRecords?.forEach((mp: any) => {
                        if (mp?.createStatus !== -1) {
                            let channelAccountMpInfo = mp?.channelAccountMpInfo
                            let channelAccountAdqInfo = mp?.channelAccountAdqInfo
                            if (channelAccountMpInfo && JSON.stringify(channelAccountMpInfo) !== '{}') {
                                MP.push(channelAccountMpInfo?.id)
                            }
                            if (channelAccountAdqInfo && JSON.stringify(channelAccountAdqInfo) !== '{}') {
                                ADQ.push(channelAccountAdqInfo?.id)
                            }
                        }
                    })
                }
                console.log({ ADQ, MP })
                setChannelAccounts({ ADQ, MP })
            }
        })
    }, [selectAccShow, channelAccounts, pageIds, disabled])
    /** 选择同步按钮返回数据 */
    const uploadData = useCallback((e: any) => {
        let channelMpAccounts: number[] = []
        let channelAdqAccounts: number[] = []
        e?.forEach((item: { id: number, MP?: any[], ADQ?: any[] }) => {
            let { MP, ADQ } = item
            if (MP && MP?.length > 0 || ADQ && ADQ?.length > 0) {
                let mpIds = MP?.map((m: any) => m?.id)
                let adqIds = ADQ?.map((a: any) => a?.id)
                if (mpIds && mpIds?.length > 0) {
                    channelMpAccounts = [...channelMpAccounts, ...mpIds]
                }
                if (adqIds && adqIds?.length > 0) {
                    channelAdqAccounts = [...channelAdqAccounts, ...adqIds]
                }
            }
        })
        addAndCreate.run({ channelMpAccounts, channelAdqAccounts, pageIds }).then((res: any) => {
            if (res?.code === 200) {
                setPageData([])
                setPageIds([])
                getSharePage?.refresh()
                message.success('同步成功, 正在创建落地页...，创建成功会钉钉通知')
            } else if (res?.code === 1003 && res?.data?.base64) {
                setAuthData(res?.data)
            }
        })
    }, [pageIds, authData])

    /** 记录 */
    const history = useCallback((value: any) => {
        setDrawvisible(true)
        setDrawTitle(value?.name)
        getSharePageDetail.run(value?.id)
    }, [drawvisible])

    /** 修改 */
    const edit = useCallback((e: any) => {
        e.type = 'edit'
        setTypesetting(e)
        setVisible(true)
    }, [typesetting, visible])

    return <Card
        hoverable
        title={<Space wrap>
            <Input placeholder="搜索推广页名称" width={200} onChange={(e) => { setQueryForm({ ...queryForm, name: e.target.value }) }} allowClear />
            <Input placeholder="搜索分享标题" width={200} onChange={(e) => { searchTgy(e.target.value) }} allowClear />
            <Input placeholder="搜索小说" width={200} onChange={(e) => { setQueryForm({ ...queryForm, novelName: e.target.value }) }} allowClear />
            <Button type="primary" icon={<SearchOutlined />} onClick={fun}>查询</Button>
            <Button type="primary" onClick={() => { checkLogin(foundLandingPage) }}>新建推广页</Button>
            <Button type="primary" icon={<SyncOutlined />} loading={addAndCreate.loading} onClick={() => {
                function fn() {
                    setSelectAccShow(true);
                    setDisabled(false)
                }
                checkLogin(fn)
            }} disabled={pageData.length === 0 || (pageData.length > 0 && pageData?.some((item: any) => item.wechatInfoList)) } style={{ background: '#67c23a', borderColor: '#67c23a' }}>批量同步</Button>
            <Popconfirm
                title={<div style={{ width: 180, color: 'red' }}>
                    注意：当前删除只会删除创建失败的落地页，是否删除?
                </div>}
                onConfirm={() => {
                    function fn() {
                        del(pageData.map((item: {id: number}) => item.id).toString())
                    }
                    checkLogin(fn)
                }}
                okText="是"
                cancelText="否"
                placement="bottom"
            >
                <Button type="primary" loading={delSharePage.loading} danger disabled={pageData.length === 0}>批量删除</Button>
            </Popconfirm>

        </Space>}
    >
        <Tables
            columns={columns(copy, look, upload, history, edit, del, addAndCreate, copys, checkLogin)}
            dataSource={getSharePage?.data?.data?.records}
            total={getSharePage?.data?.data?.total}
            loading={getSharePage?.loading}
            pageChange={pageChange}
            sizeChange={pageChange}
            size="small"
            bordered
            scroll={{ x: 1700 }}
            rowSelection={{
                selectedRowKeys: pageIds.map(item => item.toString()),
                onChange: (selectedRowKeys: string[], selectedRows: any[]) => {
                    setPageData(selectedRows)
                    setPageIds(selectedRows.map(item => item.id))
                }
            }}
        />
        <Drawer
            title={drawTitle + ' 记录'}
            placement='top'
            onClose={() => { setDrawvisible(false) }}
            visible={drawvisible}
            height={500}
        >
            <Table bordered size="small" dataSource={getSharePageDetail?.data?.data?.createRecords} loading={getSharePageDetail?.loading} columns={columnsDraw(uploadRecord, addAndCreate)} rowKey={(row) => row.id} pagination={false}
                rowClassName={(record: any) => {
                    if (record?.createStatus === -1) {
                        return 'error'
                    } else {
                        return ""
                    }
                }}
                scroll={{ y: 350 }}
            />
        </Drawer>
        {/* 授权登录 */}
        <AdLogin onClose={() => { setAuthData({ base64: '', code: '' }) }} value={authData} onChange={() => { setAuthData({ base64: '', code: '' }); getSharePage?.refresh(); }} />
        {visible && <AddLandingPage visible={visible} accountsInfo={accountsInfo} hideModal={() => { setVisible(false) }} ajax={getSharePage} typesetting={typesetting}></AddLandingPage>}
        {lookVisible && <LookLanding visible={lookVisible} hideModal={() => { setLookVisible(false) }} typesetting={typesetting}></LookLanding>}
        {selectAccShow && <SelectAccount show={selectAccShow} onClose={() => { setSelectAccShow(false) }} onChange={(e: any) => { uploadData(e); setSelectAccShow(false) }} disabledAccounts={channelAccounts} disabled={disabled} />}
        {copysShow && <BathLauCopy visible={copysShow} data={copysData} onClose={() => { setCopysShow(false) }} accountsInfo={accountsInfo} ajaxHome={getSharePage} />}
    </Card>
}

export default HocError(LandingPage)