import React, { useContext, useState } from 'react';
import style from '../../index.less';
import { App, Button, Empty, Space, Upload } from 'antd';
import { DispatchTaskCreate } from '../..';
import SettingsMassSending from './settingsMassSending';
import dayjs from 'dayjs';
import '../../global.less'
import useNewToken from '@/Hook/useNewToken';
import ShowContent from './showContent';
import { getGroupData, headerJsMustStyle, headerJsStyle, TIME_TYPE, welcomeContentData } from '../../const';
import ExcelJS from 'exceljs';
import FilterUserText from '@/pages/weComTask/components/filterUser/filterUserText';
import { RcFile } from 'antd/es/upload';
import { groupBy, readFileAsBuffer } from '@/utils/utils';
import { saveAs } from 'file-saver';
import PreviewMassSendingStrategy from './previewMassSendingStrategy';

/**
 * 群发
 * @returns 
 */
const MassSending: React.FC = () => {

    /***************************************************/
    const { token } = useNewToken()
    const { message } = App.useApp()
    const { setSettings, settings, bookPlatForm, bookList, onPreviewReset } = useContext(DispatchTaskCreate)!;

    const [newVisible, setNewVisible] = React.useState(false);
    const [createType, setCreateType] = useState<'STRATEGY' | 'CONTENT'>()
    const [downloadLoading, setDownloadLoading] = useState<boolean>(false)
    /***************************************************/

    const exportExcel = async () => {
        setDownloadLoading(true)
        const workbook = new ExcelJS.Workbook();  // 创建空工作簿
        const worksheet = workbook.addWorksheet('Sheet1');  // 添加工作表
        const headerRowIndex = 1; // 表头行索引

        // 表头冻结
        worksheet.views = [
            {
                state: 'frozen',
                ySplit: 1,          // 冻结行数
                topLeftCell: 'A2'   // 冻结后可见区域的起始单元格
            }
        ];

        // 设置全局禁止
        worksheet.protect('yourPwd', {
            deleteColumns: false,       // 禁止删除列
            sort: false,                // 禁止排序
            autoFilter: false           // 禁止自动筛选
        });

        worksheet.columns = [
            { key: 'A1', width: 20, header: '账号' },
            { key: 'A2', width: 20, header: '群发标题' },
            { key: 'A3', width: 30, header: '策略信息' },
            { key: 'A4', width: 40, header: '发送对象' },
            { key: 'A5', width: 70, header: '群发内容' },
            { key: 'A6', width: 30, header: '图文链接' },
            { key: 'A7', width: 30, header: '小程序APPID' },
            { key: 'A8', width: 30, header: '小程序路径' },
        ];

        // 表头设置样式
        worksheet.getRow(headerRowIndex).height = 30;
        Array(8).fill(0).forEach((_, index) => {
            const col = index + 1; // 从第1列开始
            // 设置表头字体样式
            worksheet.getCell(headerRowIndex, col).style = index >= 5 ? headerJsMustStyle as any : headerJsStyle as any;
        })


        const data = getGroupData(settings)
        console.log('数据', data)

        const corpUserListLength = settings?.corpUsers?.length || 0;
        const dataLength = data.length || 0;
        // 合并单元集合
        const mergeCells = [];
        // 解放填写限制区域
        const unLockArea = [];
        let dataRow = 1
        // 数据内容
        settings?.corpUsers?.forEach((item, i) => {
            // 1、客服号 群发标题

            const startRow = 2 + (i * dataLength)
            const endRow = startRow + dataLength - 1
            mergeCells.push({
                startRow,
                startColumn: 1,
                endRow,
                endColumn: 1,
            })
            mergeCells.push({
                startRow,
                startColumn: 2,
                endRow,
                endColumn: 2,
            })

            let strategyIndex = 0

            data.forEach((dataItem, index, row) => {
                if (strategyIndex !== dataItem.strategyIndex) {
                    const startRow = i * row.length + (index + 2)
                    mergeCells.push({
                        startRow,
                        startColumn: 3,
                        endRow: startRow + dataItem.strategyDataCount - 1,
                        endColumn: 3,
                    })
                }
                if (dataItem.sendDataRowSpan) {
                    const startRow = i * row.length + (index + 2)
                    mergeCells.push({
                        startRow,
                        startColumn: 4,
                        endRow: startRow + dataItem.sendDataRowSpan - 1,
                        endColumn: 4,
                    })
                }
                const mediaItem = JSON.parse(JSON.stringify(dataItem?.content?.attachmentList || []))
                if (dataItem?.content?.text?.content) {
                    mediaItem.push({
                        msgType: 'TASK_CONTENT_TEXT',
                        textContent: dataItem?.content?.text?.content
                    })
                }
                let linkPlaceholder = '<空>'
                let miniprogramPlaceholder = '<空>'
                const contentRichText = mediaItem.map(item => {
                    // 'TASK_CONTENT_TEXT' | 'TASK_CONTENT_IMAGE' | 'TASK_CONTENT_LINK' | 'TASK_STATUS_MINIPROGRAM' | 'TASK_STATUS_VIDEO' | 'TASK_STATUS_FILE'
                    switch (item.msgType) {
                        case 'TASK_CONTENT_LINK':
                            linkPlaceholder = '请输入'
                            return { text: `链接：${item.link.title}_${item.link.desc}\n`, font: { color: { argb: "FF0000" } } }
                        case 'TASK_STATUS_MINIPROGRAM':
                            miniprogramPlaceholder = '请输入'
                            return { text: `小程序：${item.miniprogram.title}\n`, font: { color: { argb: "FF0000" } } }
                        case 'TASK_STATUS_FILE':
                            return { text: `文件：${item.file.fileUrl}\n` }
                        case 'TASK_STATUS_VIDEO':
                            return { text: `视频：${item.video.videoUrl}\n` }
                        case 'TASK_CONTENT_IMAGE':
                            return { text: `图片：${item.image.picUrl}\n` }
                        case 'TASK_CONTENT_TEXT':
                            return { text: `文本：${item.textContent}\n` }
                        default:
                            return { text: `该类型没有请联系管理员` }
                    }
                })

                const richText = {
                    richText: [
                        { text: `(内容${dataItem?.contentIndex})\n`, font: { bold: true } },
                        ...contentRichText
                    ]
                }

                if (linkPlaceholder !== '<空>') {
                    unLockArea.push(`${dataRow}_6`)
                }
                if (miniprogramPlaceholder !== '<空>') {
                    unLockArea.push(`${dataRow}_7`, `${dataRow}_8`)
                }
                dataRow++;
                strategyIndex = dataItem.strategyIndex
                worksheet.addRow([
                    // 账号
                    `${item.name}（ID：${item.corpUserId}）`,
                    // 群发标题
                    `${dataItem?.groupSendName}`,
                    // 策略信息
                    {
                        richText: [
                            { text: `(策略${dataItem?.strategyIndex})\n`, font: { bold: true } },
                            { text: `名称：${dataItem?.strategyData?.strategyName || '<空>'}\n` },
                            {
                                text: (`执行类型：${TIME_TYPE[dataItem?.strategyData?.timeRepeatType]}\n`) +
                                    (dataItem?.strategyData?.sendDay ? `执行时间：${dataItem?.strategyData?.sendDay}\n` : '') +
                                    (dataItem?.strategyData?.startTime ? `执行日期：${dataItem?.strategyData?.startTime}~${dataItem?.strategyData?.endTime ? dataItem?.strategyData?.endTime : '长期执行'}\n` : '') +
                                    (dataItem?.strategyData?.sendTime ? '执行时间：' + dataItem?.strategyData?.sendTime + '\n' : '') +
                                    (dataItem?.strategyData?.repeatArray ? `执行天数：${dataItem?.strategyData?.repeatArray.join('、')}\n` : '')
                            }
                        ]
                    },
                    // 发送对象
                    {
                        richText: [
                            { text: `(发送对象${dataItem?.sendDataIndex})\n`, font: { bold: true } },
                            { text: `发送模式：${welcomeContentData?.find(i => i.value === dataItem?.sendMode)?.label}\n` },
                            {
                                text: `类型：${dataItem?.sendData?.externalUserType === 'all' ? '全部' : '指定'}\n` +
                                    (dataItem?.sendData?.externalUserType === 'specify' && dataItem?.sendData?.externalUserFilter ? FilterUserText({
                                        data: dataItem?.sendData?.externalUserFilter?.configContent,
                                        configName: dataItem?.sendData?.externalUserFilter?.configName,
                                        bookCityList: bookPlatForm?.map(item => ({ label: item.platformName, value: item.platformKey })),
                                        bookPlatForm,
                                        bookList
                                    }) : '')
                            }
                        ]
                    },
                    // 群发内容
                    richText,
                    // 图文链接
                    linkPlaceholder,
                    // 小程序APPID
                    miniprogramPlaceholder,
                    // 小程序路径
                    miniprogramPlaceholder
                ])
            })
        })

        Array(corpUserListLength * dataLength).fill(0).forEach((_, index) => {
            worksheet.getRow(index + headerRowIndex + 1).height = 100; // 设置行高
            worksheet.getRow(index + headerRowIndex + 1).alignment = {
                vertical: 'middle',
                wrapText: true
            }
            // 分组设置背景色
            if (index % (dataLength * 2) < dataLength) {
                worksheet.getRow(index + headerRowIndex + 1).eachCell(function (cell, rowNumber) {
                    if (rowNumber <= 8) {
                        cell.border = {
                            top: { style: 'thin', color: { argb: 'D4D4D4' } },
                            bottom: { style: 'thin', color: { argb: 'D4D4D4' } },
                            left: { style: 'thin', color: { argb: 'D4D4D4' } },
                            right: { style: 'thin', color: { argb: 'D4D4D4' } }
                        }
                        cell.fill = {
                            type: 'pattern',
                            pattern: 'solid',
                            fgColor: { argb: 'f0f0f0' }
                        }
                    }
                })
            } else {
                worksheet.getRow(index + headerRowIndex + 1).eachCell(function (cell, rowNumber) {
                    if (rowNumber <= 8) {
                        cell.border = {
                            top: { style: 'thin', color: { argb: 'D4D4D4' } },
                            bottom: { style: 'thin', color: { argb: 'D4D4D4' } },
                            left: { style: 'thin', color: { argb: 'D4D4D4' } },
                            right: { style: 'thin', color: { argb: 'D4D4D4' } }
                        }
                    }
                })
            }
        })

        // 合并单元格
        mergeCells.forEach(({ startRow, startColumn, endRow, endColumn }) => {
            worksheet.mergeCells(startRow, startColumn, endRow, endColumn); // 合并单元格
        })

        // 设置可填写区域
        for (let rowNum = 1; rowNum <= corpUserListLength * dataLength; rowNum++) {
            for (let colNum = 1; colNum <= 3; colNum++) {
                if (unLockArea.includes(`${rowNum}_${colNum + 5}`)) {
                    const cell = worksheet.getCell(rowNum + 1, colNum + 5);
                    cell.protection = { locked: false };
                    cell.fill = {
                        type: 'pattern',
                        pattern: 'solid',
                        fgColor: { argb: 'ffadd2' }
                    }
                }
            }
        }
        // 生成文件内容
        workbook.xlsx.writeBuffer().then(buffer => {
            // 通过 Blob 下载
            const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            saveAs(blob, `群发内容配置_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
            setTimeout(() => setDownloadLoading(false), 1000)
        });
    }

    // 读取Excel
    const readExcelContent = async (file: RcFile) => {
        const buffer: any = await readFileAsBuffer(file);
        const workbook = new ExcelJS.Workbook();
        await workbook.xlsx.load(buffer);  // 加载 Excel 内容

        const worksheet = workbook.worksheets[0];  // 获取第一个工作表
        const data = [];

        worksheet.eachRow((row) => {
            const rowData = {};
            row.eachCell((cell, colNumber) => {
                if (cell.isHyperlink) {
                    rowData[`col${colNumber}`] = cell.text || '';
                } else {
                    rowData[`col${colNumber}`] = cell.value || '';
                }
            });
            data.push(rowData);
        });

        data.shift();  // 删除表头
        const NULLDATA = ['请输入', '']
        if (data?.some(item => (NULLDATA.includes(item.col6) || !item?.col6 || NULLDATA.includes(item.col7) || !item?.col7 || NULLDATA.includes(item.col8) || !item?.col8))) {
            message.error('请正确填写Excel内容！')
            return
        }

        const msgData = getGroupData(settings)
        console.log('读取的Excel数据', data, msgData)

        if (msgData.length * settings?.corpUsers?.length !== data?.length) {
            message.error('数量对不上，请正确填写Excel内容！')
            return
        }

        const groupData = groupBy(data, (item) => [item['col1']]).reduce((acc, cur) => {
            const id = cur[0]['col1'].split('ID：')[1].replace(/\）$/, '');
            acc[id] = cur
            return acc;
        }, {});

        const corpUsers = settings?.corpUsers?.map(item => {
            const groupMsgContent = []
            groupData[item.corpUserId]?.forEach((i: any) => {
                const strategyIndex = i.col3.richText[0].text.split('(策略')[1]?.split(')')[0]
                const sendDataIndex = i.col4.richText[0].text.split('(发送对象')[1]?.split(')')[0]
                const contentIndex = i.col5.richText[0].text.split('(内容')[1]?.split(')')[0]
                const layer1 = strategyIndex - 1;
                if (!groupMsgContent[layer1]) groupMsgContent[layer1] = [];              // 初始化第二层
                const layer2 = sendDataIndex - 1;
                if (!groupMsgContent[layer1][layer2]) groupMsgContent[layer1][layer2] = [];
                groupMsgContent[strategyIndex - 1][sendDataIndex - 1][contentIndex - 1] = {
                    linkUrl: i.col6 === '<空>' ? undefined : i.col6?.toString()?.trim(),
                    miniprogramAppid: i.col7 === '<空>' ? undefined : i.col7?.toString()?.trim(),
                    miniprogramPage: i.col8 === '<空>' ? undefined : i.col8?.toString()?.trim()
                }
            })
            console.log('群发内容', groupMsgContent)
            return {
                ...item,
                groupMsgContent
            }
        })
        console.log('corpUsers', corpUsers)
        setSettings({
            ...settings,
            corpUsers
        })
    }

    return <>
        <div className={`${style.settingsBody_content_row}`} style={{ width: 'calc(100% / 2)' }}>
            <div className={`${style.settingsBody_content_col}`} style={{ width: '50%' }}>
                <div className={style.title}>
                    <span>群发</span>
                </div>
                <div className={style.detail}>
                    <div className={style.detail_title}>群发策略配置</div>
                    <div className={style.detail_body}>
                        {settings?.massSendingStrategy && Object.keys(settings?.massSendingStrategy).length > 0 ? <>
                            <PreviewMassSendingStrategy massSendingStrategy={settings?.massSendingStrategy} />
                        </> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    </div>
                </div>
                <div className={style.detail_footer}>
                    <Button
                        type="link"
                        style={{ padding: 0, fontSize: 12, color: token.colorPrimary }}
                        size='small'
                        onClick={() => {
                            setNewVisible(true);
                            setCreateType('STRATEGY')
                        }}
                    >编辑</Button>
                </div>
            </div>
            <div className={`${style.settingsBody_content_col}`} style={{ width: '50%' }}>
                <div className={style.title}>
                    <span></span>
                    {(settings?.massSendingStrategy && Object.keys(settings?.massSendingStrategy).length > 0) && <Space>
                        {/* {settings?.massSendingContent?.massSendingContentDTO?.some(item => item?.sendContentDto?.some(si => si?.contentDTO?.some(i => i?.attachmentList?.some(a => ['TASK_CONTENT_LINK', 'TASK_STATUS_MINIPROGRAM'].includes(a?.msgType))))) && <>
                            <Button
                                type="link"
                                style={{ padding: 0, fontSize: 12 }}
                                loading={downloadLoading}
                                onClick={() => { exportExcel() }}
                            >下载</Button>
                            <Upload
                                accept={'.xlsx'}
                                action="#"
                                showUploadList={false}
                                customRequest={() => { }}
                                beforeUpload={async (file: RcFile): Promise<any> => {
                                    readExcelContent(file)
                                    onPreviewReset()
                                }}
                            >
                                <Button
                                    type="link"
                                    style={{ padding: 0, fontSize: 12 }}
                                >{settings?.corpUsers?.every(item => item?.groupMsgContent?.length) ? 'Excel内容已上传，重新上传' : '上传Excel'}</Button>
                            </Upload>
                        </>} */}
                        <Button
                            type="link"
                            danger
                            style={{ padding: 0, fontSize: 12 }}
                            onClick={() => {
                                const corpUsers = settings?.corpUsers?.map(item => {
                                    delete item?.groupMsgContent
                                    return item
                                })
                                setSettings({
                                    ...settings,
                                    corpUsers,
                                    massSendingStrategy: undefined,
                                    massSendingContent: undefined
                                })
                                onPreviewReset()
                            }}
                        >清空</Button>
                    </Space>}
                </div>
                <div className={style.detail}>
                    <div className={style.detail_title}>群发内容配置</div>
                    <div className={style.detail_body} style={{ padding: 0 }}>
                        {settings?.massSendingContent && Object.keys(settings?.massSendingContent) ? <>
                            <ShowContent
                                strategySettings={settings?.massSendingStrategy?.strategySettings}
                                massSendingContent={settings?.massSendingContent}
                            />
                        </> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    </div>
                </div>
                <div className={style.detail_footer}>
                    <Button
                        type="link"
                        style={{ padding: 0, fontSize: 12, color: token.colorPrimary }}
                        size='small'
                        onClick={() => {
                            if (!(settings?.massSendingStrategy && Object.keys(settings?.massSendingStrategy))) {
                                message.error('请先配置策略')
                                return
                            }
                            setNewVisible(true); setCreateType('CONTENT')
                        }}
                    >编辑</Button>
                </div>
            </div>
        </div>

        {/* 模板配置 */}
        {newVisible && <SettingsMassSending
            visible={newVisible}
            createType={createType}
            bookCityList={bookPlatForm?.map(item => ({ label: item.platformName, value: item.platformKey, id: item.id }))}
            value={{
                massSendingContent: settings?.massSendingContent,
                massSendingStrategy: settings?.massSendingStrategy
            }}
            onClose={() => {
                setNewVisible(false)
            }}
            onChange={(values, type) => {
                const corpUsers = settings?.corpUsers?.map(item => {
                    delete item?.groupMsgContent
                    return item
                })
                if (!values?.massSendingContent && settings?.corpUsers?.some(item => item?.groupMsgContent?.length)) {
                    setSettings({
                        ...settings,
                        ...values,
                        corpUsers
                    })
                } else {
                    setSettings({
                        ...settings,
                        ...values,
                        corpUsers
                    })
                }

                if (type === 'OK') {
                    setNewVisible(false)
                }
                onPreviewReset()
            }}
        />}
    </>
};

export default React.memo(MassSending);