import { PlusOutlined } from '@ant-design/icons'
import { Button, Card, Col, Input, message, Modal, Radio, Row, Tag } from 'antd'
import { RadioChangeEvent } from 'antd/lib/radio'
import React, { useCallback, useEffect, useState } from 'react'
import WxModalBox from './wxModalBox'
import style from './graphic.less'
import { useModel } from 'umi'
type Props = {
    visible: boolean,
    onCancel: () => void,
    onOK: (props: any, type?: number) => void,
    defaultData: any,
}
const WxGraphicModal = (props: Props) => {
    const { visible, onCancel, onOK } = props
    const [isShow, setIsShow] = useState<boolean>(false)//图片弹窗
    const [eq, setEq] = useState<number>(1)//切换
    const [action, setAction] = useState<any>(null)//选中
    const [img, setImg] = useState<any>(null)//存放图片数据
    const [ref, setRef] = useState<any>(null)
    const [range, setRange] = useState<Range>()
    const [isImport, setIsImport] = useState<boolean>(false)//点击导入
    const [link, setLink] = useState<string>('')//link
    const [text, setText] = useState<string>('')//摘要
    const getWeItData = useModel('useOperating.useMaterialContent', model => model.getWeItData)
    const actionWX = useModel('useOperating.useWxGroupList', model => model.state.actionWX)
    //确定
    const callback = useCallback(() => {
        if (eq === 2) {
            onOK(action, 5)
        } else {
            if (link && text && img && ref.innerHTML.replace(/<[/]?span[^>]*>/ig, '#')) {
                onOK({
                    newsUrl: link,
                    newsDescription: text,
                    newsPicUrl: img,
                    newsTitle: ref.innerHTML.replace(/<[/]?span[^>]*>/ig, '#'),
                    indexId: props.defaultData?.indexId
                }, 5)

            } else {
                message.error('有遗漏未填项！')
            }
        }

    }, [action, eq, link, text, img, ref])
    //切换
    const handelRadio = useCallback((e: RadioChangeEvent) => {
        let v = e.target.value
        setEq(v)
        setAction(null)
    }, [])
    //选中素材时的操作
    const handelAction = useCallback((data: any) => {
        let { title, contentSourceUrl, digest, thumbUrl } = data.content.articles[0]
        setAction({ mediaId: data.mediaId, articles: { title, contentSourceUrl, digest, thumbUrl } })//存放选中数据
        if (eq !== 2) {
            setLink(contentSourceUrl)//存放选中的连接
            setText(digest)//存放选中的摘要
            setImg(thumbUrl)//存放图片
            ref.innerText = title//标题
        }
    }, [ref, eq])
    //开关图片弹窗
    const closeModal = useCallback(() => {
        setIsShow(!isShow)
    }, [isShow])
    //选中图片
    const handleOk = (data: any) => {
        setImg(data.url)
        closeModal()
    }
    //插入粉丝昵称
    const pushName = useCallback(() => {
        let span = document.createElement('span')
        span.className = style.nickName
        span.setAttribute('contentEditable', 'false')
        span.innerText = `粉丝昵称`
        range?.insertNode(span)
    }, [range])
    //光标丢失记录位置
    const onBlur = useCallback(() => {
        let selection = window.getSelection()
        let range = selection?.getRangeAt(0)
        setRange(range)
    }, [])
    //初始光标选中
    useEffect(() => {
        ref?.focus()
    }, [ref])
    //获取微信图文列表
    useEffect(() => {
        getWeItData.run({ appId: actionWX.appid, count: 1000, offset: 0 })
    }, [actionWX])
    //连接输入
    const handelLink = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let v = e.target.value
        setLink(v)
    }, [])
    //摘要输入
    const handelText = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
        let v = e.target.value
        setText(v)
    }, [])
    //复制只取纯文本
    function textPaste(event: any) {
        event.preventDefault();
        let text;
        let clp = (event.originalEvent || event).clipboardData;
        // 兼容chorme或hotfire
        text = clp.getData('text')
        console.log(text)
        if (text !== "") {
            document.execCommand('insertHtml', false, text);
        }
    }
    //编辑回填内容
    useEffect(() => {
        if (props.defaultData && ref) {
            let { newsList } = props.defaultData
            let { newsUrl, newsDescription, newsPicUrl, newsTitle } = newsList[0]
            newsTitle = newsTitle.replace('#粉丝昵称#', `<span class=${style.nickName} contenteditable="false">粉丝昵称</span>`)
            setImg(newsPicUrl)
            setText(newsDescription)
            setLink(newsUrl)
            ref.innerHTML = newsTitle
        }
    }, [ref])
    //list渲染
    const List = useCallback((props: { width: string, action: any }) => {
        let { action } = props
        return <div className={style.list}>
            {
                getWeItData?.data?.items?.map((item: any, index: any) => {
                    let isAction = action?.mediaId === item.mediaId
                    return <Card
                        hoverable
                        style={{ width: props.width, borderRadius: 5, marginBottom: 10 }}
                        bodyStyle={{ padding: '5px' }}
                        className={isAction ? style.action : ''}
                        bordered={isAction ? false : true}
                        key={index}
                        onClick={() => handelAction(item)}
                    >
                        <div className={style.box}>
                            <div className={style.left}>
                                <p>{item.content.articles[0].title}</p>
                                <span>最近编辑：{item.content?.updateTime?.replace(/T|\.000\+0800/ig, ' ')}</span>
                            </div>
                            <img src={item.content.articles[0].thumbUrl} />
                        </div>
                    </Card>
                })
            }
        </div>
    }, [getWeItData])
    return <Modal
        title='编辑图文内容'
        width={1100}
        visible={visible}
        onCancel={onCancel}
        onOk={callback}
    >
        <div>
            <div className={style.header}>
                <label>添加方式：</label>
                <Radio.Group onChange={handelRadio} value={eq}>
                    <Radio value={1}>自定义设置</Radio>
                    {/* <Radio value={2}>素材库导入</Radio> */}
                </Radio.Group>
            </div>
            {
                eq === 1
                    ?
                    // 自定义设置
                    <div className={style.centent}>
                        <div >
                            {
                                !isImport
                                    ?
                                    <div className={style.text}>
                                        <span>
                                            您可以点击下方”导入图文内容”按钮，直接从微信素材导入，也可以在右边表单手动添加内容。
                                         </span>
                                        <Button type='primary' size='small' onClick={() => { setIsImport(true) }} disabled={getWeItData?.loading} loading={getWeItData?.loading}>导入图文内容</Button>
                                    </div>
                                    :
                                    <div className={style.text}>
                                        <span>选择图文导入：</span>
                                        <List width='100%' action={action} />
                                    </div>
                            }
                        </div>
                        <div>
                            <Row style={{ width: '80%' }}>
                                <Col span={24}>
                                    <label >图文标题 ：<span>(必填)</span></label>
                                    <div
                                        contentEditable="true"
                                        className={style.editor}
                                        ref={(ref) => setRef(ref)}
                                        onBlur={onBlur}
                                        onPaste={textPaste}
                                    />
                                    {/* <label >点击插入：<Tag color='orange' onClick={pushName}>粉丝昵称</Tag></label> */}
                                </Col>
                                <Col span={24}>
                                    <label >描述内容 ：</label>
                                    <Input.TextArea rows={5} placeholder='填写图文描述' onChange={handelText} value={text} />
                                </Col>
                                <Col span={24}>
                                    <label >链接设置 ：<span>(必填)</span></label>
                                    <Input placeholder='请输入跳转链接，且必须以http://或https://开头' onChange={handelLink} value={link} />
                                </Col>
                            </Row>
                            <div>
                                <label >图文封面 ：</label>
                                <span className={img ? style.imgupload : ''} onClick={closeModal}>
                                    {
                                        img ? <img src={img} /> : <PlusOutlined style={{ fontSize: 30 }} />
                                    }
                                    <div><PlusOutlined style={{ fontSize: 30, color: '#fff' }} /> </div>
                                </span>
                            </div>
                        </div>
                        {isShow && <WxModalBox mediaType={1} onCancel={closeModal} title={`公众号图片素材`} visible={isShow} onOk={handleOk} />}
                    </div>
                    :
                    //素材库导入
                    <div className={style.centent_2}>
                        <p>选择图文 <span>（因官方接口限制，智能推送仅支持导入单图文素材）</span></p>
                        <List width='32%' action={action} />
                    </div>
            }

        </div>
    </Modal>
}
export default WxGraphicModal