import { Badge, Tag } from 'antd'
import { ReactNode } from 'react'

/** 欢迎语模板适用产品 */
export const welcomeTemplateData = [
    {
        label: '通用',
        value: 0
    },
    {
        label: '洗粉',
        value: 1
    },
    {
        label: '大主宰',
        value: 2
    },
    {
        label: '大队辅导员',
        value: 3
    }
]

/** 欢迎语内容组发送模式 */
export const welcomeContentData = [
    {
        label: '顺序依次发送',
        value: 1
    },
    {
        label: '随机发送',
        value: 0
    }
]

/** 业务类型 */
export const businessPlanData = [
    { label: '付费小说', value: 'NOVEL' },
    { label: '小说IAA', value: 'NOVEL_IAA' },
    { label: '付费游戏', value: 'GAME' },
    { label: '游戏IAA', value: 'GAME_IAA' },
    { label: '短剧IAA', value: 'SKIT_IAA' },
]



export const WEEK_SERIRES = [{ label: '周一', value: 1 }, { label: '周二', value: 2 }, { label: '周三', value: 3 }, { label: '周四', value: 4 }, { label: '周五', value: 5 }, { label: '周六', value: 6 }, { label: '周天', value: 7 }]
export const WEEK_SERIRES_DX: { [x: string]: string } = {
    '1': '周一',
    '2': '周二',
    '3': '周三',
    '4': '周四',
    '5': '周五',
    '6': '周六',
    '7': '周天'
}

export const STATUS_ZJ: { [x: string]: JSX.Element } = {
    'TASK_STATUS_CREATE': <Badge status="default" text={'创建中'} />,
    'TASK_STATUS_WAIT': <Badge status="warning" text={'等待中'} />,
    'TASK_STATUS_RUN': <Badge status="processing" text={'执行中'} />,
    'TASK_STATUS_FINISH': <Badge status="success" text={'执行完成'} />,
    'TASK_STATUS_FAIL': <Badge status="error" text={'执行失败'} />,
    'TASK_STATUS_DELETE': <Badge status="error" text={'已删除'} />,
    'TASK_STATUS_SUSPEND': <Badge color={'purple'} text={'执行暂停'} />,
    'TASK_STATUS_CANCEL': <Badge color={'magenta'} text={'执行取消'} />
}


export enum StatusEnum {
    TASK_STATUS_CREATE = '创建中',
    TASK_STATUS_WAIT = '等待中',
    TASK_STATUS_RUN = '执行中',
    TASK_STATUS_FINISH = '执行完成',
    TASK_STATUS_FAIL = '执行失败',
    TASK_STATUS_SUSPEND = '执行暂停',
    TASK_STATUS_CANCEL = '执行取消'
}

export const TIME_TYPE: { [x: string]: string } = {
    TIME_TYPE_SINGLE_TIMELY: '立即发送',
    TIME_TYPE_SINGLE_PLACE: '定时发送',
    TIME_TYPE_REPEAT_DAY: '每日循环',
    TIME_TYPE_REPEAT_WEEK: '每周循环',
    TIME_TYPE_REPEAT_MONTH: '每月循环'
}

export const TIME_TYPE_ZJ: { [x: string]: ReactNode } = {
    TIME_TYPE_SINGLE_TIMELY: <Tag color="#f50">立即发送</Tag>,
    TIME_TYPE_SINGLE_PLACE: <Tag color="#2db7f5">定时发送</Tag>,
    TIME_TYPE_REPEAT_DAY: <Tag color="#87d068">每日循环</Tag>,
    TIME_TYPE_REPEAT_WEEK: <Tag color="#108ee9">每周循环</Tag>,
    TIME_TYPE_REPEAT_MONTH: <Tag color="#cd201f">每月循环</Tag>
}


export const GENDER_TYPE: { [x: string]: string } = {
    '2': '女',
    '1': '男',
    '0': '未知'
}

export const EUTTaskStatus = { 0: <Badge status="default" text="创建中" />, 1: <Badge status="processing" text='执行中' />, 2: <Badge status="success" text="执行完成" />, 3: <Badge status="warning" text="暂停" /> }
// 拉群
export const LQTaskStatus = { 1: <Badge status="processing" text='执行中' />, 2: <Badge status="success" text="执行完成" />, 3: <Badge status="warning" text="暂停" />, '-1': <Badge status="error" text="执行失败" /> }

