import { App, Button, Dropdown, Form, Input, message, Modal, Radio, Select } from "antd"
import React, { useEffect, useState } from "react"
import UploadImg from "../../components/materialMould/uploadImg"
import UploadVideo from "../../components/materialMould/uploadVideo"
import { CloseCircleOutlined, MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { useAjax } from "@/Hook/useAjax";
import { createLandingPageApi, editLandingPageApi } from "../../API/miniProgramPages";

interface Props {
    groupList: { label: string, value: number }[]
    corpList: { corpName: string, corpId: string, corpUserList: { corpUserName: string, corpUserId: string }[] }[]
    pageSpecs: TASK_MINI_PAGE_CREATE.PageSpecsProps
    visible?: boolean
    onChange?: () => void
    onClose?: () => void
    initialValues?: any
}

const Submit: React.FC<Props> = ({ corpList, visible, pageSpecs, onChange, onClose, groupList, initialValues }) => {

    /***********************************/
    const { message } = App.useApp();
    const [form] = Form.useForm();
    const corpId = Form.useWatch('corpId', form)
    const [corpUserList, setCorpUserList] = useState<{ corpUserName: string, corpUserId: string }[]>([])

    const createLandingPage = useAjax((params) => createLandingPageApi(params))
    const editLandingPage = useAjax((params) => editLandingPageApi(params))
    /***********************************/

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

    const handleOk = () => {
        form.validateFields().then(valid => {
            const { bgColor, globalElementsSpecList, pageElementsSpecList } = pageSpecs
            let pageSpecsList = []
            let qrCodeFloatList: { siteId: number, urlList: string[] }[] = []
            if (globalElementsSpecList?.length > 0) {
                pageSpecsList = [...pageElementsSpecList.map(item => {
                    delete (item as any)?.comptActive
                    return item
                }), ...globalElementsSpecList.map(item => {
                    delete item.comptActive
                    return item
                })]
                const floatButton = globalElementsSpecList?.find(item => item.elementType === 'FLOAT_BUTTON')
                if (floatButton) {
                    qrCodeFloatList = [{
                        siteId: floatButton.id,
                        urlList: floatButton.qrCodeFloatList
                    }]
                }
            }
            const qrCodeList = pageElementsSpecList.filter(item => item.elementType === 'QR_CODE')?.map((item: TASK_MINI_PAGE_CREATE.QrCode) => ({ siteId: item.id, urlList: item.imageList }))
            const { pageName, ...v } = valid
            const params = {
                content: JSON.stringify({
                    pageName,
                    bgColor,
                    elementsSpecList: pageSpecsList
                }),
                qrCodeFloatList,
                qrCodeList,
                ...v
            }
            if (initialValues?.id) {
                editLandingPage.run({ ...params, id: initialValues.id }).then(res => {
                    if (res?.data) {
                        message.success('修改成功')
                        onChange?.()
                    }
                })
            } else {
                createLandingPage.run(params).then(res => {
                    if (res?.data) {
                        message.success('新增成功')
                        onChange?.()
                    }
                })
            }
        }).catch(err => { })
    }

    return <Modal
        title={<strong>落地页基础配置</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        width={750}
        confirmLoading={createLandingPage?.loading || editLandingPage?.loading}
        maskClosable={false}
    >
        <Form
            form={form}
            name="newPageLink"
            labelAlign='left'
            labelCol={{ span: 5 }}
            colon={false}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            onFinish={handleOk}
            initialValues={initialValues}
        >
            <Form.Item label={<strong>落地页名称</strong>} name="name" rules={[{ required: true, message: '请输入落地页名称!' }]}>
                <Input placeholder="请输入落地页名称" />
            </Form.Item>

            <Form.Item label={<strong>落地页标题</strong>} name="pageName" rules={[{ required: true, message: '请输入落地页标题!' }]}>
                <Input placeholder="请输入落地页标题" />
            </Form.Item>

            <Form.Item label={<strong>落地页备注</strong>} name="remark">
                <Input placeholder="请输入落地页备注" />
            </Form.Item>

            <Form.Item label={<strong>小程序预览AppId</strong>} name="previewAppId">
                <Input placeholder="请输入小程序预览AppId" />
            </Form.Item>
            
            <Form.Item label={<strong>企微主体</strong>} name="corpId" rules={[{ required: true, message: '请选择主体!' }]}>
                <Select
                    placeholder='请选择主体'
                    allowClear
                    options={corpList.map(item => ({ label: item.corpName, value: item.corpId }))}
                    showSearch
                    filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                />
            </Form.Item>
            {corpId && <Form.Item label={<strong>企微客服号</strong>} name="corpUserIdList" rules={[{ required: true, message: '请选择企微客服号!' }]}>
                <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"
                />
            </Form.Item>}
            <Form.Item label={<strong>书名</strong>} name="bookName">
                <Input placeholder="请输入书名名称" />
            </Form.Item>
            <Form.Item label={<strong>项目组</strong>} name="projectGroupIdList" rules={[{ required: true, message: '请选择项目组!' }]}>
                <Select
                    placeholder='请选择项目组'
                    allowClear
                    options={groupList}
                    showSearch
                    mode="multiple"
                    filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                />
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(Submit)