<template>
  <div class="mainBox">
    <div class="layerBox">
      <tableTitle :name="tableDivTitle"/>
      <el-form :model="form" ref="form" :rules="formRules" label-position="left" label-width="120px">
        <div class="formDiv">
          <el-form-item label="资讯题目：" prop="title" class="custom-align-right">
            <template #label>
              <span class="askBox">
                资讯题目：
                <!-- <el-tooltip class="item" effect="dark" content="资讯标题，如：三农市场网_网站列表_全国信息一体化网络平台_项目大全。" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip> -->
              </span>
            </template>
            <el-input v-model="form.title" autocomplete="off" placeholder="请输入资讯标题"></el-input>
            <el-checkbox v-model="form.islink">是否使用外链</el-checkbox>
          </el-form-item>
          <div v-if="form.islink==true"> 
            <el-form-item label="导航池名称：" prop="cat_arr_id" class="custom-align-right">
              <el-cascader :key="parentKey" v-model="form.cat_arr_id" placeholder="请选择要绑定的导航池名称" :props="parentData" filterable clearable></el-cascader>
            </el-form-item>
            <el-form-item label="外链地址：" prop="linkurl" class="custom-align-right">
              <el-input v-model="form.linkurl" autocomplete="off" placeholder="请输入外链地址"></el-input>
            </el-form-item>
            <el-form-item label="作者：" prop="author" class="custom-align-right">
              <el-input v-model="form.author" autocomplete="off" placeholder="请输入作者"></el-input>
            </el-form-item>
          </div>
          <div v-if="form.islink==false">
            <el-form-item label="导航池名称：" prop="cat_arr_id" class="custom-align-right">
              <el-cascader :key="parentKey" v-model="form.cat_arr_id" placeholder="请选择要绑定的导航池名称" :props="parentData" filterable clearable></el-cascader>
            </el-form-item>  
            <el-form-item label="推荐等级：" class="custom-align-right" >
              <el-select v-model="form.level" clearable placeholder="请选择推荐等级..">
                <el-option label="头条" :value="1"></el-option>
                <el-option label="轮播图" :value="2"></el-option>
                <el-option label="推荐图" :value="3"></el-option>
                <el-option label="热点资讯" :value="4"></el-option>
                <el-option label="资讯推荐" :value="5"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="缩略图：" class="custom-align-right" prop="imgUrl" v-if="form.level==2||form.level==3">
              <div class="uploaderBox">
                <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload">
                  <!-- <img v-if="imgUrl" :src="imgUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                  <!-- 预览图片 -->
                  <img v-if="imgUrl" :src="imgUrl" class="avatar">
                  <!-- 上传图标 -->
                  <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                  <div v-else class="chooseImgDiv">
                    <div>
                      <img src="@/assets/public/upload/noImage.png">
                      <div>选择图片</div>
                    </div>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item label="缩略图：" class="custom-align-right" v-else>
              <div class="uploaderBox">
                <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload">
                  <!-- <img v-if="imgUrl" :src="imgUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                  <!-- 预览图片 -->
                  <img v-if="imgUrl" :src="imgUrl" class="avatar">
                  <!-- 上传图标 -->
                  <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                  <div v-else class="chooseImgDiv">
                    <div>
                      <img src="@/assets/public/upload/noImage.png">
                      <div>选择图片</div>
                    </div>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item label="资讯关键词：" prop="keyword" class="custom-align-right">
              <template #label>
                <span class="askBox">
                  资讯关键词：
                  <el-tooltip class="item" effect="dark" content="资讯关键词，如：三农市场网、全国三农、信息一体化。" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.keyword" autocomplete="off" placeholder="请输入资讯关键词"></el-input>
            </el-form-item>
            <el-form-item label="资讯描述：" prop="introduce" class="custom-align-right">
              <template #label>
                <span class="askBox">
                  资讯描述：
                  <el-tooltip class="item" effect="dark" content="资讯描述，如：中国三农市场网创建以来，社会效益和会员经济效益贡献。" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
              </template>
              <el-input type="textarea" v-model="form.introduce" class="custom-textarea" placeholder="请输入资讯描述"></el-input>
            </el-form-item>
            <div class="QuillTitle">
              <span>* </span>资讯内容：
              <div @click="toggleSourceMode" class="QuillModelBtn">
                {{ showHtml ? '切换到编辑模式' : '切换到源码模式' }}
              </div>
            </div>
            <el-form-item label="" prop="content">
              <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="form.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" class="custom-align-right">
              <el-input v-model="form.author" autocomplete="off" placeholder="请输入作者"></el-input>
            </el-form-item>
            <el-form-item label="浏览量：" class="custom-align-right">
              <el-input v-model="form.hits" autocomplete="off" placeholder="请输入浏览量"></el-input>
            </el-form-item>
            <el-form-item label="是否为原创：" prop="is_original" class="custom-align-right">
              <el-radio-group v-model="form.is_original" @change="changeIsOriginal">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-if="form.is_original==0">
              <el-form-item label="来源名称：" prop="copyfrom" class="custom-align-right">
                <el-input v-model="form.copyfrom" autocomplete="off" placeholder="请输入来源名称"></el-input>
              </el-form-item>
              <el-form-item label="来源链接：" prop="fromurl" class="custom-align-right">
                <el-input v-model="form.fromurl" autocomplete="off" placeholder="请输入来源链接"></el-input>
              </el-form-item>
              <div class="disclaimerBox">
                <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>
            </div>
            <div v-if="form.is_original==1">
              <el-form-item label="来源名称：" prop="copyfrom" class="custom-align-right">
                <el-input v-model="form.copyfrom" autocomplete="off" placeholder="请输入来源名称" disabled="disabled"></el-input>
              </el-form-item>
            </div>

            <el-form-item label="资讯状态：" class="custom-align-right" style="width: 100%;">
              <el-select v-model="form.status" placeholder="请选择..">
                <el-option label="已发布" :value="1"></el-option>
                <el-option label="待发布" :value="0"></el-option>
              </el-select>
            </el-form-item>
           
            <el-form-item label="是否开启投票：" prop="is_survey" class="custom-align-right">
              <el-radio-group v-model="form.is_survey" >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-if="form.is_survey==1">
            <el-form-item label="问卷标题：" prop="survey_name" class="custom-align-right">
              <el-input v-model="form.survey_name" autocomplete="off" placeholder="请输入问卷标题"></el-input>
            </el-form-item>
            <el-form-item label="选项：" prop="is_survey" class="custom-align-right">
              <el-radio-group v-model="form.survey_type" >
                <el-radio :label="0">单选</el-radio>
                <el-radio :label="1">多选</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label=""   class="custom-align-right">
              <div v-for="(input, index) in inputList" :key="index">
                 <div class="formLabelFloatBox">
                  <el-input autocomplete="off" v-model="input.value" maxlength="150" :label-width="formLabelWidth"  placeholder="">  <template slot="prepend">{{ index+1 }}</template></el-input>
                  <el-button type="info" icon="el-icon-plus" circle size="mini" @click="addInput(index)" class="formLabeladdIcon"></el-button>
                  <el-button type="info" icon="el-icon-delete" circle size="mini" @click="deleteInput(index)"  class="formLabelDelIcon"></el-button>
                </div>  
            </div>
          </el-form-item>
          <el-form-item label=""  class="custom-align-right">
                <el-checkbox v-model="checked">允许用户自己填写</el-checkbox>
            </el-form-item>
          </div>
          </div>
        </div>
      </el-form>
    </div>
    <div class="bottomBtnBox">
      <el-button type="info" @click="returnPage">返回</el-button>
      <el-button type="primary" @click="editToServe" v-if="editStatus==true">确定</el-button>
      <el-button type="primary" @click="addToServe" v-else>发布资讯</el-button>
    </div>
  </div>
