<template>
    <!-- 采集咨询 -->
    <div>
        <!--表格内容 start------------------------------------------------------------>
        <div class="layerBox">
            <tableTitle :name="tableDivTitle" />
            <el-row class="formContent">
                <el-checkbox v-model="checked" class="links">引用外链</el-checkbox>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="资讯题目:" prop="title">
                        <el-input v-model="ruleForm.title" placeholder="请输入资讯题目" maxlength="500"
                            show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item v-show="this.checked" label="外链地址:" prop="title">
                        <el-input v-model="ruleForm.url" placeholder="请输入外链地址(即外链网站URL链接)" maxlength="50"
                            show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item label="导航池名称:" prop="name">
                        <el-select v-model="ruleForm.name" disabled placeholder="请选择导航池名称">
                            <el-option label="区域一" value="shanghai"></el-option>
                            <el-option label="区域二" value="beijing"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="推荐等级:" prop="">
                        <el-select v-model="ruleForm.grade" clearable placeholder="请选择推荐等级">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- 缩略图 -->
                    <el-form-item label="缩略图:" prop="" :label-width="formLabelWidth" :class="['custom-form-item']"
                        class="custom-align-right">
                        <div class="uploaderBox">
                            <!--图片上传组件 start ------------------------------------------------------------>
                            <div class="avatar-upload-container" @mouseenter="hovering = true"
                                @mouseleave="hovering = false">
                                <!-- 上传组件 -->
                                <el-upload class="avatar-uploader" action="#" :show-file-list="false"
                                    :before-upload="beforeAvatarUpload">
                                    <!-- 预览图片 -->
                                    <img v-if="logoUrl" :src="logoUrl" class="avatar">
                                    <div v-else class="chooseImgDiv">
                                        <div>
                                            <img src="@/assets/public/upload/noImage.png">
                                            <div>选择图片</div>
                                        </div>
                                    </div>
                                    <input type="hidden" name="logo" v-model="ruleForm.imgSrc">
                                </el-upload>
                                <!-- 删除按钮，当鼠标悬浮时显示 -->
                                <div v-if="hovering && logoUrl" class="delete-button" @click="handleDelete">
                                    <i class="el-icon-delete"></i>
                                </div>
                            </div>
                            <!--图片上传组件 end ------------------------------------------------------------>
                        </div>
                    </el-form-item>
                    <el-form-item label="资讯关键词:" prop="keywords" class="keywords">
                        <el-input v-model="ruleForm.keywords" placeholder="请输入资讯的关键词"></el-input>
                        <el-tooltip class="item" effect="dark"
                            content="  资讯关键词，如：三农市场网,最大的三农市场交易平台—全国三农信息一体化应用平台—中农兴业工程指定网站-农业百强网站。"
                            placement="top-start">
                            <i class="el-icon-warning"></i>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="资讯描述:" prop="desc" class="desc">
                        <el-input type="textarea" v-model="ruleForm.desc" placeholder="请输入资讯的描述..." maxlength="500"
                            resize="none" show-word-limit></el-input>
                        <el-tooltip placement="top-start">
                            <div slot="content">
                                资讯描述，如：2020年,我们取得了脱贫攻坚的伟大胜利,如期全面建成小康社会,未来五年湖南在统筹推进乡村振兴、加快农业农村现代化建设方面有什么样的目标和具体措施?<br />
                                省第十二次党代会代表，省委农村工作领导小组办公室主任，省农业农村厅党组书记、厅长袁延文在党代表通道,三农市场网,最大的三农市场交易平台—全国三农信息一体化应用平台—中农兴业工程指定网站-农业百强网站。
                            </div>
                            <i class="el-icon-warning"></i>
                        </el-tooltip>
                    </el-form-item>
                    <!-- 富文本编辑器配置 -->
                    <div class="QuillTitle">
                        <span>* </span>资讯内容:
                        <div @click="toggleSourceMode" class="QuillModelBtn">
                            {{ showHtml ? '切换到编辑模式' : '切换到源码模式' }}
                        </div>
                    </div>
                    <el-form-item label="">
                        <div class="editor-container">
                            <div v-if="showHtml">
                                <textarea v-model="editorHtml" style="width: 100%; height: 400px;"></textarea>
                            </div>
                            <div v-else>
                                <quill-editor ref="quillEditor" v-model="ruleForm.content" :options="editorOptions"
                                    class="my-quill-editor" />
                            </div>
                            <!-- 多图上传隐藏的input -->
                            <input type="file" ref="multiFileInput" @change="handleMultipleFiles" multiple hidden
                                accept="image/jpeg, image/png" />
                        </div>
                    </el-form-item>
                    <el-form-item label="作者:" prop="author">
                        <el-input v-model="ruleForm.author" placeholder="请输入发布资讯的作者"></el-input>
                    </el-form-item>
                    <el-form-item label="浏览量:" prop="">
                        <el-input-number v-model="ruleForm.count" @change="handleChange" :min="0" :max="100000"
                            :step="1" label="描述文字"></el-input-number>
                    </el-form-item>
                    <el-form-item label="是否原创:" prop="original">
                        <el-radio v-model="ruleForm.original" label="true">是</el-radio>
                        <el-radio v-model="ruleForm.original" label="false">否</el-radio>
                    </el-form-item>
                    <!-- 浏览量 -->

                    <el-form-item v-show="this.ruleForm.original == 'false'" label="来源链接:" prop="link">
                        <el-input v-model="ruleForm.link" placeholder="请输入完整的资讯来源链接。"></el-input>
                    </el-form-item>
                    <el-form-item v-show="this.ruleForm.original == 'false'" label=" 来源:" prop="source">
                        <el-input v-model="ruleForm.source" placeholder="请输入资讯来源，如：XX市农业农村局。"></el-input>
                    </el-form-item>
                    <div class="disclaimerBox" v-show="this.ruleForm.original == 'false'">
                        <div class="disclaimerTitle">
                            <img src="@/assets/public/check.png" />同意《免责声明》：
                            <!-- <el-checkbox v-model="disclaimer" disabled="disabled"></el-checkbox> -->
                        </div>
                        <div class="disclaimerText">
                            本文来源于网络转载，仅供学习交流使用，不构成商业目的。版权归原作者所有，如涉及作品内容、版权和其它问题，请在30日内与本网联系，我们将在第一时间处理。</div>
                    </div>
                </el-form>
            </el-row>
            <div class="btn">
                <button class="cancel" @click="goCancel">取消</button>
                <button class="sure" @click="goSubmit">确定</button>
            </div>
        </div>
        <!--表格内容 end------------------------------------------------------------>

    </div>
