import { App, Button, Card, DatePicker, Input, Pagination, Popconfirm, Select, Table } from "antd"
import SearchBox from "../../components/searchBox"
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { useEffect, useRef, useState } from "react";
import style from '../bookLink/index.less'
import { getProjectGroupsAllListApi } from "../../API/groupManage";
import { useAjax } from "@/Hook/useAjax";
import dayjs from 'dayjs';
import { delLandingPageApi, getLandingPageListApi, GetLandingPageListProps } from "../../API/miniProgramPages";
import { useSize } from "ahooks";
import { TableConfig } from "./tableConfig";
import { randomString } from "@/utils/utils";
import DrawerMini from "./drawerMini";
import { getCorpUserListApi, getGenerateUrllinkApi } from "../../API/global";
import ShowQrCode from "./showQrCode";
import dayJs from 'dayjs';


/**
 * 小程序落地页
 * @returns 
 */
const MiniProgramPages: React.FC = () => {

    /******************************************/
    const ref = useRef<HTMLDivElement>(null)
    const size = useSize(ref)
    const { message } = App.useApp();
    const [visible, setVisible] = useState<boolean>(false)
    const [queryParams, setQueryParams] = useState<GetLandingPageListProps>({ pageNum: 1, pageSize: 20 })
    const [queryParamsNew, setQueryParamsNew] = useState<GetLandingPageListProps>({ pageNum: 1, pageSize: 20 })
    const [groupList, setGroupList] = useState<{ label: string, value: number }[]>([])
    const [selectedRows, setselectedRows] = useState<any[]>([])
    const [initialValues, setInitialValues] = useState<any>()
    const [qrCode, setQrCode] = useState<{ url: string, visible: boolean }>()
    const [corpList, setCorpList] = useState<{ corpName: string, corpId: string, corpUserList: { corpUserName: string, corpUserId: string }[] }[]>([])
    const [corpUserList, setCorpUserList] = useState<{ corpUserName: string, corpUserId: string }[]>([])

    const getProjectGroupsAllList = useAjax(() => getProjectGroupsAllListApi())
    const getLandingPageList = useAjax((params) => getLandingPageListApi(params))
    const delLandingPage = useAjax((params) => delLandingPageApi(params))
    const getGenerateUrllink = useAjax((params) => getGenerateUrllinkApi(params))
    const getCorpUserList = useAjax((params) => getCorpUserListApi(params))
    /******************************************/

    useEffect(() => {
        if (queryParams?.corpId) {
            setCorpUserList(corpList.find(item => item.corpId === queryParams.corpId)?.corpUserList || [])
        } else {
            setCorpUserList([])
        }
    }, [corpList, queryParams?.corpId])

    useEffect(() => {
        getProjectGroupsAllList.run().then(res => {
            setGroupList(res?.data?.map(item => ({ label: item.name, value: item.id })) || [])
        })

        getCorpUserList.run().then(res => {
            setCorpList(res?.data || [])
        })
    }, [])

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

    const handleEdit = (d: Record<string, any>, isCopy?: boolean) => {
        const { content, name, id, projectGroupIdList, bookName, remark, corpId, corpUserList, previewAppId, type, h5VisitSwitch } = d

        const pageElementsSpecList: TASK_MINI_PAGE_CREATE.PageElementsSpecListProps = []
        const globalElementsSpecList: TASK_MINI_PAGE_CREATE.GlobalElementsSpecListProps = []

        let newPageName = ''
        let pageSpecs: Partial<TASK_MINI_PAGE_CREATE.PageSpecsProps> = {}
        if (type === 'LANDING_PAGE') {
            const { bgColor, pageName, elementsSpecList } = JSON.parse(content)
            elementsSpecList.forEach(item => {
                if (item.elementType === 'FLOAT_BUTTON') {
                    globalElementsSpecList.push({ ...item, comptActive: false })
                } else {
                    pageElementsSpecList.push({ ...item, comptActive: false })
                }
            })
            pageSpecs = {
                bgColor,
                pageElementsSpecList,
                globalElementsSpecList,
                pageType: type || 'LANDING_PAGE'
            }
            newPageName = pageName
        } else {
            const data = JSON.parse(content)
            newPageName = data?.[0]?.user?.nick || ''
            const { url, tipText } = data?.[0] || {}
            const newData = data.map(item => {
                return {
                    url: item.v_url,
                    duration: item.du
                }
            })
            pageElementsSpecList.push({
                elementType: 'TOP_SHORT_VIDEO',
                data: newData,
                url,
                tipText
            })
            pageSpecs = {
                bgColor: '#000000',
                pageElementsSpecList,
                pageType: type || 'VIDEO'
            }
        }



        const newInitialValues = {
            name,
            pageName: newPageName,
            bookName,
            corpId,
            id,
            previewAppId,
            pageSpecs,
            corpUserIdList: corpUserList.map(item => item.corpUserId),
            projectGroupIdList: projectGroupIdList.map(item => item.projectGroupId),
            remark,
            isCopy: isCopy || false,
            h5VisitSwitch: h5VisitSwitch || false
        }
        console.log(newInitialValues)
        if (isCopy) {
            delete newInitialValues.id
            newInitialValues.name = newInitialValues.name + '_副本' + randomString(true, 3, 5)
        }
        setInitialValues(newInitialValues)
        setVisible(true)
    }

    const handleDel = (ids: number[]) => {
        const hide = message.loading('删除中...', 0)
        delLandingPage.run({ idList: ids.join(',') }).then(res => {
            hide()
            if (res?.data) {
                message.success('删除成功');
                getLandingPageList.refresh();
            }
        }).catch(() => hide())
    }

    const handleCode = (appId: string, vid: string, createTime: string) => {
        let params = {}
        if (dayJs(createTime) > dayJs('2026-04-08').startOf('day')) {
            params = { path: '/pages/player/index', query: `id=${vid}` }
        } else {
            params = { path: '/pages/play/index', query: `vid=${vid}&eq=${-Math.random()}` }
        }
        getGenerateUrllink.run({ ...params, appId }).then(res => {
            if (res?.data) {
                setQrCode({ visible: true, url: res.data })
            }
        })
    }

    return <Card
        styles={{ body: { padding: 0, display: 'flex', flexDirection: 'column', height: 'calc(100vh - 88px)' } }}
    >
        <div>
            <SearchBox
                bodyPadding={`10px 16px 4px`}
                buttons={<>
                    <Button type="primary" onClick={() => {
                        setQueryParamsNew({ ...queryParams, pageNum: 1 })
                    }} icon={<SearchOutlined />}>搜索</Button>
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => setVisible(true)}>新增落地页</Button>
                    <Popconfirm
                        title="确定删除？"
                        onConfirm={() => { handleDel?.(selectedRows.map(i => i.id)) }}
                        disabled={selectedRows?.length === 0}
                    >
                        <Button danger disabled={selectedRows?.length === 0}>删除</Button>
                    </Popconfirm>
                </>}
            >
                <>
                    <Select
                        placeholder='请选择主体'
                        allowClear
                        options={corpList.map(item => ({ label: item.corpName, value: item.corpId }))}
                        showSearch
                        style={{ minWidth: 130 }}
                        value={queryParams?.corpId}
                        filterOption={(input, option) =>
                            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                        }
                        onChange={(v) => setQueryParams({ ...queryParams, corpId: v })}
                    />
                    {queryParams?.corpId && <Select
                        placeholder='请选择企微客服号'
                        allowClear
                        options={corpUserList.map(item => ({ label: item.corpUserName, value: item.corpUserId }))}
                        showSearch
                        filterOption={(input, option) =>
                            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                        }
                        mode="multiple"
                        maxTagCount={1}
                        style={{ minWidth: 130 }}
                        value={queryParams?.corpUserIdList}
                        onChange={(v) => setQueryParams({ ...queryParams, corpUserIdList: v })}
                    />}
                    <Input
                        placeholder="落地页名称"
                        allowClear
                        value={queryParams?.name}
                        onChange={(e) => {
                            setQueryParams({ ...queryParams, name: e.target.value })
                        }}
                    />
                    <Input
                        placeholder="书名"
                        allowClear
                        value={queryParams?.bookName}
                        onChange={(e) => {
                            setQueryParams({ ...queryParams, bookName: e.target.value })
                        }}
                    />
                    <Input
                        placeholder="备注"
                        allowClear
                        value={queryParams?.remark}
                        onChange={(e) => {
                            setQueryParams({ ...queryParams, remark: e.target.value })
                        }}
                    />
                    <Select
                        placeholder='请选择项目组'
                        allowClear
                        style={{ minWidth: 150 }}
                        maxTagCount={1}
                        options={[{ label: '空项目组', value: 0 }, ...groupList || []]}
                        showSearch
                        filterOption={(input, option) =>
                            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                        }
                        mode="multiple"
                        value={queryParams?.projectGroupIdList}
                        onChange={(value) => setQueryParams({ ...queryParams, projectGroupIdList: value })}
                    />
                    <DatePicker.RangePicker
                        placeholder={["创建时间开始", "创建时间结束"]}
                        value={queryParams?.startTime ? [dayjs(queryParams?.startTime), dayjs(queryParams?.endTime)] : undefined}
                        onChange={(_, options) => {
                            const newQueryForm = { ...queryParams }
                            if (options?.[0]) {
                                newQueryForm.startTime = options?.[0]
                                newQueryForm.endTime = options?.[1]
                            } else {
                                delete newQueryForm?.startTime
                                delete newQueryForm?.endTime
                            }
                            setQueryParams(newQueryForm)
                        }}
                    />
                </>
            </SearchBox>
        </div>
        <div className={style.bookLinkTable} ref={ref}>
            <Table
                dataSource={getLandingPageList?.data?.data?.records}
                columns={TableConfig(handleEdit, handleDel, handleCode)}
                bordered
                pagination={false}
                rowKey={'id'}
                size='small'
                className='resetTable'
                loading={getLandingPageList?.loading}
                scroll={{ y: size?.height && ref.current ? size?.height - ref.current.querySelector('.ant-table-thead').clientHeight : 300 }}
                rowSelection={{
                    selectedRowKeys: selectedRows?.map((item: any) => item?.id),
                    onSelect: (record: { id: string }, selected: boolean) => {
                        let newData = JSON.parse(JSON.stringify(selectedRows))
                        if (selected) {
                            newData.push({ ...record })
                        } else {
                            newData = newData.filter((item: { id: string }) => item.id !== record.id)
                        }
                        setselectedRows(newData)
                    },
                    onSelectAll: (selected: boolean, _: { id: string }[], changeRows: { id: string }[]) => {
                        let newData = JSON.parse(JSON.stringify(selectedRows || '[]'))
                        if (selected) {
                            changeRows.forEach((item: { id: string }) => {
                                let index = newData.findIndex((ite: { id: string }) => ite.id === item.id)
                                if (index === -1) {
                                    newData.push(item)
                                }
                            })
                        } else {
                            let newSelectAccData = newData.filter((item: { id: string }) => {
                                let index = changeRows.findIndex((ite: { id: string }) => ite.id === item.id)
                                if (index !== -1) {
                                    return false
                                } else {
                                    return true
                                }
                            })
                            newData = newSelectAccData
                        }
                        setselectedRows(newData)
                    }
                }}
            />
        </div>
        <div className={style.bookLinkPagination}>
            <Pagination
                size="small"
                total={getLandingPageList?.data?.data?.total || 0}
                showSizeChanger
                showQuickJumper
                pageSize={getLandingPageList?.data?.data?.size || 20}
                current={getLandingPageList?.data?.data?.current || 1}
                onChange={(page: number, pageSize: number) => {
                    // ref.current?.scrollTo({ top: 0 })
                    setTimeout(() => {
                        setQueryParams({ ...queryParams, pageNum: page, pageSize })
                        setQueryParamsNew({ ...queryParamsNew, pageNum: page, pageSize })
                    }, 50)
                }}
                showTotal={(total: number) => <span style={{ fontSize: 12 }}>共 {total} 条</span>}
            />
        </div>

        {/* {visible && <NewMini
            initialValues={initialValues}
            groupList={groupList}
            corpList={corpList}
            visible={visible}
            onChange={() => {
                setInitialValues(undefined)
                setVisible(false)
                getLandingPageList?.refresh()
            }}
            onClose={() => {
                setInitialValues(undefined)
                setVisible(false)
            }}
        />} */}
        {visible && <DrawerMini
            initialValues={initialValues}
            groupList={groupList}
            corpList={corpList}
            visible={visible}
            onChange={() => {
                setInitialValues(undefined)
                setVisible(false)
                getLandingPageList?.refresh()
            }}
            onClose={() => {
                setInitialValues(undefined)
                setVisible(false)
            }}
        />}

        {qrCode?.visible && <ShowQrCode
            {...qrCode}
            onClose={() => setQrCode(undefined)}
        />}
    </Card>
}

export default MiniProgramPages