/**
 * 返回处理过的客户继承数据
 * @param schedulingStrategyDTO 
 * @param taskName 
 * @returns 
 */
export const getUserInDataData = (schedulingStrategyDTO: any[], taskName?: string): { taskName: string, strategyData: { [x: string]: any }, inheritData: { [x: string]: any }, strategyIndex: number, inheritIndex: number }[] => {
    const userInData = []
    schedulingStrategyDTO?.forEach((item, index) => {
        // 1、策略 名称 、时间、周期
        const { inheritDto, ...strategyData } = JSON.parse(JSON.stringify(item))
        inheritDto?.forEach((item1, index1, row) => {
            // 2、转移对象、文本

            userInData.push({
                taskName: taskName || '--',
                strategyData,
                inheritData: item1,
                strategyIndex: index + 1,
                inheritIndex: index1 + 1,
                strategyRowSpan: index1 === 0 ? row.length : 0
            })
        })
    })

    return userInData
}

/**
 * 返回处理过的群发数据
 * @param settings 
 * @returns 
 */
export const getGroupData = (settings: TASK_CREATE.SettingsProps): {
    groupSendName: string,
    strategyData: { [x: string]: any },
    sendData: { [x: string]: any },
    content: { [x: string]: any },
    strategyIndex: number,
    sendDataIndex: number,
    contentIndex: number,
    sendMode: 0 | 1,
    strategyDataCount: number,
    sendDataRowSpan: number,
}[] => {
    const msgData = []
    settings?.massSendingContent?.massSendingContentDTO?.forEach((mediaItem, index) => {
        // 2、策略信息 发送 发送时间
        const strategyData = settings?.massSendingStrategy?.strategySettings?.[index]
        // 下面总共多少发送对象
        const strategyDataCount = mediaItem?.sendContentDto?.reduce((pre, cur) => {
            return pre + cur.contentDTO.length
        }, 0)
        // console.log('策略信息' + (index + 1), strategyData)
        mediaItem?.sendContentDto?.forEach((contentItem, contentindex) => {
            // 发送对象
            const sendData = strategyData?.sendData?.[contentindex]
            const sendDataCount = contentItem.contentDTO.length
            // console.log('发送对象' + (contentindex + 1), sendData)
            // 4、群发内容
            contentItem?.contentDTO.forEach((item, i) => {
                // console.log('发送内容' + (i + 1), item)
                const { sendData: aa, ...sd } = strategyData
                msgData.push({
                    groupSendName: settings?.massSendingStrategy?.groupSendName,
                    // 策略信息
                    strategyData: sd,
                    // 发送模式
                    sendMode: contentItem?.sendMode,
                    // 发送对象
                    sendData,
                    // 群发内容
                    content: item,
                    strategyIndex: index + 1,
                    sendDataIndex: contentindex + 1,
                    contentIndex: i + 1,
                    strategyDataCount,
                    sendDataRowSpan: i === 0 ? sendDataCount : 0
                })
            })
        })
    })
    return msgData
}

/**
 * 返回处理过的高级群发数据
 * @param settings 
 * @returns 
 */
export const getHighGroupData = (settings: TASK_CREATE.SettingsProps): {
    groupSendName: string,
    strategyData: { [x: string]: any },
    sendData: { [x: string]: any },
    content: { [x: string]: any },
    strategyIndex: number,
    sendDataIndex: number,
    contentIndex: number,
    sendMode: 0 | 1,
    strategyDataCount: number,
    sendDataRowSpan: number,
    strategyItemSendDataCount: number
}[] => {
    const msgData = []
    settings?.highMassSendingContent?.massSendingContentDTO?.forEach((mediaItem, index) => {
        // 2、策略信息 发送 发送时间
        const strategyData = settings?.highMassSendingStrategy?.strategySettings?.[index]
        // 下面总共多少发送对象
        const strategyDataCount = mediaItem?.sendContentDto?.reduce((pre, cur) => {
            return pre + cur.contentDTO.length
        }, 0)
        // console.log('策略信息' + (index + 1), strategyData)
        mediaItem?.sendContentDto?.forEach((contentItem, contentindex) => {
            // 发送对象
            const sendData = strategyData?.sendData?.[contentindex]
            const strategyItemSendDataCount = strategyData?.sendData.length
            const sendDataCount = contentItem.contentDTO.length
            // console.log('发送对象' + (contentindex + 1), sendData)
            // 4、群发内容
            contentItem?.contentDTO.forEach((item, i) => {
                // console.log('发送内容' + (i + 1), item)
                const { sendData: aa, ...sd } = strategyData
                msgData.push({
                    groupSendName: settings?.highMassSendingStrategy?.groupSendName,
                    // 策略信息
                    strategyData: sd,
                    // 发送模式
                    sendMode: contentItem?.sendMode,
                    // 发送对象
                    sendData,
                    // 群发内容
                    content: item,
                    strategyIndex: index + 1,
                    sendDataIndex: contentindex + 1,
                    contentIndex: i + 1,
                    strategyDataCount,
                    strategyItemSendDataCount,
                    sendDataRowSpan: i === 0 ? sendDataCount : 0
                })
            })
        })
    })
    return msgData
}

