import useNewToken from "@/Hook/useNewToken"
import PreviewMsg from "@/pages/weComTask/components/previewMsg"
import { emoList } from "@/pages/weComTask/components/textEditor/Expression"
import { copy } from "@/utils/utils"
import { Avatar, Badge, Button, Space, Tooltip, Typography } from "antd"
import { ColumnsType } from "antd/es/table"
import { InfoCircleOutlined, QuestionCircleOutlined, UserOutlined } from "@ant-design/icons"
import GroupErrorCountList from "./groupErrorCountList"
import GroupReSend from "./groupReSend"
import { GENDER_TYPE } from "@/pages/weComTask/page/businessPlan/create/const"

export function groupMsgCorpUserListConfig(change: (data: any, type: string) => void): ColumnsType<any> {

    let arr: ColumnsType<any> = [
        {
            title: '所属企业',
            dataIndex: 'corpName',
            key: 'corpName',
            align: 'center',
            width: 120,
        },
        {
            title: '企微号',
            dataIndex: 'userName',
            key: 'userName',
            align: 'center',
            width: 120,
            ellipsis: true,
            render: (a: string, b: any) => {
                return a + `(${b?.userId})`
            }
        },
        {
            title: '发送时间',
            dataIndex: 'sendTime',
            key: 'sendTime',
            align: 'center',
            width: 120,
            ellipsis: true,
        },
        {
            title: '预计发送时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
            width: 120,
            ellipsis: true,
        },
        {
            title: '发送状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            width: 100,
            render: (a: number) => {
                return <span>{{ '0': <Badge status="error" text='未发送' />, '2': <Badge status="success" text='已发送' /> }[a]}</span>
            }
        },
        {
            title: '发送对象',
            dataIndex: 'userCount',
            key: 'userCount',
            align: 'center',
            width: 100,
            render: (a: number) => {
                return <span>好友{a > 0 ? a : 0}个</span>
            }
        },
        {
            title: '发送成功',
            dataIndex: 'sendSuccessCount',
            key: 'sendSuccessCount',
            align: 'center',
            width: 80,
            render: (a) => {
                return a > 0 ? a : 0
            }
        },
        {
            title: '发送失败',
            dataIndex: 'sendFailCount',
            key: 'sendFailCount',
            align: 'center',
            width: 80,
            render: (a) => {
                return a > 0 ? a : 0
            }
        },
        {
            title: '因客户不是好友导致发送失败',
            dataIndex: 'unFriendCount',
            key: 'unFriendCount',
            align: 'center',
            width: 80,
            ellipsis: true,
            render: (a) => {
                return a > 0 ? a : 0
            }
        },
        {
            title: '因客户已经收到其他群发消息导致发送失败',
            dataIndex: 'othersSendCount',
            key: 'othersSendCount',
            align: 'center',
            width: 80,
            ellipsis: true,
            render: (a) => {
                return a > 0 ? a : 0
            }
        },
        {
            title: '消息ID',
            dataIndex: 'msgId',
            key: 'msgId',
            align: 'center',
            width: 100,
            ellipsis: true,
            render: (a: string) => {
                return <a onClick={() => copy(a)}>{a}</a>
            }
        },
        {
            title: '操作',
            dataIndex: 'cz',
            key: 'cz',
            align: 'center',
            fixed: 'right',
            width: 120,
            render: (a: any, b: { status: any, sendCancelRemindStatus: number }) => {
                return b?.status == '2' ? '--' : <Space wrap>
                    {b?.sendCancelRemindStatus === 1 ? '已取消发送' : <>
                        <Button type="link" style={{ padding: 0 }} disabled={b?.status == '2'} onClick={() => { change(b, 'txSend') }} >{'提醒发送'}</Button>
                        <Button type="link" style={{ padding: 0 }} disabled={b?.status == '2'} onClick={() => { change(b, 'qxSend') }} >{'取消发送'}</Button>
                    </>}
                </Space>
            }
        },
    ]
    return arr
}


