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, useReducer, 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,
}
type State = {
    actionData?: any//数据
}
export type Action = {
    type: 'pushData' | 'initData' | 'range',
    params?: any
}
function reducer(state: State, action: Action) {
    let { type, params } = action
    let newData = JSON.parse(JSON.stringify(state.actionData))
    switch (type) {
        case 'pushData':
            let { eq, ...param } = params
            Object.keys(param).forEach((key: string) => {
                newData.articles.forEach((obj: any, index: number) => {
                    if (index === eq) {
                        obj[key] = params[key]
                    }
                })
            })
            return { ...state, actionData: newData }
        case 'initData':
            return { ...state, actionData: params.actionData }
        default:
            return state;
    }
}
const WxGraphicListModal = (props: Props) => {
    const [state, dispatch] = useReducer(reducer, { actionData: { articles: [{}, {}, {}, {}, {}, {}, {}, {}] } })
    const { actionData: action } = state
    const { visible, onCancel, onOK, defaultData } = props
    const [isShow, setIsShow] = useState<boolean>(false)//图片弹窗
    const [eq, setEq] = useState<number>(1)//切换
    const [ref, setRef] = useState<any>(null)//存放实例
    const [range, setRange] = useState<Range>()//存放光标丢失位置
    const [isImport, setIsImport] = useState<boolean>(false)//点击导入
    const [radio, setRadio] = useState<number>(0)
    const getWeItData = useModel('useOperating.useMaterialContent', model => model.getWeItData)
    const actionWX = useModel('useOperating.useWxGroupList', model => model.state.actionWX)

    //确定
    const callback = useCallback(() => {
        let arr: any = action.articles.filter((item: any) => JSON.stringify(item) !== '{}')//筛除空对象|| 
        arr = arr.filter((item: any) => {
            return item.title
        })
        arr = arr.map((item: any) => {
            return { newsPicUrl: item.thumbUrl, newsUrl: item.contentSourceUrl, newsDescription: item.digest, newsTitle: item.title.replace(/<[/]?span[^>]*>/ig, '#') }
        })
        let isOk: boolean = arr.every((item: any) => item.newsPicUrl && item.newsDescription && item.newsUrl && item.newsTitle)//检测全部必填项
        if (isOk) {
            onOK({ newsList: arr, indexId: action.indexId }, 5)
        } else {
            message.error('请检测标题，图片，描述，链接是否填写完整！不需要的篇章请全部留空')
        }
    }, [action])
    //切换
    const handelRadio = useCallback((e: RadioChangeEvent) => {
        let v = e.target.value
        setEq(v)
    }, [])
    //选中素材时的操作
    const handelAction = useCallback((data: any) => {
        let obj = { mediaId: data.mediaId, articles: [...data.content.articles, ...Object.values(Array(8 - data.content.articles.length).fill({})).map(n => n)] }
        dispatch({ type: 'initData', params: { actionData: obj } })//存放选中数据
    }, [ref, eq])
    //开关图片弹窗
    const closeModal = useCallback(() => {
        setIsShow(!isShow)
    }, [isShow])
    //选中图片
    const handleOk = (data: any) => {
        dispatch({ type: 'pushData', params: { thumbUrl: data.url, eq: radio } })
        closeModal()
    }
    //插入粉丝昵称
    const pushName = useCallback(() => {
        let span = document.createElement('span')
        span.className = style.nickName
        span.setAttribute('contentEditable', 'false')
        span.innerText = `粉丝昵称`
        range?.insertNode(span)
        dispatch({ type: 'pushData', params: { title: ref.innerHTML, eq: radio } })
    }, [range, radio])
    //复制只取纯文本
    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);
        }
    }
    //光标丢失记录位置
    const onBlur = useCallback(() => {
        let selection = window.getSelection()
        let range = selection?.getRangeAt(0)
        setRange(range)
        dispatch({ type: 'pushData', params: { title: ref.innerHTML, eq: radio } })
    }, [ref, radio])
    // useEffect(() => {
    //     if (ref) {
    //         let { title } = action?.articles[radio]
    //         ref.innerText = title || ''
    //     }

    // }, [radio, ref, action])
    //初始光标选中
    useEffect(() => {
        ref?.focus()
    }, [ref])
    //获取微信图文列表
    useEffect(() => {
        if(actionWX){
            getWeItData.run({ appId: actionWX.appid, count: 1000, offset: 0 })
        }
    }, [actionWX])
    //获取同步更新素材
    const sync = () => {
        getWeItData.run({ appId: actionWX.appid, count: 1000, offset: 0, isNew: true })
    }
    //连接输入
    const handelLink = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let v = e.target.value
        dispatch({ type: 'pushData', params: { contentSourceUrl: v, eq: radio } })
    }, [radio])
    //摘要输入
    const handelText = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
        let v = e.target.value
        dispatch({ type: 'pushData', params: { digest: v, eq: radio } })
    }, [radio])
    /**篇数选择 */
    const radioChange = useCallback((e: RadioChangeEvent) => {
        let v = e.target.value
        setRadio(v)
    }, [])
    //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])
    /**编辑回填 */
    useEffect(() => {
        if (defaultData?.newsList) {
            let arr = defaultData?.newsList.map((item: any) => {
                return { title: item.newsTitle.replace('#粉丝昵称#', `<span class=${style.nickName} contenteditable="false">粉丝昵称</span>`), thumbUrl: item.newsPicUrl, contentSourceUrl: item.newsUrl, digest: item.newsDescription }//转义
            })
            arr = [...arr, ...Object.values(Array(8 - arr.length).fill({})).map(n => n)]  //不足8个填充
            dispatch({ type: 'initData', params: { actionData: { articles: arr, indexId: defaultData?.indexId } } })
        }
    }, [defaultData])
    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>
                <Button type='primary' onClick={sync} loading={getWeItData?.loading}>同步最新素材</Button>
            </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 className={style.graphic_list}>
                            <Radio.Group
                                onChange={radioChange}
                                value={radio}>
                                {
                                    action?.articles?.map((list: any, index: number) => {
                                        return <Radio key={index} value={index}>第{index + 1}篇</Radio>
                                    })
                                }
                            </Radio.Group>
                            {
                                action?.articles?.map((list: any, index: number) => {

                                    return radio === index && <div key={index}>
                                        <Row style={{ width: '80%' }}>
                                            <Col span={24}>
                                                <label >图文标题 ：<span>(必填)</span></label>
                                                <div
                                                    contentEditable="true"
                                                    className={style.editor}
                                                    ref={(ref) => setRef(ref)}
                                                    onBlur={onBlur}
                                                    dangerouslySetInnerHTML={{ __html: list?.title }}
                                                    onPaste={textPaste}
                                                />
                                                {/* <label >点击插入：<Tag color='orange' onClick={pushName}>粉丝昵称</Tag></label> */}
                                            </Col>
                                            <Col span={24}>
                                                <label >描述内容 ：</label>
                                                <Input.TextArea rows={5} placeholder='填写图文描述' onChange={handelText} value={list?.digest} />
                                            </Col>
                                            <Col span={24}>
                                                <label >链接设置 ：<span>(必填)</span></label>
                                                <Input placeholder='请输入跳转链接，且必须以http://或https://开头' onChange={handelLink} value={list?.contentSourceUrl} />
                                            </Col>
                                        </Row>
                                        <div>
                                            <label >图文封面 ：</label>
                                            <span className={list?.thumbUrl ? style.imgupload : ''} onClick={closeModal}>
                                                {
                                                    list?.thumbUrl ? <img src={list?.thumbUrl} /> : <PlusOutlined style={{ fontSize: 30 }} />
                                                }
                                                <div><PlusOutlined style={{ fontSize: 30, color: '#fff' }} /> </div>
                                            </span>
                                        </div>
                                    </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 WxGraphicListModal