/**
 * 重置客户继承数据成可编辑数据
 * @param externalUserTransferTasksDTO 
 * @returns 
 */
export const restoreUserInheritData = (externalUserTransferTasksDTO: { [x: string]: any }) => {

    const { taskName, schedulingStrategyDTO } = externalUserTransferTasksDTO

    return {
        taskName,
        schedulingStrategyDTO: schedulingStrategyDTO.map(schedulingStrategyDTOItem => {
            const { transferStrategyContentDTOS, ...strategy } = schedulingStrategyDTOItem
            return {
                ...strategy,
                inheritDto: transferStrategyContentDTOS.map(item => {

                    const { externalUserFilter, transferSuccessMsg } = item
                    const inherit: { [x: string]: any } = {
                        transferSuccessMsg
                    }
                    if (externalUserFilter) {
                        inherit.transferType = 'specify'
                        const { configName, ...configContent } = externalUserFilter
                        inherit.transferUserDto = {
                            configName,
                            configContent
                        }
                    } else {
                        inherit.transferType = 'all'
                    }
                    return inherit
                })
            }
        })
    }
}

/**
 * 重置群发数据为可编辑数据
 * @param groupSendTaskAddDTO 
 */
export const restoreGroupData = (groupSendTaskAddDTO: { [x: string]: any }, configType?: BUSINES_SPLAN_API.ConfigTypeProps) => {
    const type = configType || 'USER_GROUP'
    const { groupSendName, strategyList } = groupSendTaskAddDTO
    const massSendingContentDTO: { [x: string]: any }[] = []
    const nowTime = Date.now()
    const strategySettings = strategyList.map((item, index) => {
        const { taskDetail, ...strategy } = item
        const sendContentDto = []
        const sendData = taskDetail.map((item1, index1) => {
            const { sendMode, externalUserFilterName, contentDTO, externalUserFilter } = item1
            sendContentDto.push({
                sendMode,
                contentDTO: type === 'USER_GROUP' ? contentDTO : contentDTO.map(item2 => {
                    const { msgType, ...content } = item2
                    if (msgType === 'TASK_STATUS_MINIPROGRAM') {
                        const { miniprogram: { appId, page, title, picUrl } } = content
                        return [{
                            miniprogramAppid: appId,
                            miniprogramPage: page,
                            miniprogramTitle: title,
                            miniprogramPicurl: picUrl,
                            mediaType: 'miniprogram'
                        }]
                    } else if (msgType === 'TASK_CONTENT_TEXT') {
                        const { text } = content
                        return [{
                            textContent: text?.content,
                            mediaType: 'text'
                        }]
                    } else if (msgType === 'TASK_CONTENT_LINK') {
                        const { link: { desc, picUrl, title, url } } = content
                        return [{
                            linkDesc: desc,
                            linkPicurl: picUrl,
                            linkTitle: title,
                            linkUrl: url,
                            mediaType: 'link'
                        }]
                    } else if (msgType === 'TASK_CONTENT_IMAGE') {
                        const { image: { picUrl } } = content
                        return [{
                            imageUrl: picUrl,
                            mediaType: 'image'
                        }]
                    } else if (msgType === 'TASK_STATUS_VIDEO') {
                        const { video: { videoUrl } } = content
                        return [{
                            videoUrl: videoUrl,
                            mediaType: 'video'
                        }]
                    } else if (msgType === 'TASK_STATUS_FILE') {
                        const { file: { fileUrl } } = content
                        return [{
                            fileUrl: fileUrl,
                            mediaType: 'file'
                        }]
                    }
                    return {
                        msgType,
                        content
                    }
                }),
                id: nowTime + (index * 1000) + (index1 * 100)
            })
            if (externalUserFilter) {
                const { configName, ...configContent } = externalUserFilter
                return {
                    externalUserType: 'specify',
                    externalUserFilter: {
                        configName,
                        configContent
                    },
                    externalUserFilterName,
                    id: nowTime + (index * 1000) + (index1 * 100)
                }
            }
            return {
                externalUserType: 'all',
                externalUserFilterName,
                id: nowTime + (index * 1000) + (index1 * 100)
            }
        })

        massSendingContentDTO.push({
            sendContentDto,
            id: nowTime + (index * 1000)
        })

        return {
            ...strategy,
            sendData,
            id: nowTime + (index * 1000)
        }
    })

    return {
        massSendingStrategy: {
            groupSendName,
            strategySettings
        },
        massSendingContent: {
            massSendingContentDTO
        }
    }
}


