<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">文档管理</span>
          <el-button type="primary" @click="handleBack">返回项目列表</el-button>
        </div>
      </template>

      <div class="content-wrapper">
        <div class="tree-container">
          <div class="tree-header">
            <el-button v-hasPermi="['document:folder:add']" type="primary" icon="Plus" size="small" @click="handleAddFolder">新建文件夹</el-button>
          </div>
          <el-scrollbar class="tree-scrollbar">
            <el-tree
              v-loading="loading"
              :data="treeData"
              :props="treeProps"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <el-icon>
                    <Folder v-if="data.type === 0" />
                    <Location v-else-if="data.type === 1" />
                    <OfficeBuilding v-else-if="data.type === 2" />
                    <Document v-else />
                  </el-icon>
                  <span class="node-label">{{ node.label }}</span>
                  <span class="node-actions">
                    <el-dropdown trigger="click" @command="handleCommand($event, data)">
                      <span class="el-dropdown-link">
                        <el-icon><MoreFilled /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="add" v-hasPermi="['document:folder:add']">添加子节点</el-dropdown-item>
                          <el-dropdown-item command="edit" v-hasPermi="['document:folder:edit']">编辑</el-dropdown-item>
                          <el-dropdown-item command="delete" v-hasPermi="['document:folder:remove']">删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </span>
                </span>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
        <div class="content-container">
          <el-empty description="文档内容展示区域">
          </el-empty>
        </div>
      </div>
    </el-card>

    <!-- 添加文件夹对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" append-to-body>
      <el-form ref="folderFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%;">
            <el-option 
              v-for="typeOption in getAvailableTypes()" 
              :key="typeOption.value" 
              :label="typeOption.label" 
              :value="typeOption.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="限制层级" prop="restrictionLevel">
          <el-input-number v-model="form.restrictionLevel" :min="-1" style="width: 100%;" placeholder="请输入限制层级" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" type="textarea" :rows="4" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { listFolder, addFolder, delFolder, getFolder, updateFolder } from '@/api/document/folder';
import { FolderListVO, FolderForm } from '@/api/document/folder/types';
import { Folder, Document, Edit, Delete, Plus, MoreFilled, Location, OfficeBuilding } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import type { ComponentInternalInstance } from 'vue';

interface Props {
  projectId?: number | string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  back: [];
}>();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 数据定义
const loading = ref(false);
const buttonLoading = ref(false);
const treeData = ref<FolderListVO[]>([]);
const folderFormRef = ref<FormInstance>();

// 对话框
const dialog = reactive({
  visible: false,
  title: '',
  isEdit: false
});

// 当前操作的节点
const currentNode = ref<FolderListVO | null>(null);

// 表单初始数据
const initFormData: FolderForm = {
  id: undefined,
  projectId: undefined,
  parentId: undefined,
  type: 0,
  name: '',
  status: 0,
  note: '',
  restrictionLevel: -1
};

// 表单数据
const form = ref<FolderForm>({ ...initFormData });

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ]
};

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name'
};

