import { useAjax } from "@/Hook/useAjax"
import { Col, Form, Input, Modal, Radio, Row, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import { getExportMediaByUrlApi } from "../../API/weMaterial/weMaterial"
import UploadImg from "./uploadImg"
import InputByteLength from "../inputByteLength"
import TextAreaByteLength from "../textAreaByteLength"
import { txtLength } from "@/utils/utils"
import { byteDate } from "./config"




interface Props {
    type?: 'PYQ' | 'QF',
    value?: any
    visible?: boolean
    onChange?: (value?: any) => void
    onClose?: () => void
}

const LinkModal: React.FC<Props> = ({ value, visible, onChange, onClose, type }) => {

    /*********************************/
    const [config, setConfig] = useState<any>({})
    const [sphLink, setSphLink] = useState("")
    const [linkType, setLinkType] = useState(1)
    const [form] = Form.useForm();
    const [open, setOpen] = useState(false)
    const getExportMediaByUrl = useAjax((params) => getExportMediaByUrlApi(params))
    /*********************************/

    useEffect(() => {
        setConfig(byteDate[type || 'DEF'])
    }, [type])

    useEffect(() => {
        if (value && Object.keys(value).length > 0) {
            if (value.linkUrl?.includes("https://channels.weixin.qq.com/mobile/commonFinderJsApi.html?api=openFinderView&extInfo")) {
                try {
                    let newLink = decodeURIComponent(value.linkUrl)
                    let extInfoJson = newLink.replace('https://channels.weixin.qq.com/mobile/commonFinderJsApi.html?api=openFinderView&extInfo=', '')
                    let extInfo = JSON.parse(extInfoJson)
                    console.log(extInfo)
                    setSphLink(extInfo.feedID)
                } catch (error) {
                    console.log(error)
                }
                setLinkType(2)
            }
            form.setFieldsValue({ ...value })
        }
    }, [value])

    const handleOk = () => {
        form.validateFields().then(valid => {
            console.log(valid);
            valid['linkUrl'] = valid['linkUrl']?.replace(/\s/ig, '')
            onChange?.(valid)
        }).catch(err => {})
    }

    // 获取链接详情
    const onSearch = (value: string) => {
        if (value) {
            getExportMediaByUrl.run(value).then(res => {
                console.log(res);
                const { title, thumbMediaUrl, digest } = res?.data
                form.setFieldsValue({
                    linkTitle: title,
                    linkPicurl: thumbMediaUrl,
                    linkDesc: digest
                })
            })
        }
    }

    return <Modal
        title='添加链接'
        open={visible}
        onCancel={() => onClose?.()}
        onOk={handleOk}
    >
        <Radio.Group onChange={(e) => { setLinkType(e.target.value) }} value={linkType} style={{ marginBottom: 10 }}>
            <Radio value={1}>通用链接</Radio>
            <Radio value={2}>视频号链接</Radio>
        </Radio.Group>
        <Form
            form={form}
            initialValues={{}}
        >
            {/* {linkType === 1 ? <Form.Item name="linkUrl" label="链接" rules={[{ message: '请输入以http://或https://开头的网址!' }]}>
                <Input.Search placeholder="请输入以http://或https://开头的网址" enterButton='获取' onSearch={onSearch} loading={getExportMediaByUrl.loading} />
            </Form.Item> : <Form.Item name="linkUrl" label="链接" rules={[{  message: '请输入以http://或https://开头的网址!', }]}>
                <Input.Search placeholder="请输入以http://或https://开头的网址" enterButton='生成视频号地址' onSearch={() => { setOpen(true) }} loading={getExportMediaByUrl.loading} />
            </Form.Item>} */}
            <Form.Item name="linkTitle" label={<strong>标题</strong>} rules={[
                { required: true, message: '请输入标题!' },
                {
                    required: true, message: `长度不超过${config.linkTitle}字节，一个中文（3字节），英文（1字节）`, validator(rule, value, callback) {
                        if (txtLength(value?.toString()) > config.linkTitle) {
                            return Promise.reject()
                        }
                        return Promise.resolve()
                    },
                },
            ]}>
                <InputByteLength placeholder="请输入标题" maxLength={config.linkTitle} />
            </Form.Item>
            <Row gutter={15}>
                <Col flex={'auto'}>
                    <Form.Item name="linkDesc" label={<strong>描述</strong>} rules={[
                        { required: true, message: '请输入描述!' },
                        {
                            required: true, message: '长度不超过512字节，一个中文（3字节），英文（1字节）', validator(rule, value, callback) {
                                if (txtLength(value?.toString()) > 512) {
                                    return Promise.reject()
                                }
                                return Promise.resolve()
                            },
                        },
                    ]}>
                        <TextAreaByteLength rows={4} placeholder="请输入描述" maxLength={512} />
                    </Form.Item>
                </Col>
                <Col flex={'88px'}>
                    <Form.Item name="linkPicurl" rules={[{ required: true, message: '请上传图片!' }]}>
                        <UploadImg type="link" size={{ width: 1440, height: 1080, evalW: '>', evalH: '>', msg: '需要图片大小不超过1440*1080' }} isCropper isEdit={false} />
                    </Form.Item>
                </Col>
            </Row>
        </Form>
        <Modal
            open={open}
            title={"生成视频号地址"}
            onCancel={() => { setOpen(false) }}
            onOk={() => {
                let regex = new RegExp("^" + "https://weixin.qq.com/sph/");
                if (sphLink && regex.test(sphLink)) {
                    let newLink = `https://channels.weixin.qq.com/mobile/commonFinderJsApi.html?api=openFinderView&extInfo=` + encodeURIComponent(`{"action":"openFinderFeed","feedID":"${sphLink}","notGetReleatedList":1,"shareScene":40,"commentScene":40,"reportExtraInfo":"{\\"sys_scene\\":1}"}`)
                    form.setFieldValue("linkUrl", newLink)
                    setOpen(false)
                } else {
                    console.log(sphLink, sphLink.indexOf('https://weixin.qq.com/sph/'))
                    message.error("输入的视频号链接不正确")
                }
            }}
        >
            <Input placeholder="请输入视频号地址例：https://weixin.qq.com/sph/AqlumTQRC" value={sphLink} onChange={(e) => { setSphLink(e.target.value.replace(/\s/ig, '')) }} allowClear />
        </Modal>
    </Modal >
}


export default React.memo(LinkModal)