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 { 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 { cutByBytes, groupBy, readFileAsBuffer } from '@/utils/utils';
import { saveAs } from 'file-saver';
import SettingsFriends from './settingsFriends';
import PreviewFriendsStrategy from './previewFriendsStrategy';
import ShowFriendsContent from './showFriendsContent';

const Friends: 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 mergeCells = [];
        // 解放填写限制区域
        const unLockArea = [];

        let dataRow = 0
        // 数据内容
        settings?.corpUsers?.forEach((item, i) => {
            let strategyIndex = 0

            settings?.friendsStrategy?.strategySettings?.forEach((strategyItem, index) => {
                const friendsContentDTO = settings?.friendsContent?.friendsContentDTO?.[index]
                const startRow = 2 + dataRow
                const endRow = startRow + (friendsContentDTO?.contentDTO?.length || 0) - 1
                mergeCells.push({
                    startRow,
                    startColumn: 3,
                    endRow,
                    endColumn: 3,
                })
                mergeCells.push({
                    startRow,
                    startColumn: 4,
                    endRow,
                    endColumn: 4,
                })
                friendsContentDTO.contentDTO.forEach((contentItem, contentIndex) => {
                    strategyIndex++;
                    let linkPlaceholder = '<空>'
                    let miniprogramPlaceholder = '<空>'

                    const mediaItem = JSON.parse(JSON.stringify(contentItem?.attachmentList || []))
                    if (contentItem?.text?.content) {
                        mediaItem.push({
                            mediaType: 'text',
                            textContent: contentItem?.text?.content
                        })
                    }

                    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: `(内容${contentIndex + 1})\n` },
                            ...contentRichText
                        ]
                    }
                    dataRow++;

                    if (linkPlaceholder !== '<空>') {
                        unLockArea.push(`${dataRow}_6`)
                    }
                    if (miniprogramPlaceholder !== '<空>') {
                        unLockArea.push(`${dataRow}_7`, `${dataRow}_8`)
                    }

                    worksheet.addRow([
                        // 账号
                        `${item.name}（ID：${item.corpUserId}）`,
                        // 朋友圈标题
                        `${settings?.friendsStrategy?.momentSendName}`,
                        // 策略信息
                        {
                            richText: [
                                { text: `(策略${index + 1})\n`, font: { bold: true } },
                                { text: `名称：${strategyItem?.strategyName || '<空>'}\n` },
                                {
                                    text: (`执行类型：${TIME_TYPE[strategyItem?.timeRepeatType]}\n`) +
                                        (strategyItem?.sendDay ? `执行时间：${strategyItem?.sendDay}\n` : '') +
                                        (strategyItem?.startTime ? `执行日期：${strategyItem?.startTime}~${strategyItem?.endTime ? strategyItem?.endTime : '长期执行'}\n` : '') +
                                        (strategyItem?.sendTime ? '执行时间：' + strategyItem?.sendTime + '\n' : '') +
                                        (strategyItem?.repeatArray ? `执行天数：${strategyItem?.repeatArray.join('、')}\n` : '')
                                }
                            ]
                        },
                        // 发送对象
                        {
                            richText: [
                                { text: `发送对象：${item?.friendsTagContent?.length > 0 ? cutByBytes(item?.friendsTagContent?.map(i => i.title).join('、'), 160) : '全部'}\n`, font: { bold: true } },
                                { text: `发送模式：${welcomeContentData?.find(i => i.value === friendsContentDTO?.sendMode)?.label}\n` },
                            ]
                        },
                        // 群发内容
                        richText,
                        // 图文链接
                        linkPlaceholder,
                        // 小程序APPID
                        miniprogramPlaceholder,
                        // 小程序路径
                        miniprogramPlaceholder
                    ])

                    worksheet.getRow(dataRow + headerRowIndex).height = 100; // 设置行高
                    worksheet.getRow(dataRow + headerRowIndex).alignment = {
                        vertical: 'middle',
                        wrapText: true
                    }
                    // 分组设置背景色
                    if (i % 2 === 0) {
                        worksheet.getRow(dataRow + headerRowIndex).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(dataRow + headerRowIndex).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' } }
                                }
                            }
                        })
                    }
                })
            })

            const startRow = 2 + (i * strategyIndex)
            const endRow = startRow + strategyIndex - 1
            mergeCells.push({
                startRow,
                startColumn: 1,
                endRow,
                endColumn: 1,
            })
            mergeCells.push({
                startRow,
                startColumn: 2,
                endRow,
                endColumn: 2,
            })
        })
        console.log('mergeCells--->', mergeCells)
        // 合并单元格
        mergeCells.forEach(({ startRow, startColumn, endRow, endColumn }) => {
            worksheet.mergeCells(startRow, startColumn, endRow, endColumn); // 合并单元格
        })

        // 设置可填写区域
        for (let rowNum = 1; rowNum <= dataRow; 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
        }

        if (settings?.corpUsers?.reduce((pre) => pre + settings?.friendsStrategy?.strategySettings.reduce((sPre, _, index) => sPre + settings?.friendsContent?.friendsContentDTO?.[index]?.contentDTO?.length, 0), 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;
        }, {});
        // console.log('读取的Excel数据', data, groupData)

        const corpUsers = settings?.corpUsers?.map(item => {
            const friendsMsgContent = []
            groupData[item.corpUserId]?.forEach((i: any) => {
                const strategyIndex = i.col3.richText[0].text.split('(策略')[1]?.split(')')[0]
                const contentIndex = i.col5.richText[0].text.split('(内容')[1]?.split(')')[0]
                const layer1 = strategyIndex - 1;
                if (!friendsMsgContent[layer1]) friendsMsgContent[layer1] = [];
                friendsMsgContent[strategyIndex - 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()
                }
            })
            return {
                ...item,
                friendsMsgContent
            }
        })
        // 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?.friendsStrategy && Object.keys(settings?.friendsStrategy).length > 0 ? <>
                            <PreviewFriendsStrategy friendsStrategy={settings?.friendsStrategy} />
                        </> : <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>
                    {(settings?.friendsStrategy && Object.keys(settings?.friendsStrategy).length > 0) && <Space>
                        {settings?.friendsContent?.friendsContentDTO?.some(item => item?.contentDTO?.some(i => i?.attachmentList?.some(a => ['link', 'miniprogram'].includes(a?.mediaType)))) && <>
                            <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?.friendsMsgContent?.length) ? 'Excel内容已上传，重新上传' : '上传Excel'}</Button>
                            </Upload>
                        </>}
                        <Button
                            type="link"
                            danger
                            style={{ padding: 0, fontSize: 12 }}
                            onClick={() => {
                                const corpUsers = settings?.corpUsers?.map(item => {
                                    delete item?.friendsTagContent
                                    delete item?.friendsMsgContent
                                    return item
                                })
                                setSettings({
                                    ...settings,
                                    corpUsers,
                                    friendsStrategy: undefined,
                                    friendsContent: undefined
                                })
                                onPreviewReset()
                            }}
                        >清空</Button>
                    </Space>}
                </div>
                <div className={style.detail}>
                    <div className={style.detail_title}>朋友圈内容配置</div>
                    <div className={style.detail_body} style={{ padding: 0 }}>
                        {settings?.friendsContent && Object.keys(settings?.friendsContent) ? <>
                            <ShowFriendsContent
                                strategySettings={settings?.friendsStrategy?.strategySettings}
                                friendsContent={settings?.friendsContent}
                            />
                        </> : <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?.friendsStrategy && Object.keys(settings?.friendsStrategy).length)) {
                                message.error('请先配置策略')
                                return
                            }
                            setNewVisible(true); setCreateType('CONTENT')
                        }}
                    >编辑</Button>
                </div>
            </div>
        </div>

        {/* 模板配置 */}
        {newVisible && <SettingsFriends
            visible={newVisible}
            createType={createType}
            value={{
                friendsContent: settings?.friendsContent,
                friendsStrategy: settings?.friendsStrategy
            }}
            onClose={() => {
                setNewVisible(false)
            }}
            onChange={(values, type) => {
                if (!values?.friendsContent && settings?.corpUsers?.some(item => item?.friendsTagContent?.length)) {
                    setSettings({
                        ...settings,
                        ...values,
                    })
                } else {
                    setSettings({
                        ...settings,
                        ...values,
                    })
                }

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

export default Friends;