</template>

<script>
//表格标题
import tableTitle from './webCrawlerListEdit/tableTitle.vue';
//引入公用样式
import '@/styles/global.less';

import { updateInfo, getOneInfo } from '@/api/crawler'

import { quillEditor } from 'vue-quill-editor';
import 'quill/dist/quill.snow.css';
import ImageResize from 'quill-image-resize-module';
import Quill from 'quill';  // 引入 Quill
import Delta from 'quill-delta'; // 引入 Delta，用于手动修改文档
import { options } from 'dropzone';

// 注册 Image Resize 模块
Quill.register('modules/imageResize', ImageResize);

export default {
    components: {
        quillEditor,
        tableTitle,  //表格标题
    },
    data() {
        return {
            tableDivTitle: "编辑资讯",
            num: 1,
            checked: false,
            iconSrc: '',
            data: '',

            activeid: '',  //当前被选中的id

            formLabelWidth: '', //广告示例图相关

            ruleId: '',
            source: '',

            //3.4 上传logo图片
            logoUrl: '',
            hovering: false, // 鼠标悬浮状态 悬浮时显示删除

            options: [
                {
                    value: 1,
                    label: '头条'
                },
                {
                    value: 2,
                    label: '轮播图'
                },
                {
                    value: 3,
                    label: '推荐图'
                },
                {
                    value: 4,
                    label: '热点资讯'
                },
                {
                    value: 5,
                    label: '资讯推荐'
                },
            ],

            ruleForm: {
                title: '',     // 资讯题目
                url: '',       // 外链地址      
                name: '',      // 导航池名称
                grade: 0,     // 推荐等级
                imgSrc: '',    // 缩略图  
                keywords: '',  // 关键词 
                desc: '',      // 描述
                content: '',   // 内容
                author: '',    // 作者
                count: 0,     // 浏览量
                original: 'false',  // 原创
                source: '',    // 来源
                link: ''       // 来源链接
            },
            rules: {
                title: [
                    { required: true, message: '请输入资讯题目', trigger: 'blur' }
                ],
                url: [
                    { required: true, message: '请输入外链地址', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请选择导航池名称', trigger: 'blur' }
                ],
                grade: [
                    { required: true, message: '请选择推荐等级', trigger: 'blur' }
                ],
                imgSrc: [
                    { required: true, message: '请选择缩略图', trigger: 'blur' }
                ],
                keywords: [
                    { required: true, message: '请输入资讯关键词', trigger: 'blur' }
                ],
                desc: [
                    { required: true, message: '请输入资讯描述', trigger: 'blur' }
                ],
                content: [
                    { required: true, message: '请输入资讯内容', trigger: 'blur' }
                ],
                author: [
                    { required: true, message: '请输入发布资讯的作者', trigger: 'blur' }
                ],
                count: [
                    { required: true, message: '请选择资讯推荐等级', trigger: 'blur' }
                ],
                original: [
                    { required: true, message: '请选择资讯推荐等级', trigger: 'blur' }
                ],
                link: [
                    { required: true, message: '请输入完整的资讯来源链接', trigger: 'blur' }
                ],
                source: [
                    { required: true, message: '请输入资讯来源', trigger: 'blur' }
                ]

            },
            //富文本编辑器配置
            showHtml: false, //用于保存源码内容
            editorHtml: '',
            editorOptions: {
                placeholder: '请输入内容...',
                theme: 'snow',  // 主题样式
                modules: {
                    toolbar: {
                        container: [
                            [{ 'font': [] }],                                // 字体
                            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],       // 标题
                            [{ 'size': ['small', false, 'large', 'huge'] }],  // 字体大小
                            ['bold', 'italic', 'underline', 'strike'],        // 加粗、斜体、下划线、删除线
                            [{ 'color': [] }, { 'background': [] }],          // 文字颜色、背景颜色
                            [{ 'script': 'sub' }, { 'script': 'super' }],     // 上标、下标
                            [{ 'list': 'ordered' }, { 'list': 'bullet' }],     // 列表
                            [{ 'indent': '-1' }, { 'indent': '+1' }],          // 缩进
                            [{ 'align': [] }],                                // 对齐方式
                            ['blockquote', 'code-block'],                     // 引用、代码块
                            ['link', 'image', 'video'],                       // 链接、图片、视频
                            ['clean'],
                            [{ 'html': true }]  // 添加自定义按钮的占位符
                        ],
                        handlers: {
                            image: () => {
                                this.handleImageClick();
                            },
                            showHtml: function () {
                                this.$emit('toggleSourceMode');
                            }
                        }
                    },
                    imageResize: {
                        displayStyles: {
                            backgroundColor: 'black',
                            border: 'none',
                            color: 'white'
                        },
                        modules: ['Resize', 'DisplaySize', 'Toolbar']  // 启用不同的调整方式
                    }
                }
            },
            //1.4图片上传
            imgUrl: "",//在页面上显示缩略图
            //获取父级导航池
            parentKey: 0,//获取父级导航
            parentData: {
                checkStrictly: true,
                lazy: true,
                async lazyLoad(node, resolve) {
                    const { level, data } = node;
                    if (data && data.children && data.children.length !== 0) {
                        return resolve(node)
                    }
                    console.log(level)
                    let parentId = level == 0 ? 0 : data.value
                    let parames = {
                        'pid': parentId
                    }
                    self.$store.dispatch('pool/categoryList', parames).then(res => {
                        if (res.data) {
                            const nodes = res.data.map(item => ({
                                value: item.id,
                                label: item.name,
                                leaf: level >= 3,
                                children: []
                            }))
                            resolve(nodes)
                        }
                    })
                }
            },
        }
    },
    methods: {
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传缩略图只能是 JPG 或 PNG 格式!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('上传缩略图大小不能超过 2MB!');
                return false;
            }

            const formData = new FormData();
            formData.append('file', file);

            this.$store.dispatch('pool/uploadFile', formData).then(res => {
                this.logoUrl = res.data.imgUrl;//显示缩略图
                this.ruleForm.imgSrc = res.data.imgUrl;//提供表单地址
                console.log(res.data.imgUrl)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '网络错误，请重试！'
                });
            })

            // 阻止默认的上传行为
            return false;
        },
        handleDelete() {
            // 删除图片
            this.logoUrl = ''; // 清空图片 URL
        },
        // 提交表单
        goSubmit() {
            if (this.ruleForm.grade == "") {
                updateInfo({
                    art_id: this.activeid,
                    title: this.ruleForm.title,
                    level: 0,
                    imgurl: this.ruleForm.imgSrc,
                    keyword: this.ruleForm.keywords,
                    introduce: this.ruleForm.desc,
                    content: this.ruleForm.content,
                    author: this.ruleForm.author,
                    hits: this.ruleForm.count,
                    is_original: this.ruleForm.original == 'false' ? 0 : 1, //是否原创
                    fromurl: this.ruleForm.link, //来源链接
                    copyfrom: this.ruleForm.source, //来源
                    islink: this.checked == false ? 0 : 1,
                    linkurl: this.ruleForm.url,
                }).then(data => {
                    console.log(data);
                    if (data.code == 200) {
                        this.$message({
                            message: "修改成功",
                            type: "success"
                        })
                        this.$router.push(`/webCrawlerList?id=${this.ruleId}&source=${this.source}`)
                    }
                    if (data.code == 0) {
                        this.$message({
                            message: data.message,
                            type: "error"
                        })
                    }
                })
            } else {
                updateInfo({
                    art_id: this.activeid,
                    title: this.ruleForm.title,
                    level: this.ruleForm.grade,
                    imgurl: this.ruleForm.imgSrc,
                    keyword: this.ruleForm.keywords,
                    introduce: this.ruleForm.desc,
                    content: this.ruleForm.content,
                    author: this.ruleForm.author,
                    hits: this.ruleForm.count,
                    is_original: this.ruleForm.original == 'false' ? 0 : 1, //是否原创
                    fromurl: this.ruleForm.link, //来源链接
                    copyfrom: this.ruleForm.source, //来源
                    islink: this.checked == false ? 0 : 1,
                    linkurl: this.ruleForm.url,
                }).then(data => {
                    console.log(data);
                    if (data.code == 200) {
                        this.$message({
                            message: "修改成功",
                            type: "success"
                        })
                        this.$router.push(`/webCrawlerList?id=${this.ruleId}&source=${this.source}`)
                    }
                    if (data.code == 0) {
                        this.$message({
                            message: data.message,
                            type: "error"
                        })
                    }
                })
            }

        },
        //取消添加或编辑
        goCancel() {
            this.$message({
                message: "已取消修改",
                type: "error"
            })
            this.$router.push(`/webCrawlerList?id=${this.ruleId}&source=${this.source}`)
        },
        //浏览量
        handleChange(value) {
            console.log(value);
            this.ruleForm.count = value
        },

        //4.富文本编辑器 start ------------------------------------------------------------>
        //4.1 编辑器点击上传图片
        handleImageClick() {
            this.$refs.multiFileInput.click(); // 打开文件选择框
        },
        handleMultipleFiles(event) {
            const files = event.target.files;
            if (files.length) {
                this.uploadMultipleImages(files); // 处理多图片上传
            }
        },
        uploadMultipleImages(files) {
            const uploadPromises = [];
            for (let i = 0; i < files.length; i++) {
                uploadPromises.push(this.uploadImage(files[i]));
            }

            Promise.all(uploadPromises).then(urls => {
                const quillEditor = this.$refs.quillEditor.quill;
                urls.forEach(url => {
                    const range = quillEditor.getSelection();
                    quillEditor.insertEmbed(range.index, 'image', url); // 在编辑器中插入图片
                });
            }).catch(error => {
                this.$message.error('图片上传失败，请重试！');
            });
        },
        uploadImage(file) {
            const formData = new FormData();
            formData.append('file', file);
            return this.$store.dispatch('pool/uploadFile', formData)
                .then(res => {
                    if (res && res.data && res.data.imgUrl) {
                        return res.data.imgUrl;
                    } else {
                        throw new Error('图片上传失败');
                    }
                })
                .catch(error => {
                    this.$message.error('图片上传失败，请重试！');
                    throw error;
                });
        },

        //4.2 图片粘贴上传
        // 处理从网页粘贴的图片 URL
        handleImageFromWeb(imageUrl) {
            return new Promise((resolve) => {
                console.log('开始下载图片:', imageUrl);

                this.fetchImageAsBlob(imageUrl).then((blob) => {
                    console.log('图片已下载为 Blob:', blob);

                    const formData = new FormData();
                    formData.append('file', blob, 'image.jpg');

                    this.$store.dispatch('pool/uploadFile', formData).then((res) => {
                        if (res && res.data && res.data.imgUrl) {
                            console.log('图片上传成功:', res.data.imgUrl);
                            resolve(res.data.imgUrl);
                        } else {
                            console.log('图片上传失败，保留原 URL:', imageUrl);
                            resolve(imageUrl);
                        }
                    }).catch((error) => {
                        console.error('图片上传时出现错误:', error);
                        resolve(imageUrl);
                    });
                }).catch((error) => {
                    console.error('图片下载失败:', error);
                    resolve(imageUrl);
                });
            });
        },
        fetchImageAsBlob(url) {
            return fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Failed to fetch image');
                    }
                    return response.blob();
                });
        },
        //编辑源码
        toggleSourceMode() {
            if (!this.showHtml) {
                // 切换到源码模式，将编辑器内容同步到 textarea 中
                this.editorHtml = this.$refs.quillEditor.quill.root.innerHTML;
                this.showHtml = true; // 显示 textarea
            } else {
                // 切换回富文本模式，将 textarea 内容同步回编辑器
                this.showHtml = false; // 显示 Quill 编辑器

                // Quill 编辑器可能被销毁，所以使用 $nextTick 确保 DOM 渲染完成后再操作编辑器
                this.$nextTick(() => {
                    if (this.$refs.quillEditor) {
                        this.$refs.quillEditor.quill.root.innerHTML = this.editorHtml;
                    } else {
                        console.error('Quill 编辑器实例未找到');
                    }
                });
            }
        }
        //富文本编辑器 end ------------------------------------------------------------>
    },
    mounted() {
        this.ruleId = this.$route.query.ruleId
        this.source = this.$route.query.source

        this.activeid = this.$route.query.id
        console.log(this.$route.query.id);


        getOneInfo({
            art_id: this.activeid
        }).then(data => {
            console.log(data);
            this.ruleForm.title = data.data.title
            this.ruleForm.url = data.data.linkurl
            this.ruleForm.name = data.data.category //导航池名称

            //推荐等级
            if (data.data.level == 0) {
                this.ruleForm.grade = ""
            } else {
                this.ruleForm.grade = data.data.level
            }

            this.logoUrl = data.data.imgurl
            this.ruleForm.keywords = data.data.keyword
            this.ruleForm.desc = data.data.introduce
            this.ruleForm.content = data.data.content  //内容
            this.ruleForm.author = data.data.author
            this.ruleForm.count = data.data.hits
            this.ruleForm.source = data.data.copyfrom
            this.ruleForm.link = data.data.fromurl
        })

        //复制内容到富文本 start ------------------------------------------------------------>
        this.$nextTick(() => {
            const quillEditor = this.$refs.quillEditor.quill;

            if (quillEditor) {
                console.log('Quill 编辑器已初始化');

                // 在粘贴事件触发时，记录所有 img 的 src
                quillEditor.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => {
                    if (node.tagName === 'IMG') {
                        const imageUrl = node.getAttribute('src');
                        console.log('检测到粘贴的图片 URL:', imageUrl);

                        if (imageUrl && !imageUrl.startsWith('data:') && !imageUrl.startsWith('file://')) {
                            // 先处理图片上传
                            this.handleImageFromWeb(imageUrl).then((uploadedImageUrl) => {
                                // 查找编辑器中所有 img 标签并替换 src
                                const imgs = quillEditor.root.querySelectorAll('img');
                                imgs.forEach((img) => {
                                    if (img.getAttribute('src') === imageUrl) {
                                        img.setAttribute('src', uploadedImageUrl);  // 替换 src
                                        console.log('图片 src 已替换为:', uploadedImageUrl);
                                    }
                                });
                            });
                        }
                    }
                    return delta;  // 返回原始 delta
                });
            } else {
                console.error('Quill 初始化失败');
            }

        });
        //复制富文本 end ------------------------------------------------------------>
    }
}
</script>