export function groupTaskNotesTableConfig(refresh: () => void): ColumnsType<any> {
    const { token } = useNewToken()
    // 处理群发内容
    function groupBody(item) {
        let msgData = []
        if (item?.text?.content) {
            let newValue = item?.text?.content
            let newEmo = emoList.reduce((prev, cur) => {
                return [...prev, ...cur]
            }, [])
            let emos = newValue.match(/\[[\u4e00-\u9fa5]+\]/g)
            if (emos && emos?.length) {
                emos.forEach((emo: any) => {
                    let emoData = newEmo.find(o => `[${o.name}]` === emo)
                    if (emoData) {
                        newValue = newValue.replace(emo, `<img src="${emoData.url}" alt="${emoData.name}" style="width:20px;height:20px"/>`)
                    }
                })
            }
            if (newValue.includes('\n')) {
                newValue = newValue.replace('\n', `<br/>`)
            }
            let names = newValue.match(/%[\u4e00-\u9fa5]+%/g)
            if (names && names?.length) {
                newValue = newValue.replace('%昵称%', ` <span style="display: inline-block;margin:0 1px;position: relative; border: 1px solid ${token.colorBorder}; padding: ${token.paddingXS}px; border-radius: ${token.borderRadius}px;color: ${token.colorTextBase}; background: ${token.colorSuccess};color:${token.colorTextLightSolid}" contenteditable="false">昵称<strong data-name="昵称" style="padding: 0 6px;cursor:pointer" onclick="let html =document.querySelector('[data-name=昵称').parentElement.parentElement.innerHTML;let span = ' '+document.querySelector('[data-name=昵称]').parentElement.outerHTML+' ';console.log('=',html,'=');console.log('=',span,'=');document.execCommand('selectAll');document.execCommand('delete'); document.execCommand('insertHTML', true, html.replace(span,''));">X</strong></span> `)
            }
            msgData.push({
                textContent: newValue,
                mediaType: 'text'
            })
        }
        if (item?.attachmentList && item?.attachmentList?.length > 0) {
            let newAttachmentList = item?.attachmentList.map((item: any) => {
                switch (item.msgType) {
                    case 'TASK_CONTENT_IMAGE':
                        return { mediaType: 'image', imageUrl: item?.image?.picUrl }
                    case 'TASK_CONTENT_LINK':
                        return { mediaType: 'link', linkDesc: item?.link?.desc, linkPicurl: item?.link?.picUrl, linkTitle: item?.link?.title, linkUrl: item?.link?.url }
                    case 'TASK_STATUS_FILE':
                        return { mediaType: 'file', fileUrl: item?.file?.fileUrl }
                    case 'TASK_STATUS_VIDEO':
                        return { mediaType: 'video', videoUrl: item?.video?.videoUrl }
                    case 'TASK_STATUS_MINIPROGRAM':
                        return {
                            mediaType: 'miniprogram',
                            miniprogramAppid: item.miniprogram?.appId,
                            miniprogramPage: item?.miniprogram?.page,
                            miniprogramPicurl: item?.miniprogram?.picUrl,
                            miniprogramTitle: item?.miniprogram?.title
                        }
                }
            })
            msgData = msgData.concat(newAttachmentList)
        }
        return msgData
    }
    return [
        {
            title: '任务ID',
            dataIndex: 'taskId',
            key: 'taskId',
            align: 'center',
            width: 65
        },
        {
            title: '客服号名称',
            dataIndex: 'corpUserName',
            key: 'corpUserName',
            align: 'center',
            width: 150,
            ellipsis: true
        },
        {
            title: '消息ID',
            dataIndex: 'msgId',
            key: 'msgId',
            align: 'center',
            width: 250,
            ellipsis: true,
            render: (a: string) => {
                return <a onClick={() => copy(a)}>{a}</a>
            }
        },
        {
            title: <div>发送内容<Tooltip title="2025-01-10前的群发无法查看内容"><InfoCircleOutlined /></Tooltip></div>,
            dataIndex: 'contentDTO',
            key: 'contentDTO',
            align: 'center',
            width: 90,
            ellipsis: true,
            render: (a, b) => {
                let data = []
                if (a) {
                    data = groupBody(a)
                }

                return data?.length > 0 ? <Tooltip color={"#fff"} title={<PreviewMsg type="MSG" minWidth={"200px"} height={'calc(100vh - 400px)'} content={{ data }} />}>
                    <a>查看内容</a>
                </Tooltip> : "无内容"
            }
        },
        {
            title: '发送时间',
            dataIndex: 'createTime',
            key: 'createTime',
            ellipsis: true,
            align: 'center',
            width: 130
        },
        {
            title: <>执行结果 <Tooltip title={<span>此结果为任务在后台创建后是否成功提交到腾讯。腾讯下发至手机和手机的最终执行结果请查看下发企微号。</span>}><QuestionCircleOutlined style={{ color: 'red' }} /></Tooltip></>,
            dataIndex: 'errCode',
            key: 'errCode',
            width: 60,
            align: 'center',
            ellipsis: true,
            render: (a: number) => {
                return { 0: '成功', 1: '失败' }[a]
            }
        },
        {
            title: '失败人数',
            dataIndex: 'failCount',
            key: 'failCount',
            align: 'center',
            ellipsis: true,
            width: 60,
            render: (a: any, b: any) => {
                return <GroupErrorCountList failCount={a} corpId={b?.corpId} msgId={b?.msgId} taskId={b?.taskId} />
            }
        },
        {
            title: '错误信息',
            dataIndex: 'errMsg',
            key: 'errMsg',
            ellipsis: true,
            width: 150
        },
        {
            title: '操作',
            dataIndex: 'cz',
            key: 'cz',
            width: 70,
            fixed: 'right',
            align: 'center',
            render(_, record) {
                if (record.errCode === 1) {
                    return <GroupReSend onChange={refresh} id={record.taskId} corpUserId={record.corpUserId} />
                }
                return '--'
            },
        },
    ]
}



export function groupErrorCountTableConfig(): ColumnsType<any> {
    return [
        {
            title: '客户名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
            width: 100,
            render: (a: string, b: any) => {
                return <Space>
                    <Avatar shape="square" size="small" icon={<UserOutlined />} src={b?.avatar} />
                    <Typography.Paragraph ellipsis={{ rows: 1, tooltip: true }} style={{ width: 62, marginBottom: 0 }}>{a}</Typography.Paragraph>
                </Space>
            }
        },
        {
            title: '用户ID',
            dataIndex: 'externalUserId',
            key: 'externalUserId',
            align: 'center',
            ellipsis: true,
            render: (a: string) => {
                return <a onClick={() => copy(a)}>{a}</a>
            }
        },
        {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            align: 'center',
            width: 80,
            render: (a: number) => {
                return <span>{GENDER_TYPE[a]}</span>
            }
        },
    ]
}