export const momentAttachmentList = (attachmentList: any[]) => {
    return attachmentList.map((item: any) => {
        switch (item.msgType) {
            case 'TASK_CONTENT_IMAGE':
                return {
                    mediaType: 'image',
                    imageUrl: item.image.picUrl,
                    mediaFormat: item.image.mediaFormat,
                    mediaSize: item.image.mediaSize,
                    mediaPlayTime: item.image.mediaPlayTime,
                    mediaWidth: item.image.mediaWidth,
                    mediaHeight: item.image.mediaHeight
                }
            case 'TASK_STATUS_VIDEO':
                return {
                    mediaType: 'video',
                    videoUrl: item.video.videoUrl,
                    mediaFormat: item.image.mediaFormat,
                    mediaSize: item.image.mediaSize,
                    mediaPlayTime: item.image.mediaPlayTime,
                    mediaWidth: item.image.mediaWidth,
                    mediaHeight: item.image.mediaHeight
                }
            case 'TASK_STATUS_FILE':
                return { mediaType: 'file', fileUrl: item.file.fileUrl }
            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_MINIPROGRAM':
                return {
                    mediaType: 'miniprogram',
                    miniprogramAppid: item.miniprogram.appId,
                    miniprogramPage: item.miniprogram.page,
                    miniprogramPicurl: item.miniprogram.picUrl,
                    miniprogramTitle: item.miniprogram.title
                }
        }
    })
}
/**
 * 重置朋友圈数据为可编辑数据
 * @param momentCreateDTO 
 * @returns 
 */
export const restoreMomentData = (momentCreateDTO: { [x: string]: any }) => {
    const { momentSendName, strategyList } = momentCreateDTO

    const friendsContentDTO: { [x: string]: any }[] = []
    const strategySettings = strategyList.map(item => {
        const { taskDetail, ...params } = item
        friendsContentDTO.push({
            ...taskDetail,
            contentDTO: taskDetail.contentDTO.map(content => {
                return {
                    text: content.text,
                    attachmentList: momentAttachmentList(content.attachmentList)
                }
            })
        })
        return params
    })

    return {
        friendsStrategy: {
            momentSendName,
            strategySettings
        },
        friendsContent: {
            friendsContentDTO
        }
    }
}

// excel 配置
// // 复杂表头示例（两级表头）
// import XLSX from "xlsx-js-style";
// const headers = [
//     [
//         { v: "账号", s: headerStyle }, 
//         { v: '欢迎语标题', s: headerStyle }, 
//         { v: '智能标签', s: headerStyle }, 
//         { v: '内容组发送模式', s: headerStyle }, 
//         { v: '欢迎语内容', s: headerStyle }, 
//         { v: '图文链接', s: headerStyle }, 
//         { v: '小程序APPID', s: headerMustStyle }, 
//         { v: '小程序路径', s: headerMustStyle }
//     ]
// ];

// // 数据内容
// const data = settings?.corpUserList?.map((item) => {

