<template>
  <div class="information-container">
    <!-- 添加搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="技术文档位置">
          <el-input
            v-model="queryParams.tech_report_location"
            placeholder="请输入技术文档位置"
            clearable
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="queryParams.department"
            placeholder="请选择部门"
            clearable
          >
            <el-option
              v-for="(item, index) in departList"
              :key="index"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery" type="danger">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="projectList" stripe>
      <el-table-column prop="sequence" label="序号" width="80">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-right: 10px">{{ scope.row.sequence }}</span>
            <i
              class="el-icon-edit"
              @click="handleEdit(scope.row)"
              style="cursor: pointer; margin-left: 5px"
            ></i>
          </div>
        </template>
      </el-table-column>
      <!--       <el-table-column prop="project_name" label="项目名称" /> -->
      <el-table-column prop="name" label="文件名称" />
      <el-table-column prop="tech_report_location" label="技术文档位置" />
      <el-table-column prop="department" label="部门" />
      <el-table-column prop="content" label="内容" width="450">
        <template slot-scope="scope">
          <div class="content-cell">
            <span class="content-text">{{
              getPlainText(scope.row.content)
            }}</span>
            <i
              class="el-icon-edit"
              @click="handleEditContent(scope.row)"
              style="cursor: pointer; margin-left: 5px"
            ></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" sortable />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 添加操作列 -->
      <!--  <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.page_size"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      title="修改序号"
      width="30%"
      append-to-body
      v-el-drag-dialog
    >
      <el-form :model="sequenceForm" label-width="80px">
        <el-form-item label="序号">
          <el-input-number
            v-model="sequenceForm.sequence"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSequence">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加内容编辑弹窗 -->
    <el-dialog
      title="编辑内容"
      :visible.sync="contentDialogVisible"
      :close-on-click-modal="false"
      width="80%"
    >
      <div style="overflow: auto">
        <CanvasEditor
          ref="wordEditor"
          :edit-mode="Modetype"
          :html-data="htmlData"
          :doc-json="docJson"
          :key="keys"
          @save="save"
          @is-save="getSave"
        ></CanvasEditor>
      </div>
      <!--   </el-form-item>
        </el-form> -->
      <div slot="footer">
        <el-button @click="contentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleContentSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import {
  projectList,
  sequence,
  Templatelist,
  TemplateUpdate,
  departments,
  projectTemUpdate,
} from "@/api/knowledge";
import elDragDialog from "@/directive/el-drag-dialog";
import CanvasEditor from "@/components/CanvasEditor/index"; // 确保路径正确
export default {
  components: {
    CanvasEditor, // 使用驼峰式注册
  },
  directives: { elDragDialog },
  name: "Information",
  data() {
    return {
      projectList: [],
      total: 0,
      queryParams: {
        sort_field: "sequence",
        sort_order: "asc",
        page: 1,
        page_size: 10,
        name: "", // 添加名称搜索参数
        tech_report_location: "", // 添加技术文档位置搜索参数
        department: "", // 部门搜索参数
      },
      dialogVisible: false,
      sequenceForm: {
        sequence: 1,
        id: null,
      },
      departList: [],
      /* 编辑内容 */
      contentDialogVisible: false,
      Modetype: "edit",
      htmlData: "", // 编辑器html数据
      docJson: null, // 编辑器getValue数据
      keys: new Date().getTime(), // 给编辑器赋值不刷新的时候，改变key
      contentForm: {
        id: "",
        content: "",
        name: "",
        department: "",
      },
    };
  },
  methods: {
    // 添加 CanvasEditor 相关的方法
    save(data) {
      // 处理保存逻辑
      console.log("保存数据:", data);
      // 这里可以添加具体的保存实现
    },

    getSave(isSaved) {
      // 处理保存状态
      console.log("是否已保存:", isSaved);
      // 这里可以添加保存状态的处理逻辑
    },
    // 修改 handleContentSubmit 方法
    async handleContentSubmit() {
      try {
        // 获取编辑器的最新内容
        const editorContent = this.$refs.wordEditor.editorRef.command.getHTML();

        // 更新 contentForm
        this.contentForm.content = editorContent.main;
        const submitData = {
          ...this.contentForm,
          content: this.contentForm.content, //processContent(this.contentForm.content),
        };
        await projectTemUpdate(submitData);
        this.$message.success("内容更新成功");
        this.contentDialogVisible = false;
        this.getProjectList();
      } catch (error) {
        this.$message.error("内容更新失败");
      }
    },
    // 修改 handleEditContent 方法，添加编辑器数据的处理
    handleEditContent(row) {
      /*  const selectedProject = this.projectOptions.find(
        (p) => p.id === this.selectedProjectId
      ); */

      // 处理 content 内容，将文本格式转换为 HTML 并清理空样式
      const processedContent = this.cleanEmptyStyles(
        this.convertTextToHtml(row.content)
      );

      this.contentForm = {
        id: row.id,
        content: row.content, //processedContent,
      };

      // 设置编辑器数据
      this.htmlData = processedContent;
      this.Modetype = "edit";
      this.keys = new Date().getTime(); // 强制刷新编辑器

      this.contentDialogVisible = true;
    },

    /* 处理文字 */
    getPlainText(html) {
      if (!html) return "";

      // 创建临时 DOM 元素来解析 HTML
      const temp = document.createElement("div");
      temp.innerHTML = html;

      // 获取纯文本内容
      const plainText = temp.textContent || temp.innerText;

      // 截断文本
      return plainText.length > 50
        ? plainText.substring(0, 50) + "..."
        : plainText;
    },
    // 添加辅助方法：清理空样式属性
    cleanEmptyStyles(html) {
      return html
        .replace(/style=""/g, "")
        .replace(/class=""/g, "")
        .replace(/\s+>/g, ">");
    },
    // 修改回显方法，解析样式
    convertTextToHtml(text) {
      if (!text) return "";

      let html = text;

      // 处理表格标记（包含边框样式）
      html = html.replace(
        /\[表格\|style=(.*?)\|class=(.*?)\]([\s\S]*?)(?=\[|$)/g,
        (match, tableStyle, tableClass, tableContent) => {
          const rows = tableContent.trim().split("\n");
          let tableHtml = `<table style="${tableStyle}" class="${tableClass}">`;

          rows.forEach((row) => {
            tableHtml += "<tr>";
            const cells = row.split("|").map((cell) => {
              const cellMatch = cell.match(
                /(.*?)(?:\[style=(.*?)\|class=(.*?)\])?$/
              );
              if (cellMatch) {
                const [_, content, style = "", className = ""] = cellMatch;
                return `<td style="${style}" class="${className}">${content.trim()}</td>`;
              }
              return `<td>${cell.trim()}</td>`;
            });
            tableHtml += cells.join("") + "</tr>";
          });

          tableHtml += "</table>";
          return tableHtml;
        }
      );

      // 2. 处理图片标记（保持不变）
      html = html.replace(
        /\[图片:(.*?)\|style=(.*?)\|class=(.*?)\]/g,
        (match, src, style, className) => {
          return `<img src="${src}" alt="图片" style="${style}" class="${className}">`;
        }
      );

      // 3. 处理文本样式（保持不变）
      html = html.replace(
        /\[文本:(.*?)\|style=(.*?)\|class=(.*?)\]/g,
        (match, content, style, className) => {
          return `<span style="${style}" class="${className}">${content}</span>`;
        }
      );

      // 4. 处理换行
      html = html.replace(/\n/g, "<br>");

      return html;
    },
    async getProjectList() {
      try {
        // 修改请求，添加分页参数
        const response = await Templatelist(this.queryParams);
        this.projectList = response.data.list;
        this.total = response.data.total; // 假设后端返回总数
      } catch (error) {
        console.error("获取项目列表失败：", error);
      }
    },
    // 添加分页处理方法
    handleSizeChange(val) {
      this.queryParams.page_size = val;
      this.getProjectList();
    },
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getProjectList();
    },
    // 获取状态标签类型
    getStatusType(status) {
      const statusMap = {
        5: "success",
        // 可以根据实际状态码添加更多映射
      };
      return statusMap[status] || "info";
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        5: "正常",
        // 可以根据实际状态码添加更多映射
      };
      return statusMap[status] || "未知状态";
    },
    // 添加搜索相关方法
    handleQuery() {
      this.queryParams.page = 1;
      this.getProjectList();
    },
    resetQuery() {
      this.queryParams.name = "";
      this.queryParams.tech_report_location = "";
      this.queryParams.department = "";
      this.handleQuery();
    },
    // 打开编辑序号对话框
    handleEdit(row) {
      this.sequenceForm.sequence = row.sequence;
      this.sequenceForm.id = row.id;
      this.dialogVisible = true;
    },

    // 提交序号修改
    async submitSequence() {
      try {
        await TemplateUpdate({
          id: this.sequenceForm.id,
          new_sequence: this.sequenceForm.sequence,
        });
        this.$message.success("修改序号成功");
        this.dialogVisible = false;
        this.getProjectList(); // 刷新列表
      } catch (error) {
        this.$message.error("修改序号失败：" + error.message);
      }
    },
    init() {
      departments().then((res) => {
        if (res.status !== 200) return;
        this.departList = res.data.departments;
      });
    },
  },
  created() {
    this.getProjectList();
    this.init();
  },
};
</script>
  
  <style lang="scss" scoped>
.information-container {
  padding: 20px;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
}
/* 内容部分样式 */
.content-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .content-text {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 430px; // 可以根据需要调整最大宽度
  }
}
/* 添加以下样式 */
::v-deep .el-dialog {
  margin-top: 0 !important;
}
</style>