</template>

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

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，用于手动修改文档

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

//解决富文本样式居中不显示
import 'quill/dist/quill.core.css';

export default {
  components: {
    quillEditor,
    tableTitle
  },
  data() {
    
    //0.全局操作 start ------------------------------------------------------------>
    //表单验证
    const validateEmpty = (rule,value,callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    const validateArray = (rule,value,callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    let self = this;
    //0.全局操作 end ------------------------------------------------------------>
    return {
      radio:3,
      checked:false,
      formLabelWidth: '80px',//表单的长度
      //1.表单项 start ------------------------------------------------------------>
      editStatus:false,
      tableDivTitle:"添加资讯",
      disclaimer:true,//免责声明
      //提交表单
      form: {
        //1.1使用了外链
        title: '',//资讯标题
        islink:0,//是否使用外链 0非 1是
        linkurl:"",//外链地址
        //1.2没有使用外链
        cat_arr_id:'',//导航池名称
        level:"",//推荐等级
        imgurl:"",//缩略图
        keyword:"",//关键词
        introduce:"",//描述
        content:"",//内容
        author:"",//作者
        hits:"",//浏览量
        is_original:0,//是否为原创 0非 1是
        copyfrom:"",//来源名称
        fromurl:"",//来源地址
        status:0,//状态 0待发布 1已发布 404已删除
        is_survey:1,//调查问卷：0：否；1：是；
        survey_name:"",//问卷名称
        suvey_array:"",//选项名称集合 
        survey_type:"0" //0:单选 1：复选
      },
      //1.2 表单验证规则
      formRules: {
        //资讯名称不能为空
        title:[{required:true,trigger:'blur',validator:validateEmpty}],
        //如果使用了外链，外链地址不能为空
        linkurl:[{required:true,trigger:'blur',validator:validateEmpty}],
        //导航池名称不能为空
        cat_arr_id:[{required:true,trigger:'blur',validator:validateArray}],
        //推荐等级不能为空
        //level:[{required:true,trigger:'blur',validator:validateEmpty}],
        //关键词不能为空
        keyword:[{required:true,trigger:'blur',validator:validateEmpty}],
        //描述不能为空
        introduce:[{required:true,trigger:'blur',validator:validateEmpty}],
        //内容不能为空
        content:[{required:true,trigger:'blur',validator:validateEmpty}],
        //作者不能为空
        author:[{required:true,trigger:'blur',validator:validateEmpty}],
        //是否原创不能为空
        is_original:[{required:true,trigger:'blur',validator:validateEmpty}],
        //来源名称和地址不能为空
        copyfrom:[{required:true,trigger:'blur',validator:validateEmpty}],
        fromurl:[{required:true,trigger:'blur',validator:validateEmpty}],
        //缩略图不能为空
        imgUrl:[{required:true,trigger:'blur',validator:validateEmpty}],
        level:[{required:true,trigger:'blur',validator:validateEmpty}],
        //是否开启投票
        is_survey:[{required:true,trigger:'blur',validator:validateEmpty}],
        //问卷标题
        survey_name:[{required:true,trigger:'blur',validator:validateEmpty}],
        //选项
        survey_type:[{required:true,trigger:'blur',validator:validateEmpty}],
      },
      //1.3富文本编辑器配置
      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)
            }
          })
        }
      },
      inputList: [
        { value: '' }
      ]
      //表单项 end ------------------------------------------------------------>
    };
  },
  methods: {
    //---------------------------
    addInput(index) {
      // 在当前索引后插入一个新的输入框对象
      if(this.inputList.length>10){
         this.$message.warning('最多只能添加10个文本框');
         return false;
      }
      this.inputList.splice(index + 1, 0, { value: '' });
    },
    deleteInput(index) {
      if (this.inputList.length > 1) {
        // 如果输入框数量大于 1，则删除当前索引对应的输入框对象
        this.inputList.splice(index, 1);
      } else {
        this.$message.warning('至少保留一个输入框');
      }
    },
    //1.提交表单 start ------------------------------------------------------------>
    //1.1 直接上传图片
    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.imgUrl = res.data.imgUrl;//显示缩略图
        this.form.imgurl = res.data.imgUrl;//提供表单地址
        console.log(res.data.imgUrl)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })

      // 阻止默认的上传行为
      return false;
    },
    //1.2 提交表单
    addToServe(){
      if(this.form.is_survey==1){
        const hasEmptyInput = this.inputList.some(input => input.value === '');
        if (hasEmptyInput) {
          // 如果有输入框为空，弹出提示信息
          this.$message.error('请确保所有输入框都有内容');
          return;
        }
        const inputLists = this.inputList.map(input => input.value);
        const allowList = [this.checked?1:0,""];
        if(this.checked){
          inputLists.push(allowList);
        }
        if(inputLists.length<3){
          this.$message.error('投票答案必须大于2条');
          return;
        }
        this.form.suvey_array = JSON.stringify(inputLists);
      }
      // console.log('提交的数据:', this.inputList.map(input => input.value));
      // this.form.suvey_array
      // return false;
      //提交之前先判断是否为外链
      //如果使用了外链，清理掉除了外链以外的内容
      if(this.form.islink==true){
        this.form.islink = 1;
        this.cleatForm(1)
      }else{
        this.form.islink = 0;
      }
      //如果推荐等级为空，则设置为0
      if(this.form.level==""){
        this.form.level = 0;
      }
      //先进行验证
      this.$refs.form.validate(valid => {
        if (valid) {
          //console.log(this.form)
          this.$store.dispatch('news/addArticle',this.form).then(res=> {
            if(res.code==200){
              //汇报结果
              this.$message({
                type: 'success',
                message: '已成功添加资讯！'
              });
              this.cleatForm(2);
              //返回列表页
              this.returnPage()
            }else{
              this.$message({
                type: 'error',
                message: "资讯发布失败，请稍后再试！"
              });
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //1.3 清理表单
    cleatForm(type){
      if(type==1){
        //使用了外链，进行部分表单清理
        //this.form.cat_arr_id = "";
        this.form.level = "";
        this.form.imgurl = "";
        this.form.keyword = "";
        this.form.introduce = "";
        this.form.content = "";
        //this.form.author = "";
        this.form.hits = "";
        this.form.is_original = "";
        this.form.copyfrom = "";
        this.form.fromurl = "";
        this.form.status = "";
      }
      if(type==2){
        //完全清理表单
        this.form.title = "";
        this.form.islink = "";
        this.form.linkurl = "";
        this.form.cat_arr_id = "";
        this.form.level = "";
        this.form.imgurl = "";
        this.form.keyword = "";
        this.form.introduce = "";
        this.form.content = "";
        this.form.author = "";
        this.form.hits = "";
        this.form.is_original = "";
        this.form.copyfrom = "";
        this.form.fromurl = "";
        this.form.status = "";
      }
    },
    //提交表单 end ------------------------------------------------------------>

    //2.跳转操作 start ------------------------------------------------------------>
    returnPage(){
      this.$router.push({
        path: '/articleList',
      });
    },
    //跳转操作 end ------------------------------------------------------------>

    //3.回显操作 ------------------------------------------------------------>
    //3.1回显数据
    getMainData() {
      let data = {
        id: this.$route.query.id
      };
      this.$store.dispatch('news/getArticleInfo', data).then(res => {
        console.log(res);
        this.form.title = res.data.title;
        //判断是否使用了外链
        if(res.data.islink==1){
          this.form.islink = true;
        }else{  
          this.form.islink = false;
        }

        //不是原创的时候显示来源
        if(res.data.is_original==1){
          this.form.is_original = 1;
          this.form.copyfrom = "本网";
        }else{
          this.form.is_original = 0;
          this.$nextTick(() => {
            this.form.is_original = 0;
            console.log('is_original:', this.form.is_original); // 确保值已更新
          });
          this.form.copyfrom = res.data.copyfrom;
          this.form.linkurl = res.data.linkurl;
        }
        
        // 回显导航池
        this.form.cat_arr_id = Array.isArray(res.data.cat_arr_id) ? res.data.cat_arr_id : JSON.parse(res.data.cat_arr_id);
        this.parentKey += 1; // 触发级联选择器重新加载
        this.loadCascaderPath(this.form.cat_arr_id); // 加载路径数据
        //回显推荐等级
        if(res.data.level==0){
          this.form.level = "";
        }else{
          this.form.level = res.data.level;
        }
        this.form.imgurl = res.data.imgurl;
        this.imgUrl = res.data.imgurl;
        this.form.keyword = res.data.keyword;
        this.form.introduce = res.data.introduce;
        this.form.content = res.data.content;
        this.form.author = res.data.author;
        this.form.hits = res.data.hits;
        this.form.is_original = res.data.is_original;
        //this.form.copyfrom = res.data.copyfrom;
        this.form.fromurl = res.data.fromurl;
        this.form.status = res.data.status;
        this.form.survey_name = res.data.survey_name;
        this.form.is_survey = res.data.is_survey;
        this.form.survey_type = res.data.survey_type;
        this.inputList = [];
        if(res.data.survey_array.length>0){
          res.data.survey_array.forEach(item => {
            if(item.is_other==0){
              this.inputList.push({"value":item.choice_name});
            }else{
              this.checked = true
            }
          
          });
        }else{
          this.inputList.push({"value":""});
        }
        console.log( this.inputList)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      });
    },
    async loadCascaderPath(path) {
      for (let i = 0; i < path.length; i++) {
        const parentId = path[i - 1] || 0; // 获取当前层级的父级ID
        const level = i; // 当前层级的索引

        await this.$store.dispatch('pool/categoryList', { pid: parentId })
          .then((res) => {
            const nodes = res.data.map(item => ({
              value: item.id,
              label: item.name,
              leaf: level >= 3, // 假设4层结构，设置叶子节点标记
            }));

            // 级联选择器加载数据
            if (level === path.length - 1) {
              this.form.cat_arr_id = path; // 确保最后一级路径正确设置
              this.parentKey += 1; // 强制刷新 cascader
            }
          });
      }
    },
    //1.3提交修改
    editToServe(){
      //提交之前先判断是否为外链
      //如果使用了外链，清理掉除了外链以外的内容
      if(this.form.is_survey==1){
        const hasEmptyInput = this.inputList.some(input => input.value === '');
        if (hasEmptyInput) {
          // 如果有输入框为空，弹出提示信息
          this.$message.error('请确保所有输入框都有内容');
          return;
        }
        const inputLists = this.inputList.map(input => input.value);
        const allowList = [this.checked?1:0,""];
        if(this.checked){
          inputLists.push(allowList);
        }
        if(inputLists.length<3){
          this.$message.error('投票答案必须大于2条');
          return;
        }
        this.form.suvey_array = JSON.stringify(inputLists);
      }
    
      console.log(this.form)
      if(this.form.islink==1){
        this.cleatForm(1)
      }
      //如果推荐等级为空，则设置为0
      if(this.form.level==""){
        this.form.level = 0;
      }
      //添加要修改的id
      this.form.id = this.editId;
      //先进行验证
      this.$refs.form.validate(valid => {
        if (valid) {
          //console.log(this.form)
          this.$store.dispatch('news/updateArticle',this.form).then(res=> {
            if(res.code!=200){
              this.$message.error("修改失败，请稍后再试！");
            }else{
              //汇报结果
              this.$message({
                type: 'success',
                message: '已成功编辑资讯！'
              });
              this.cleatForm(2);
              //返回列表页
              this.returnPage()
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //1.4 修改是否原创
    changeIsOriginal(){
      if(this.form.is_original==1){
        this.form.copyfrom = "本网";
      }else{
        this.form.copyfrom = "";
        this.form.fromurl = "";
      }
    },
    //跳转操作 end ------------------------------------------------------------>

    //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(){
    //1.判断是新建还是回显
    if(this.$route.query.id!=undefined){
      this.editId = this.$route.query.id;
      this.editStatus = true;
      console.log("编辑新闻！")
      this.getMainData();
    }else{
      this.editStatus = false;
      console.log("添加新闻！")
    }

    //复制内容到富文本 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">
  //文本编辑器
  .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;
    padding-bottom:20px;
  }
  .my-quill-editor {
    height: 320px;
  }
  .ql-editor {
    height: 320px;
  }

  /* 富文本对齐方式 */
	.ql-align-center{
    text-align: center;
  }
  .ql-align-right{
    text-align: right;
  }
  .ql-indent-1{
    padding-left: 16px;
  }
  .ql-indent-2{
    padding-left: 32px;
  }
  .ql-indent-3{
    padding-left: 48px;
  }
  .ql-indent-4{
    padding-left: 64px;
  }
  .ql-indent-5{
    padding-left: 80px;
  }
  .ql-indent-6{
    padding-left: 96px;
  }
  .ql-indent-7{
    padding-left: 112px;
  }
  .ql-indent-8{
    padding-left: 128px;
  }


  //执行v-deep穿透scope选择器 start------------------------------------------------------------>*/
  ::v-deep .custom-form-item > .el-form-item__label {
    line-height: 140px !important;
  }
  ::v-deep .custom-textarea .el-textarea__inner {
    resize: none; /* 禁止用户拖拽调整大小 */
  }
  ::v-deep .custom-align-right .el-form-item__label {
    text-align: right; /* 设置标签文字右对齐 */
  }
  ::v-deep .el-select {
    width: 100%; /* 禁止用户拖拽调整大小 */
  }
  ::v-deep .el-input-group__prepend {
    color: black !important;
  }
  .formLabelFloatBox {
    margin-bottom: 10px;
    position: relative;
    .formLabeladdIcon {
      position: absolute;
      right:45px;
      top:5px;
      width:38px;
      height:24px;
    }
    .formLabelDelIcon {
      position: absolute;
      right:5px;
      top:5px;
      width:38px;
      height:24px;
    }
  }
  //执行v-deep穿透scope选择器 end------------------------------------------------------------>*/
</style>