//     return mediaContent?.map((mediaItem) => {
//         return {
//             '账号': `${item.name}（${item.corpUserId}）`,
//             '欢迎语标题': `${welcomeName}`,
//             '智能标签': `${business ? `业务：${businessPlanData.find(i => i.value === business)?.label}` : '--'}\n${bookCity ? `书城；${bookPlatForm.find(i => i.id === bookCity)?.platformName}` : '--'}\n${product ? `产品：${bookList.find(i => i.id === product)?.bookName}` : '--'}`,
//             '内容组发送模式': welcomeContentData.find(i => i.value === welcomeContentType)?.label,
//             '欢迎语内容': '--',
//             '图文链接': '--',
//             '小程序APPID': '--',
//             '小程序路径': '--'
//         }
//     })
// })

// // 将数据转换为二维数组
// const dataArray = [
//     ...headers,
//     ...data.map(row => [
//         row['账号'],
//         row['欢迎语标题'],
//         row['智能标签'],
//         row['内容组发送模式'],
//         row['欢迎语内容'],
//         row['图文链接'],
//         row['小程序APPID'],
//         row['小程序路径']
//     ])
// ];

// // 创建工作表并合并单元格
// const worksheet = XLSX.utils.aoa_to_sheet(dataArray);
// worksheet["!rows"] = [{ hpx: 30 }, ...Array(1000).fill({ hpx: 20 })]; // 设置行高
// worksheet['!cols'] = [{ width: 40 }, { width: 25 }, { width: 30 }, { width: 30 }, { width: 40 }, { width: 30 }, { width: 30 }, { width: 30 }]; // 设置列宽

// // worksheet['!merges'] = [
// //     // 合并主标题1（合并前两列）
// //     { s: { r: 1, c: 0 }, e: { r: 1, c: 1 } }
// // ];

// // 创建工作簿并导出
// const workbook = XLSX.utils.book_new();
// XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
// const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
// const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
// saveAs(blob, 'complex_data.xlsx');
// console.log(dataArray);
// 表头样式
export const headerStyle = {
    font: { bold: true, sz: 14, color: { rgb: "FFFFFF" }, name: "微软雅黑" },
    fill: { fgColor: { rgb: "1890FF" } },
    alignment: { vertical: "center", horizontal: "center" },
    border: {
        top: { style: "thin", color: { rgb: "FFFFFF" } },
        bottom: { style: "thin", color: { rgb: "FFFFFF" } },
        left: { style: "thin", color: { rgb: "FFFFFF" } },
        right: { style: "thin", color: { rgb: "FFFFFF" } }
    }
};

// 必填样式
export const headerMustStyle = {
    font: { bold: true, sz: 14, color: { rgb: "FFFFFF" }, name: "微软雅黑" },
    fill: { fgColor: { rgb: "ff7875" } },
    alignment: { vertical: "center", horizontal: "center" },
    border: {
        top: { style: "thin", color: { rgb: "FFFFFF" } },
        bottom: { style: "thin", color: { rgb: "FFFFFF" } },
        left: { style: "thin", color: { rgb: "FFFFFF" } },
        right: { style: "thin", color: { rgb: "FFFFFF" } }
    }
};


// JS表格头样式
export const headerJsStyle = {
    fill: {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: '1890ff' } // 蓝色背景
    },
    font: {
        name: '微软雅黑',
        size: 14,
        bold: true,
        color: { argb: 'FFFFFF' }
    },
    alignment: {
        vertical: 'middle',
        horizontal: 'center'
    },
    border: {
        top: { style: 'thin', color: { argb: 'FFFFFF' } },
        bottom: { style: 'thin', color: { argb: 'FFFFFF' } },
        left: { style: 'thin', color: { argb: 'FFFFFF' } },
        right: { style: 'thin', color: { argb: 'FFFFFF' } }
    }
};

// JS必填样式
export const headerJsMustStyle = {
    fill: {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'ff7875' } // 蓝色背景
    },
    font: {
        name: '微软雅黑',
        size: 14,
        bold: true,
        color: { argb: 'FFFFFF' }
    },
    alignment: {
        vertical: 'middle',
        horizontal: 'center'
    },
    border: {
        top: { style: 'thin', color: { argb: 'FFFFFF' } },
        bottom: { style: 'thin', color: { argb: 'FFFFFF' } },
        left: { style: 'thin', color: { argb: 'FFFFFF' } },
        right: { style: 'thin', color: { argb: 'FFFFFF' } }
    }
};

// 排除标签    
export const sysExternalExcludeTagList = [
    'QC_智能_移出',
    'QC_投诉客户',
    'QC_进群_异常'
]