import React, { useContext, useState } from 'react';
import style from '../../index.less';
import { App, Button, Empty, Space, Upload } from 'antd';
import { DispatchTaskCreate } from '../..';
import dayjs from 'dayjs';
import '../../global.less'
import useNewToken from '@/Hook/useNewToken';
import { getHighGroupData, 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 SettingsHighMassSending from './settingsHighMassSending';
import { saveAs } from 'file-saver';
import PreviewMassSendingStrategy from '../massSending/previewMassSendingStrategy';
import ShowContent from '../massSending/showContent';

/**
 * 高级群发
 * @returns 
 */
const HighMassSending: 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: 45, header: '群发外部联系人' },
            { key: 'A6', width: 70, header: '群发内容' },
            { key: 'A7', width: 30, header: '图文链接' },
            { key: 'A8', width: 30, header: '小程序APPID' },
            { key: 'A9', width: 30, header: '小程序路径' },
        ];

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


        const data = getHighGroupData(settings)
        console.log('数据', data)
        let rowLength = 0
        // 合并单元集合
        const mergeCells = [];
        // 解放填写限制区域
        const unLockArea = [];
        let dataRow = 1
        // 数据内容
        settings?.corpUsers?.forEach((item, i) => {
            const startRow = 2 + rowLength
            let strategyIndex = 0
            data.forEach((dataItem) => {
                const externalUserListLength = item.externalUserList.length
                const startRow = rowLength + 2
                if (strategyIndex !== dataItem.strategyIndex) {
                    mergeCells.push({
                        startRow,
                        startColumn: 3,
                        endRow: startRow + (dataItem.strategyDataCount * externalUserListLength) - 1,
                        endColumn: 3
                    })
                }
                if (dataItem.sendDataRowSpan) {
                    mergeCells.push({
                        startRow,
                        startColumn: 4,
                        endRow: startRow + (dataItem.sendDataRowSpan * externalUserListLength) - 1,
                        endColumn: 4,
                    })
                }

                const mediaItem = JSON.parse(JSON.stringify(dataItem?.content || []))
                let linkPlaceholder = '<空>'
                let miniprogramPlaceholder = '<空>'
                const contentRichText = mediaItem.map(item => {
                    switch (item.mediaType) {
                        case 'link':
                            linkPlaceholder = '请输入'
                            return { text: `链接：${item.linkTitle}_${item.linkDesc}\n`, font: { color: { argb: "FF0000" } } }
                        case 'miniprogram':
                            miniprogramPlaceholder = '请输入'
                            return { text: `小程序：${item.miniprogramTitle}\n`, font: { color: { argb: "FF0000" } } }
                        case 'file':
                            return { text: `文件：${item.fileUrl}\n` }
                        case 'video':
                            return { text: `视频：${item.videoUrl}\n` }
                        case 'image':
                            return { text: `图片：${item.imageUrl}\n` }
                        case 'text':
                            return { text: `文本：${item.textContent}\n` }
                        default:
                            return { text: `该类型没有请联系管理员` }
                    }
                })

                const richText = {
                    richText: [
                        { text: `(内容${dataItem?.contentIndex})\n`, font: { bold: true } },
                        ...contentRichText
                    ]
                }
                
                item.externalUserList.forEach((user) => {
                    rowLength += 1;
                    if (linkPlaceholder !== '<空>') {
                        unLockArea.push(`${dataRow}_7`)
                    }
                    if (miniprogramPlaceholder !== '<空>') {
                        unLockArea.push(`${dataRow}_8`, `${dataRow}_9`)
                    }

                    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,
                                            configType: 'GROUP_GROUP'
                                        }) : '')
                                }
                            ]
                        },
                        {
                            richText: [
                                { text: `消息发送号外部联系人\n`, font: { bold: true } },
                                { text: `${user?.externalUserId}（${user.name}）\n` },
                                { text: `群聊所在主体\n`, font: { bold: true } },
                                { text: `${user?.corpId}（${user.corpName}）` }
                            ]
                        },
                        // 群发内容
                        richText,
                        // 图文链接
                        linkPlaceholder,
                        // 小程序APPID
                        miniprogramPlaceholder,
                        // 小程序路径
                        miniprogramPlaceholder
                    ])

                    dataRow++;
                    worksheet.getRow(dataRow).height = 65; // 设置行高
                    worksheet.getRow(dataRow).alignment = {
                        vertical: 'middle',
                        wrapText: true
                    }
                    if (i % 2) {
                        worksheet.getRow(dataRow).eachCell(function (cell, rowNumber) {
                            if (rowNumber <= 9) {
                                cell.border = {
                                    top: { style: 'thin', color: { argb: '525252' } },
                                    bottom: { style: 'thin', color: { argb: '525252' } },
                                    left: { style: 'thin', color: { argb: '525252' } },
                                    right: { style: 'thin', color: { argb: '525252' } }
                                }
                                cell.fill = {
                                    type: 'pattern',
                                    pattern: 'solid',
                                    fgColor: { argb: 'f0f0f0' }
                                }
                            }
                        })
                    } else {
                        worksheet.getRow(dataRow).eachCell(function (cell, rowNumber) {
                            if (rowNumber <= 9) {
                                cell.border = {
                                    top: { style: 'thin', color: { argb: '525252' } },
                                    bottom: { style: 'thin', color: { argb: '525252' } },
                                    left: { style: 'thin', color: { argb: '525252' } },
                                    right: { style: 'thin', color: { argb: '525252' } }
                                }
                            }
                        })
                    }
                })

                strategyIndex = dataItem.strategyIndex
            })

            // 1、客服号 群发标题
            const endRow = 2 + rowLength - 1
            mergeCells.push({
                startRow,
                startColumn: 1,
                endRow,
                endColumn: 1,
            })
            mergeCells.push({
                startRow,
                startColumn: 2,
                endRow,
                endColumn: 2,
            })
        })
        // 合并单元格
        mergeCells.forEach(({ startRow, startColumn, endRow, endColumn }) => {
            worksheet.mergeCells(startRow, startColumn, endRow, endColumn); // 合并单元格
        })

        // 设置可填写区域
        for (let rowNum = 1; rowNum <= rowLength; rowNum++) {
            for (let colNum = 1; colNum <= 3; colNum++) {
                if (unLockArea.includes(`${rowNum}_${colNum + 6}`)) {
                    const cell = worksheet.getCell(rowNum + 1, colNum + 6);
                    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' });
            console.log('33333333333333333333333', blob)
            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.col9) || !item?.col9 || NULLDATA.includes(item.col7) || !item?.col7 || NULLDATA.includes(item.col8) || !item?.col8))) {
            message.error('请正确填写Excel内容！')
            return
        }

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

        if (settings?.corpUsers?.reduce((pre, cur) => pre + (cur?.externalUserList?.length * msgData.length), 0) !== 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 highGroupMsgContent = []
            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 externalUserId = i.col5.richText[1].text.split('（')[0]
                const corpId = i.col5.richText[3].text.split('（')[0]
                const contentIndex = i.col6.richText[0].text.split('(内容')[1]?.split(')')[0]
                const layer1 = strategyIndex - 1;
                if (!highGroupMsgContent[layer1]) highGroupMsgContent[layer1] = [];              // 初始化第二层
                const layer2 = sendDataIndex - 1;
                const layer3 = corpId + '-' + externalUserId
                if (!highGroupMsgContent[layer1][layer2]) highGroupMsgContent[layer1][layer2] = {};
                if (!highGroupMsgContent[layer1][layer2][layer3]) highGroupMsgContent[layer1][layer2][layer3] = [];


                highGroupMsgContent[strategyIndex - 1][sendDataIndex - 1][layer3][contentIndex - 1] = {
                    linkUrl: i.col7 === '<空>' ? undefined : i.col7?.toString()?.trim(),
                    miniprogramAppid: i.col8 === '<空>' ? undefined : i.col8?.toString()?.trim(),
                    miniprogramPage: i.col9 === '<空>' ? undefined : i.col9?.toString()?.trim()
                }
            })
            return {
                ...item,
                highGroupMsgContent
            }
        })
        console.log('corpUsers', corpUsers)
        setSettings({
            ...settings,
            corpUsers
        })
    }

    return <>
        <div className={`${style.settingsBody_content_row}`}>
            <div className={`${style.settingsBody_content_col}`}>
                <div className={style.title}>
                    <span>高级群发</span>
                </div>
                <div className={style.detail}>
                    <div className={style.detail_title}>高级群发策略配置</div>
                    <div className={style.detail_body}>
                        {settings?.highMassSendingStrategy && Object.keys(settings?.highMassSendingStrategy).length > 0 ? <>
                            <PreviewMassSendingStrategy massSendingStrategy={settings?.highMassSendingStrategy} configType='GROUP_GROUP' />
                        </> : <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}`}>
                <div className={style.title}>
                    <span></span>
                    <Space>
                        {settings?.highMassSendingContent?.massSendingContentDTO?.some(item => item?.sendContentDto?.some(si => si?.contentDTO?.some(i => i?.some(a => ["miniprogram", 'link'].includes(a?.mediaType))))) && <>
                            {settings?.corpUsers?.every(item => item?.externalUserList?.length) && <>
                                <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?.highGroupMsgContent?.length) ? 'Excel内容已上传，重新上传' : '上传Excel'}</Button>
                                </Upload>
                            </>}
                        </>}

                        {((settings?.highMassSendingContent && Object.keys(settings?.highMassSendingContent).length > 0) || (settings?.highMassSendingStrategy && Object.keys(settings?.highMassSendingStrategy).length > 0)) && <Button
                            type="link"
                            danger
                            style={{ padding: 0, fontSize: 12 }}
                            onClick={() => {
                                const corpUsers = settings?.corpUsers?.map(item => {
                                    delete item?.highGroupMsgContent
                                    delete item?.externalUserList
                                    return item
                                })
                                setSettings({
                                    ...settings,
                                    corpUsers,
                                    highMassSendingStrategy: undefined,
                                    highMassSendingContent: undefined
                                })
                                onPreviewReset()
                            }}
                        >清空</Button>}
                    </Space>
                </div>
                <div className={style.detail}>
                    <div className={style.detail_title}>高级群发内容配置</div>
                    <div className={style.detail_body} style={{ padding: 0 }}>
                        {settings?.highMassSendingContent && Object.keys(settings?.highMassSendingContent) ? <>
                            <ShowContent
                                strategySettings={settings?.highMassSendingStrategy?.strategySettings}
                                massSendingContent={settings?.highMassSendingContent}
                                type="highQf"
                            />
                        </> : <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?.highMassSendingStrategy && Object.keys(settings?.highMassSendingStrategy))) {
                                message.error('请先配置策略')
                                return
                            }
                            setNewVisible(true); setCreateType('CONTENT')
                        }}
                    >编辑</Button>
                </div>
            </div>
        </div>

        {/* 模板配置 */}
        {newVisible && <SettingsHighMassSending
            visible={newVisible}
            createType={createType}
            value={{
                highMassSendingContent: settings?.highMassSendingContent,
                highMassSendingStrategy: settings?.highMassSendingStrategy
            }}
            onClose={() => {
                setNewVisible(false)
            }}
            onChange={(values, type) => {
                console.log(values, type)
                const corpUsers = settings?.corpUsers?.map(item => {
                    delete item?.highGroupMsgContent
                    return item
                })
                if (!values?.highMassSendingContent && settings?.corpUsers?.some(item => item?.highGroupMsgContent?.length)) {

                    setSettings({
                        ...settings,
                        ...values,
                        corpUsers
                    })
                } else {
                    setSettings({
                        ...settings,
                        ...values,
                        corpUsers
                    })
                }

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

export default React.memo(HighMassSending);