<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="知识库名称" prop="knowledgeName">
        <el-input
          v-model="queryParams.knowledgeName"
          placeholder="请输入知识库名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="知识库状态" clearable style="width: 240px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['flood:knowledge:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['flood:knowledge:add']"
        >导入知识库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['flood:knowledge:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['flood:knowledge:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="knowledgeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="知识库ID" align="center" prop="knowledgeId" width="100" />
      <el-table-column label="知识库名称" align="center" prop="knowledgeName" :show-overflow-tooltip="true" />
      <el-table-column label="知识库描述" align="center" prop="knowledgeDesc" :show-overflow-tooltip="true" />
      <el-table-column label="文件数量" align="center" prop="fileCount" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['flood:knowledge:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['flood:knowledge:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['flood:knowledge:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改洪水知识库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="知识库名称" prop="knowledgeName">
          <el-input v-model="form.knowledgeName" placeholder="请输入知识库名称" />
        </el-form-item>
        <el-form-item label="知识库描述" prop="knowledgeDesc">
          <el-input v-model="form.knowledgeDesc" type="textarea" placeholder="请输入知识库描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入知识库对话框 -->
    <el-dialog title="导入知识库" :visible.sync="importOpen" width="600px" append-to-body>
      <el-form ref="importForm" :model="importForm" :rules="importRules" label-width="120px">
        <el-form-item label="知识库名称" prop="knowledgeName">
          <el-input v-model="importForm.knowledgeName" placeholder="请输入知识库名称（将使用目录名作为默认名称）" />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            提示：如果不填写，将使用选择的目录名作为知识库名称
          </div>
        </el-form-item>
        <el-form-item label="知识库描述" prop="knowledgeDesc">
          <el-input v-model="importForm.knowledgeDesc" type="textarea" :rows="3" placeholder="请输入知识库描述（可选）" />
        </el-form-item>
        <el-form-item label="选择目录">
          <div style="display: flex; align-items: center; gap: 10px;">
            <input
              ref="directoryInput"
              type="file"
              webkitdirectory
              directory
              multiple
              style="display: none"
              @change="handleDirectoryInputChange"
            />
            <el-button
              size="small"
              type="primary"
              @click="triggerDirectorySelect"
            >选择目录</el-button>
            <span v-if="importForm.fileCount > 0" style="color: #67C23A; font-size: 14px;">
              ✓ 已选择目录，共 {{ importForm.fileCount }} 个文件
            </span>
            <el-button
              v-if="importForm.fileList && importForm.fileList.length > 0"
              size="small"
              type="text"
              @click="clearDirectorySelection"
            >清除</el-button>
          </div>
          <div slot="tip" class="el-upload__tip" style="color: #909399; font-size: 12px; margin-top: 10px;">
            请选择一个目录，系统将上传该目录下的所有文件（支持图片、PDF、Word、PPT等格式）
          </div>
          <div v-if="importForm.fileList && importForm.fileList.length > 0" style="margin-top: 10px;">
            <el-alert
              :title="`已选择目录，共 ${importForm.fileCount} 个文件`"
              type="success"
              :closable="false"
              show-icon
            />
            <div style="max-height: 200px; overflow-y: auto; margin-top: 10px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
              <div v-for="(file, index) in importForm.fileList.slice(0, 20)" :key="index" style="font-size: 12px; color: #606266; margin-bottom: 5px;">
                {{ file.name || (file instanceof File ? file.name : '未知文件') }}
              </div>
              <div v-if="importForm.fileList.length > 20" style="font-size: 12px; color: #909399; margin-top: 5px;">
                还有 {{ importForm.fileList.length - 20 }} 个文件...
              </div>
            </div>
          </div>
          <div v-else style="margin-top: 10px;">
            <el-alert
              title="请选择一个包含文件的目录"
              type="warning"
              :closable="false"
              show-icon
            />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport" :loading="importUploading">开始导入</el-button>
        <el-button @click="cancelImport">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listKnowledge, getKnowledge, delKnowledge, addKnowledge, updateKnowledge } from "@/api/flood/knowledge";
import request from "@/utils/request";
import { getToken } from "@/utils/auth";

export default {
  name: "FloodKnowledge",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 洪水知识库表格数据
      knowledgeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        knowledgeName: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        knowledgeName: [
          { required: true, message: "知识库名称不能为空", trigger: "blur" }
        ]
      },
      // 导入知识库相关
      importOpen: false,
      importUploading: false,
      importForm: {
        knowledgeName: '',
        knowledgeDesc: '',
        fileList: [], // 原始File对象数组
        fileCount: 0,
        uploadedFiles: [] // 已上传的文件信息数组
      },
      importRules: {
        knowledgeName: [
          { required: true, message: "知识库名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询洪水知识库列表 */
    getList() {
      this.loading = true;
      listKnowledge(this.queryParams).then(response => {
        this.knowledgeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        knowledgeId: null,
        knowledgeName: null,
        knowledgeDesc: null,
        fileCount: 0,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.knowledgeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加洪水知识库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const knowledgeId = row.knowledgeId || this.ids[0]
      getKnowledge(knowledgeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改洪水知识库";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.$router.push({
        path: '/flood/knowledge/detail',
        query: { knowledgeId: row.knowledgeId }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.knowledgeId != null) {
            updateKnowledge(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addKnowledge(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const knowledgeIds = row.knowledgeId || this.ids;
      this.$modal.confirm('是否确认删除知识库编号为"' + knowledgeIds + '"的数据项？').then(function() {
        return delKnowledge(knowledgeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入知识库按钮操作 */
    handleImport() {
      this.importOpen = true;
      this.resetImportForm();
    },
    /** 重置导入表单 */
    resetImportForm() {
      this.importForm = {
        knowledgeName: '',
        knowledgeDesc: '',
        fileList: [],
        fileCount: 0,
        uploadedFiles: []
      };
      // 清空文件输入
      if (this.$refs.directoryInput) {
        this.$refs.directoryInput.value = '';
      }
    },
    /** 触发目录选择 */
    triggerDirectorySelect() {
      if (this.$refs.directoryInput) {
        this.$refs.directoryInput.click();
      }
    },
    /** 清除目录选择 */
    clearDirectorySelection() {
      this.importForm.fileList = [];
      this.importForm.fileCount = 0;
      if (this.$refs.directoryInput) {
        this.$refs.directoryInput.value = '';
      }
    },
    /** 取消导入 */
    cancelImport() {
      this.importOpen = false;
      this.resetImportForm();
    },
    /** 处理目录输入框变化 */
    handleDirectoryInputChange(event) {
      const files = Array.from(event.target.files || []);
      
      // 过滤掉目录本身，只保留文件
      const validFiles = files.filter(file => {
        return file instanceof File && !file.name.endsWith('/');
      });
      
      // 直接保存原始File对象，不进行转换
      // 这样可以确保文件对象在后续上传时可用
      this.importForm.fileList = validFiles; // 直接保存File对象数组
      this.importForm.fileCount = validFiles.length;
      
      // 如果知识库名称为空，使用目录名作为默认名称
      if (!this.importForm.knowledgeName && validFiles.length > 0) {
        // 从第一个文件的路径中提取目录名
        const firstFile = validFiles[0];
        if (firstFile.webkitRelativePath) {
          const pathParts = firstFile.webkitRelativePath.split('/');
          if (pathParts.length > 0) {
            this.importForm.knowledgeName = pathParts[0];
          }
        }
      }
      
      // 手动触发表单验证更新
      this.$nextTick(() => {
        if (this.$refs.importForm) {
          this.$refs.importForm.validateField('knowledgeName');
        }
      });
    },
    /** 提交导入 */
    submitImport() {
      // 先验证文件是否选择
      if (!this.importForm.fileList || this.importForm.fileList.length === 0) {
        this.$modal.msgError("请选择要导入的目录");
        return false;
      }
      
      // 验证知识库名称
      if (!this.importForm.knowledgeName || this.importForm.knowledgeName.trim() === '') {
        this.$modal.msgError("知识库名称不能为空");
        return false;
      }
      
      // 验证表单
      this.$refs["importForm"].validate(valid => {
        if (!valid) {
          return false;
        }
        
        this.importUploading = true;
        this.importForm.uploadedFiles = []; // 清空已上传文件列表
        
        // 第一步：先上传所有文件
        this.uploadAllFiles().then(() => {
          // 第二步：所有文件上传成功后，创建知识库并关联文件
          this.createKnowledgeAndAssociateFiles();
        }).catch(error => {
          this.importUploading = false;
          console.error("上传文件失败", error);
          this.$modal.msgError("上传文件失败：" + (error.message || "未知错误"));
        });
      });
    },
    /** 上传所有文件 */
    uploadAllFiles() {
      return new Promise((resolve, reject) => {
        if (!this.importForm.fileList || this.importForm.fileList.length === 0) {
          reject(new Error("没有找到可上传的文件"));
          return;
        }
        
        // 准备上传文件
        const formData = new FormData();
        this.importForm.fileList.forEach(file => {
          if (file instanceof File) {
            formData.append('files', file);
          }
        });
        
        console.log("开始上传文件，文件数量:", this.importForm.fileList.length);
        
        // 调用临时上传接口
        request({
          url: '/flood/knowledge/uploadTemp',
          method: 'post',
          data: formData,
          timeout: 300000 // 5分钟超时
        }).then(response => {
          console.log("文件上传响应:", response);
          if (response.code === 200 && response.data && response.data.files) {
            // 保存已上传的文件信息
            this.importForm.uploadedFiles = response.data.files;
            console.log("文件上传成功，共", this.importForm.uploadedFiles.length, "个文件");
            resolve();
          } else {
            reject(new Error(response.msg || "文件上传失败"));
          }
        }).catch(error => {
          console.error("上传文件异常", error);
          reject(error);
        });
      });
    },
    /** 创建知识库并关联文件 */
    createKnowledgeAndAssociateFiles() {
      // 创建知识库
      const knowledgeData = {
        knowledgeName: this.importForm.knowledgeName.trim(),
        knowledgeDesc: this.importForm.knowledgeDesc || '',
        status: "0"
      };
      
      addKnowledge(knowledgeData).then(response => {
        if (response.code === 200) {
          // 获取知识库ID
          let knowledgeId = null;
          if (response.data) {
            if (response.data.knowledgeId) {
              knowledgeId = response.data.knowledgeId;
            } else if (typeof response.data === 'number' || typeof response.data === 'string') {
              knowledgeId = response.data;
            }
          }
          
          if (!knowledgeId) {
            this.importUploading = false;
            this.$modal.msgError("创建知识库成功，但无法获取知识库ID");
            return;
          }
          
          // 关联文件到知识库
          if (this.importForm.uploadedFiles && this.importForm.uploadedFiles.length > 0) {
            // 确保fileId是Number类型（Long）
            const fileIds = this.importForm.uploadedFiles.map(file => {
              const fileId = file.fileId;
              // 确保转换为数字类型
              return typeof fileId === 'string' ? parseInt(fileId, 10) : fileId;
            });
            
            console.log("准备关联文件，知识库ID:", knowledgeId, "文件IDs:", fileIds);
            
            request({
              url: '/flood/knowledge/associateFiles',
              method: 'put',
              data: {
                knowledgeId: Number(knowledgeId), // 确保是Number类型
                fileIds: fileIds
              }
            }).then(associateResponse => {
              this.importUploading = false;
              if (associateResponse.code === 200) {
                this.$modal.msgSuccess("导入成功！" + associateResponse.msg || ("共上传 " + this.importForm.uploadedFiles.length + " 个文件"));
                this.importOpen = false;
                this.resetImportForm();
                this.getList();
              } else {
                this.$modal.msgError(associateResponse.msg || "关联文件失败");
              }
            }).catch(error => {
              this.importUploading = false;
              console.error("关联文件失败", error);
              this.$modal.msgError("关联文件失败：" + (error.message || "未知错误"));
            });
          } else {
            // 没有文件需要关联，直接完成
            this.importUploading = false;
            this.$modal.msgSuccess("知识库创建成功");
            this.importOpen = false;
            this.resetImportForm();
            this.getList();
          }
        } else {
          this.importUploading = false;
          this.$modal.msgError(response.msg || "创建知识库失败");
        }
      }).catch(error => {
        this.importUploading = false;
        console.error("创建知识库失败", error);
        this.$modal.msgError("创建知识库失败：" + (error.message || "未知错误"));
      });
    },
    /** 上传文件 */
    uploadFiles(formData, knowledgeId) {
      console.log("开始上传文件，知识库ID:", knowledgeId);
      console.log("FormData中的文件数量:", formData.getAll('files').length);
      
      // 使用request上传文件（会自动添加token）
      // 注意：不要手动设置Content-Type，让浏览器自动设置，这样会包含boundary
      request({
        url: '/flood/knowledge/upload',
        method: 'post',
        data: formData,
        // 不设置Content-Type，让浏览器自动设置multipart/form-data; boundary=...
        timeout: 300000 // 5分钟超时
      }).then(response => {
        this.importUploading = false;
        console.log("上传响应:", response);
        if (response.code === 200) {
          this.$modal.msgSuccess(response.msg || "导入成功，共上传 " + this.importForm.fileCount + " 个文件");
          this.importOpen = false;
          this.resetImportForm();
          this.getList();
        } else {
          this.$modal.msgError(response.msg || "导入失败");
        }
      }).catch(error => {
        this.importUploading = false;
        console.error("上传文件失败", error);
        this.$modal.msgError("上传文件失败：" + (error.message || "未知错误"));
      });
    }
  }
};
</script>
