<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="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模版名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板类型" prop="templateType">
        <el-select v-model="queryParams.templateType" placeholder="请选择模板类型" clearable>
          <el-option
            v-for="dict in templateTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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="['generator:template: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="['generator:template: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="['generator:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['generator:template:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-folder"
          size="mini"
          @click="handleStructure"
          v-hasPermi="['generator:template:list']"
        >项目结构</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模版名称" align="center" prop="templateName" v-if="columns[0].visible"/>
      <el-table-column label="模板类型" align="center" prop="templateType" v-if="columns[1].visible">
        <template slot-scope="scope">
          <span>{{ formatTemplateType(scope.row.templateType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模版路径" align="center" prop="templatePath" v-if="columns[2].visible"/>
      <el-table-column label="模版描述" align="center" prop="templateDesc" v-if="columns[3].visible"/>
      <el-table-column label="状态" align="center" key="templateStatus" v-if="columns[4].visible">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.templateStatus"
            :active-value="Number(0)"
            :inactive-value="Number(1)"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleManageFiles(scope.row)"
            v-hasPermi="['generator:template:list']"
          >文件管理</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['generator:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['generator:template: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模版名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模版名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="templateType">
          <el-select v-model="form.templateType" placeholder="请选择模板类型">
            <el-option
              v-for="dict in templateTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模版路径" prop="templatePath">
          <el-input v-model="form.templatePath" placeholder="请输入模版路径" />
        </el-form-item>
        <el-form-item label="模版描述" prop="templateDesc">
          <el-input v-model="form.templateDesc" 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="templateFilesDialogTitle" :visible.sync="templateFilesDialogOpen" width="800px" append-to-body @open="getListTemplateFiles">
      <div v-if="currentTemplate">
        <p>正在管理模板: {{ currentTemplate.templateName }} (ID: {{ currentTemplate.templateId }})</p>
        
        <!-- Add New File Button (Placeholder for now) -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddTemplateFile"
              v-hasPermi="['generator:template:add']"
            >新增文件</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-view"
              size="mini"
              @click="handlePreviewAllFiles"
              v-hasPermi="['generator:template:list']"
            >预览文件</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="templateFileLoading" :data="templateFileList" @selection-change="handleTemplateFileSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="文件ID" align="center" prop="templateFileId" />
          <el-table-column label="文件名称" align="center" prop="fileName" /> 
          <el-table-column label="文件路径" align="center" prop="filePath" />
          <!-- Add other relevant columns for template files -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handlePreviewTemplateFile(scope.row)"
                v-hasPermi="['generator:template:list']"
              >预览</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdateTemplateFile(scope.row)"
                v-hasPermi="['generator:template:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteTemplateFile(scope.row)"
                v-hasPermi="['generator:template:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- We might need a pagination component here if the list can be long -->

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="templateFilesDialogOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改代码模版文件对话框 -->
    <el-dialog :title="fileTitle" :visible.sync="fileOpen" width="700px" append-to-body>
      <el-form ref="fileForm" :model="fileForm" :rules="fileRules" label-width="100px">
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="fileForm.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="文件路径" prop="filePath">
          <el-input v-model="fileForm.filePath" placeholder="请输入文件路径" />
        </el-form-item>
        <el-form-item label="文件内容" prop="fileContent">
          <el-input
            v-model="fileForm.fileContent"
            type="textarea"
            placeholder="请输入内容"
            :rows="15"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelFile">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 代码预览对话框 -->
    <el-dialog :title="previewTitle" :visible.sync="previewOpen" width="800px" append-to-body>
      <div v-if="currentTemplate && previewFiles.length > 0">
        <el-tabs v-model="activeFileTab" type="card">
          <el-tab-pane
            v-for="file in previewFiles"
            :key="file.templateFileId"
            :label="file.fileName"
            :name="file.templateFileId.toString()"
          >
            <div class="code-preview" v-if="file.fileContent">
              <div class="preview-header">
                <span class="preview-title">{{ file.fileName }}</span>
                <el-link
                  :underline="false"
                  icon="el-icon-document-copy"
                  v-clipboard:copy="file.fileContent"
                  v-clipboard:success="clipboardSuccess"
                  class="copy-btn"
                >复制</el-link>
              </div>
              <div class="preview-content" ref="previewContent">
                <pre><code class="hljs" v-html="highlightCode(file.fileContent, file.fileName)"></code></pre>
              </div>
            </div>
            <div v-else class="empty-preview">
              <span>加载中...</span>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-else class="empty-preview">
        <span>没有可预览的文件</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 项目结构对话框 -->
    <el-dialog :title="structureTitle" :visible.sync="structureOpen" width="1300px" append-to-body>
      <structure v-if="structureOpen" :templateId="currentTemplate ? currentTemplate.templateId : null"></structure>
      <div slot="footer" class="dialog-footer">
        <el-button @click="structureOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate, changeTemplateStatus } from '@/api/generator/template';
import { listTemplateFilesByTemplateId, getTemplateFile, addTemplateFile, updateTemplateFile, delTemplateFile } from '@/api/generator/templateFile';
import hljs from 'highlight.js/lib/highlight';
import 'highlight.js/styles/atom-one-dark.css';
import Structure from './structure'

// Register languages
hljs.registerLanguage('java', require('highlight.js/lib/languages/java'));
hljs.registerLanguage('xml', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('yaml', require('highlight.js/lib/languages/yaml'));
hljs.registerLanguage('html', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('vue', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript'));
hljs.registerLanguage('sql', require('highlight.js/lib/languages/sql'));

export default {
  name: 'Template',
  components: {
    Structure
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代码模版表格数据
      templateList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 当前操作的模板
      currentTemplate: null,
      // 代码模版文件管理对话框
      templateFilesDialogOpen: false,
      templateFilesDialogTitle: '代码文件管理',
      templateFileList: [],
      templateFileLoading: true,
      // 选中的模板文件
      selectedTemplateFiles: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        templateType: null
      },
      // 列信息
      columns: [
        { key: 0, label: '模版名称', visible: true },
        { key: 1, label: '模板类型', visible: true },
        { key: 2, label: '模版路径', visible: true },
        { key: 3, label: '模版描述', visible: true },
        { key: 4, label: '状态', visible: true }
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: '模板名称不能为空', trigger: 'blur' }
        ],
        templatePath: [
          { required: true, message: '模板路径不能为空', trigger: 'blur' }
        ],
        templateType: [
          { required: true, message: '模板类型不能为空', trigger: 'change' }
        ]
      },
      templateTypeOptions: [
        { value: 'backend', label: '后端' },
        { value: 'frontend', label: '前台前端' },
        { value: 'admin_frontend', label: '后台前端' }
      ],
      // 文件表单对话框
      fileOpen: false,
      fileTitle: '',
      fileForm: {
        templateFileId: null,
        templateId: null,
        fileName: '',
        filePath: '',
        fileContent: ''
      },
      fileRules: {
        fileName: [
          { required: true, message: '文件名称不能为空', trigger: 'blur' }
        ],
        filePath: [],
        fileContent: [
          { required: true, message: '文件内容不能为空', trigger: 'blur' }
        ]
      },
      previewOpen: false,
      previewTitle: '',
      previewFiles: [],
      activeFileTab: '',
      clipboardSuccess: false,
      // 项目结构对话框
      structureOpen: false,
      structureTitle: '项目结构'
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询代码模版列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        templateName: null,
        templatePath: null,
        templateDesc: null,
        templateType: null,
        templateStatus: '0' // Assuming default status is "0" (normal)
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 模板文件多选框选中数据
    handleTemplateFileSelectionChange(selection) {
      this.selectedTemplateFiles = selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加代码模版';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids;
      getTemplate(templateId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改代码模版';
      });
    },
    /** 管理代码模版文件按钮操作 */
    handleManageFiles(row) {
      this.currentTemplate = row;
      this.templateFileList = [];
      this.templateFilesDialogOpen = true;
      this.templateFilesDialogTitle = `管理 '${row.templateName}' 的代码文件`;
    },
    /** 查询模板下的文件列表 */
    getListTemplateFiles() {
      if (!this.currentTemplate || !this.currentTemplate.templateId) {
        this.$modal.msgWarning("没有选中的模板");
        return;
      }
      this.templateFileLoading = true;
      listTemplateFilesByTemplateId(this.currentTemplate.templateId).then(response => {
        this.templateFileList = response.rows || response.data || response;
        this.templateFileLoading = false;
      }).catch(() => {
        this.templateFileLoading = false;
        this.$modal.msgError("加载模板文件列表失败");
      });
    },
    /** 新增模板文件按钮操作 */
    handleAddTemplateFile() {
      this.resetFileForm();
      this.fileForm.templateId = this.currentTemplate.templateId;
      this.fileOpen = true;
      this.fileTitle = '添加模板文件';
    },
    /** 修改模板文件按钮操作 */
    handleUpdateTemplateFile(fileRow) {
      this.resetFileForm();
      const templateFileId = fileRow.templateFileId;
      getTemplateFile(templateFileId).then(response => {
        this.fileForm = response.data;
        this.fileOpen = true;
        this.fileTitle = '修改模板文件';
      });
    },
    /** 删除模板文件按钮操作 */
    handleDeleteTemplateFile(fileRow) {
      this.$modal.confirm('是否确认删除文件 "' + fileRow.fileName + '"？').then(() => {
        return delTemplateFile(fileRow.templateFileId);
      }).then(() => {
        this.getListTemplateFiles();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {});
    },
    // 取消文件按钮
    cancelFile() {
      this.fileOpen = false;
      this.resetFileForm();
    },
    // 文件表单重置
    resetFileForm() {
      this.fileForm = {
        templateFileId: null,
        templateId: null,
        fileName: '',
        filePath: '',
        fileContent: ''
      };
      if (this.$refs.fileForm) {
        this.$refs.fileForm.resetFields();
      }
    },
    /** 预览单个模板文件 */
    handlePreviewTemplateFile(fileRow) {
      this.previewFiles = [fileRow];
      this.activeFileTab = fileRow.templateFileId.toString();
      this.previewOpen = true;
      this.previewTitle = '代码预览';
      this.loadFileContent(fileRow);
    },
    /** 预览所有选中的模板文件 */
    handlePreviewAllFiles() {
      // 使用选中的文件或所有文件
      if (this.selectedTemplateFiles && this.selectedTemplateFiles.length > 0) {
        this.previewFiles = [...this.selectedTemplateFiles];
      } else {
        this.previewFiles = [...this.templateFileList];
      }
      
      if (this.previewFiles.length > 0) {
        this.activeFileTab = this.previewFiles[0].templateFileId.toString();
        // 加载每个文件的内容
        this.previewFiles.forEach(file => {
          this.loadFileContent(file);
        });
      }
      
      this.previewOpen = true;
      this.previewTitle = '代码预览';
    },
    /** 加载文件内容 */
    loadFileContent(file) {
      if (!file.fileContent) {
        getTemplateFile(file.templateFileId).then(response => {
          // 找到文件在预览列表中的索引并更新内容
          const index = this.previewFiles.findIndex(f => f.templateFileId === file.templateFileId);
          if (index !== -1) {
            // 使用 $set 确保响应式更新
            this.$set(this.previewFiles[index], 'fileContent', response.data.fileContent);
          }
        });
      }
    },
    /** 提交文件表单 */
    submitFileForm() {
      this.$refs['fileForm'].validate(valid => {
        if (valid) {
          if (this.fileForm.templateFileId != null) {
            updateTemplateFile(this.fileForm).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.fileOpen = false;
              this.getListTemplateFiles();
            });
          } else {
            addTemplateFile(this.fileForm).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.fileOpen = false;
              this.getListTemplateFiles();
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.templateId != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 模版状态修改
    handleStatusChange(row) {
      const text = row.templateStatus === 0 ? '启用' : '停用';
      this.$modal.confirm('确认要"' + text + '" "' + row.templateName + '"吗？').then(function() {
        return changeTemplateStatus(row.templateId, row.templateStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + '成功');
        this.getList();
      }).catch(function() {
        row.templateStatus = row.templateStatus === 0 ? 1 : 0;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids;
      this.$modal.confirm('是否确认删除代码模版编号为"' + templateIds + '"的数据项？').then(function() {
        return delTemplate(templateIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('generator/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`);
    },
    formatTemplateType(templateType) {
      const type = this.templateTypeOptions.find(opt => opt.value === templateType);
      return type ? type.label : templateType;
    },
    highlightCode(code, fileName) {
      if (!code) return '';
      
      // Determine language from fileName extension
      let language = 'plaintext';
      if (fileName) {
        const extension = fileName.split('.').pop().toLowerCase();
        
        // Map file extensions to languages
        const languageMap = {
          'java': 'java',
          'xml': 'xml',
          'html': 'html',
          'js': 'javascript',
          'vue': 'xml',
          'sql': 'sql',
          'yml': 'yaml',
          'yaml': 'yaml'
        };
        
        language = languageMap[extension] || 'plaintext';
      }
      
      try {
        // Apply syntax highlighting
        const result = hljs.highlight(language, code, true);
        return result.value || code;
      } catch (e) {
        console.error('Highlighting error:', e);
        return code;
      }
    },
    clipboardSuccess() {
      this.$modal.msgSuccess('复制成功');
    },
    /** 项目结构按钮操作 */
    handleStructure() {
      if (this.single) {
        this.$modal.msgError("请先选择一个模板");
        return;
      }
      this.currentTemplate = this.templateList.find(item => item.templateId === this.ids[0]);
      this.structureOpen = true;
    }
  }
};
</script>

<style scoped>
.code-preview {
  height: 100%;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 0 10px;
}

.preview-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.copy-btn {
  color: #409EFF;
  font-size: 14px;
}

.copy-btn:hover {
  color: #66b1ff;
}

.preview-content {
  max-height: 500px;
  overflow-y: auto;
  background-color: #282c34;
  border-radius: 4px;
}

.preview-content pre {
  margin: 0;
  padding: 10px;
}

.empty-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}
</style>
