<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">
          <div>
            <el-form-item label="课题分类：" prop="type" class="custom-align-right">
              <el-select v-model="form.type" placeholder="请选择课题分类..">
                <!-- <el-option label="科研" value="1"></el-option>
                <el-option label="维权" value="2"></el-option> -->
                <el-option :label="item.label" :value="item.value" v-for="item in topicType"></el-option>
              </el-select>
            </el-form-item>  
            <el-form-item label="课题标题：" prop="title" class="custom-align-right">
              <el-input v-model="form.title" autocomplete="off" placeholder="请输入课题标题"></el-input>
            </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="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="is_group" class="custom-align-right">
              <el-radio-group v-model="form.is_group" :disabled="groupStatus">
                <el-radio :label="'1'">是</el-radio>
                <el-radio :label="'0'">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <div>
              <el-form-item label="群聊名称：" prop="group_name" class="custom-align-right" v-if="form.is_group=='1'">
                <el-input v-model="form.group_name" autocomplete="off" placeholder="请输入群聊名称" :disabled="groupStatus"></el-input>
              </el-form-item>
              <el-form-item label="作者：" class="custom-align-right">
                <el-input v-model="form.author" autocomplete="off" placeholder="请输入作者名"></el-input>
              </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);

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 {
      //1.表单项 start ------------------------------------------------------------>
      editStatus:false,//是否为编辑状态
      groupStatus:false,//是否可以编辑群信息
      tableDivTitle:"编辑课题",
      disclaimer:true,//免责声明
      //提交表单
      form: {
        type:"",//课题分类
        title:"",//课题标题
        content:"",//内容
        is_group:"0",//是否创建群聊
        group_name:"",//群聊名称
        author:"",//作者
      },
      topicType:[],//课题分类
      topicStatus:[],//课题状态
      //1.2 表单验证规则
      formRules: {
        title:[{required:true,trigger:'blur',validator:validateEmpty}],
        type:[{required:true,trigger:'blur',validator:validateArray}],
        is_group:[{required:true,trigger:'blur',validator:validateEmpty}],
        group_name:[{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']  // 启用不同的调整方式
          }
        }
      },
      //表单项 end ------------------------------------------------------------>
    };
  },
  methods: {
    //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(){
      //先进行验证
      this.$refs.form.validate(valid => {
        if (valid) {
          //console.log(this.form)
          this.$store.dispatch('chat/addTopic',this.form).then(res=> {
            //汇报结果
            this.$message({
              type: 'success',
              message: '已成功创建商圈！'
            });
            this.cleatForm();
            //返回列表页
            this.returnPage()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //1.3 清理表单
    cleatForm(){
      this.form.type = "";
      this.form.title = "";
      this.form.content = "";
      this.form.is_group = "";
      this.form.group_name = "";
      this.form.author = "";
    },
    //1.4 查询商圈分类
    getTopicType(){
      this.$store.dispatch('chat/topicType',this.getApiData).then(res=> {
        this.topicType = res.data;
        console.log(this.topicType)
      }).catch(() => {
        this.$message.error("查询商圈分类失败！");
      })
    },
    //1.5 查询商圈状态
    getTopicStatus(){
      this.$store.dispatch('chat/topicStatus',this.getApiData).then(res=> {
        this.topicStatus = res.data;
        console.log(res)
      }).catch(() => {
        this.$message.error("查询商圈状态失败！");
      })
    },
    //提交表单 end ------------------------------------------------------------>

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

    //3.回显操作 ------------------------------------------------------------>
    //3.1回显数据
    getMainData() {
      let data = {
        id: this.$route.query.id + ""
      };
      this.$store.dispatch('chat/getTopicInfo', data).then(res => {
        console.log(res);
        this.form.title = res.data.title;
        this.form.type = res.data.type;
        this.form.content = res.data.content;
        this.form.is_group = res.data.is_group;
        this.form.group_name = res.data.group_name;
        this.form.author = res.data.user_name;
        //如果已经创建了群聊，阻止其修改
        if(res.data.is_group=="1"){
          this.groupStatus = true;
        }
      }).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(){
      //添加要修改的id
      this.form.id = this.editId + "";
      //先进行验证
      this.$refs.form.validate(valid => {
        if (valid) {
          //console.log(this.form)
          this.$store.dispatch('chat/updateTopic',this.form).then(res=> {
            //汇报结果
            this.$message({
              type: 'success',
              message: '已成功修改课题信息！'
            });
            this.cleatForm();
            //返回列表页
            this.returnPage()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //跳转操作 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(){
    //查询课题分类
    this.getTopicType();

    this.form.author = this.$store.state.user.name;
    //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;
  }
  //执行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穿透scope选择器 end------------------------------------------------------------>*/
</style>