// 获取文件夹列表
const getList = async () => {
  if (!props.projectId) {
    ElMessage.warning('项目ID不存在');
    return;
  }
  
  loading.value = true;
  try {
    const res = await listFolder({ projectId: props.projectId } as any);
    treeData.value = res.data || [];
  } catch (error) {
    ElMessage.error('获取文件夹列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 返回项目列表
const handleBack = () => {
  emit('back');
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  folderFormRef.value?.resetFields();
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 新建文件夹（顶级）
const handleAddFolder = () => {
  reset();
  currentNode.value = null;
  form.value.projectId = props.projectId;
  form.value.parentId = undefined;
  dialog.visible = true;
  dialog.title = '新增文件夹';
  dialog.isEdit = false;
};

// 新增子节点
const handleAddChild = (data: FolderListVO) => {
  reset();
  currentNode.value = data;
  form.value.projectId = props.projectId;
  form.value.parentId = data.id;
  dialog.visible = true;
  dialog.title = '新增子节点';
  dialog.isEdit = false;
};

// 获取可选类型（根据父节点类型限制）
const getAvailableTypes = () => {
  if (!currentNode.value) {
    // 顶级节点，可以选择所有类型
    return [
      { label: '文件夹', value: 0 },
      { label: '国家', value: 1 },
      { label: '中心', value: 2 }
    ];
  }
  
  const parentType = currentNode.value.type;
  
  if (parentType === 1 || parentType === 2) {
    // 父节点是国家或中心，子节点只能是中心或文件夹
    return [
      { label: '文件夹', value: 0 },
      { label: '中心', value: 2 }
    ];
  } else {
    // 父节点是文件夹，子节点只能是文件夹
    return [
      { label: '文件夹', value: 0 }
    ];
  }
};

// 下拉菜单命令处理
const handleCommand = (command: string, data: FolderListVO) => {
  if (command === 'add') {
    handleAddChild(data);
  } else if (command === 'edit') {
    handleEdit(data);
  } else if (command === 'delete') {
    handleDelete(data);
  }
};

// 提交表单
const submitForm = () => {
  folderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 如果是编辑，显示确认对话框
      if (dialog.isEdit) {
        try {
          const typeLabel = form.value.type === 0 ? '文件夹' : form.value.type === 1 ? '国家' : '中心';
          const confirmMessage = `
            <div style="text-align: left;">
              <p><strong>名称：</strong>${form.value.name}</p>
              <p><strong>类型：</strong>${typeLabel}</p>
              <p><strong>限制层级：</strong>${form.value.restrictionLevel}</p>
              <p><strong>备注：</strong>${form.value.note || '无'}</p>
            </div>
          `;
          await ElMessageBox.confirm(confirmMessage, '确认修改信息', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          });
        } catch {
          return; // 用户取消
        }
      }
      
      buttonLoading.value = true;
      try {
        if (dialog.isEdit) {
          await updateFolder(form.value);
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addFolder(form.value);
          proxy?.$modal.msgSuccess('新增成功');
        }
        dialog.visible = false;
        await getList();
      } catch (error) {
        console.error(dialog.isEdit ? '修改失败' : '新增失败', error);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

// 编辑
const handleEdit = async (data: FolderListVO) => {
  reset();
  loading.value = true;
  try {
    const res = await getFolder(data.id);
    Object.assign(form.value, res.data);
    currentNode.value = null; // 编辑时不限制类型
    dialog.visible = true;
    dialog.title = '修改文件夹';
    dialog.isEdit = true;
  } catch (error) {
    ElMessage.error('获取文件夹信息失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 删除
const handleDelete = async (data: FolderListVO) => {
  // 检查是否有子节点
  if (data.children && data.children.length > 0) {
    ElMessage.warning('该文件夹下存在子节点，无法删除');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确认删除 "${data.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    await delFolder(data.id);
    ElMessage.success('删除成功');
    await getList();
  } catch (error: any) {
    // 用户取消删除或删除失败
    if (error !== 'cancel') {
      console.error('删除失败:', error);
    }
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.text-lg {
  font-size: 1.125rem;
}

.font-bold {
  font-weight: 700;
}

.content-wrapper {
  display: flex;
  height: calc(100vh - 250px);
  min-height: 500px;
}

.tree-container {
  width: 300px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.tree-header {
  padding: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.tree-scrollbar {
  flex: 1;
  overflow: hidden;
  
  :deep(.el-scrollbar__view) {
    padding: 10px;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
  
  .el-icon {
    margin-right: 8px;
    font-size: 16px;
  }
  
  .node-label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .node-actions {
    display: none;
  }
  
  &:hover .node-actions {
    display: inline-flex;
    gap: 4px;
  }
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 16px;
  
  &:hover {
    color: var(--el-color-primary);
  }
}

.content-container {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.detail-content {
  max-width: 800px;
}
</style>