<style scoped lang="less">
p {
    padding: 0;
    margin: 0;
}

//文本编辑器
.QuillTitle {
    line-height: 36px;
    font-size: 14px;
    color: #606266;
    font-weight: bold;
    padding-left: 30px;

    span {
        color: #ff4949
    }

    .QuillModelBtn {
        display: inline-block;
        margin-left: 10px;
        font-size: 12px;
        color: #999;
        cursor: pointer;
    }
}

.editor-container {
    // height: 420px;
    height: 375px;
    padding-bottom: 20px;
    background-color: #fff;
}

.my-quill-editor {
    height: 320px;
}

.ql-editor {
    height: 320px;
}

.layerBox {
    padding: 30px 20px;
    position: relative;

    .listBtnBox {
        justify-content: left;
    }

    // 表单内容
    .formContent {
        background-color: #f5f7fb;
        padding: 30px 225px 0px 25px;
        position: relative;

        // 顶部引用外链
        .links {
            position: absolute;
            top: 37px;
            right: 97px;
        }

        //底部免责声明提示文字
        .tips {
            margin: 0 auto;
            font-size: 13px;
            color: #666666;
        }

        // 图片上传提示文字
        .imgTips {
            color: #8B8D97;
            font-size: 14px;
        }

        // 资讯关键词 和 资讯描述 的 文字提示 
        .keywords,
        .desc {
            position: relative;

            i {
                position: absolute;
                top: 0;
                left: -15px;
            }
        }

        // 文字提示用到的图标的颜色
        .el-icon-warning {
            color: #a9a9a9;
        }

        // input框右下角数字颜色
        ::v-deep .el-input__count {
            color: #999;
        }

        // 多行文本框的高度
        ::v-deep .el-textarea__inner {
            height: 100px;
        }

        // 表单元素的下外边距
        ::v-deep .el-form-item {
            margin-bottom: 50px;
        }

        // 下拉框
        ::v-deep .el-select {
            width: 100%;
            display: inline-block;
            position: relative;
        }

    }

    //按钮
    .btn {
        width: 440px;
        margin: 50px auto 20px;

        button {
            width: 180px;
            height: 58px;
            border-radius: 12px;
            border: none;
            font-size: 20px;
        }

        .cancel {
            color: #333;
            background-color: #f5f7fb;
            border: 2px solid #e3e8fa;
            margin-right: 80px;
        }

        .sure {
            background-color: #5570f1;
            color: #fff;
        }
    }

    //缩略图
    .uploaderBox {
        .avatar {
            width: 140px;
            height: auto;
        }

        .chooseImgDiv {
            background-color: #fff;

            img {
                display: inline-block;
            }
        }
    }

}
</style>