<script setup lang="ts">
import { computed, nextTick, provide, ref, watch } from 'vue';
import { ElMessageBox } from 'element-plus';
import {
  fetchCreateProjectRequirementModule,
  fetchDeleteProjectRequirementModule,
  fetchGetProjectRequirementModuleTree,
  fetchUpdateProjectRequirementModule
} from '@/service/api';
import { useCurrentProject } from '../../../shared/use-current-project';
import ModuleTreeNode from './module-tree-node.vue';

defineOptions({ name: 'ProjectRequirementModuleTree' });

interface Props {
  requirementTree?: Api.Project.ProjectRequirement[];
}

const props = withDefaults(defineProps<Props>(), {
  requirementTree: () => []
});

interface Emits {
  (e: 'select', moduleId: string | undefined): void;
  (e: 'refresh'): void;
}

const emit = defineEmits<Emits>();

const { currentObjectId } = useCurrentProject();

const moduleTree = ref<Api.Project.ProjectRequirementModule[]>([]);
const selectedModuleId = ref<string | undefined>(undefined);
const editingNodeId = ref<string | undefined>(undefined);
const editingName = ref('');
const addingChildParentId = ref<string | undefined>(undefined);
const newChildModuleName = ref('');
const collapsedModuleIds = ref(new Set<string>());

provide('collapsedModuleIds', collapsedModuleIds);
provide('toggleCollapse', (moduleId: string) => {
  const nextSet = new Set(collapsedModuleIds.value);

  if (nextSet.has(moduleId)) {
    nextSet.delete(moduleId);
  } else {
    nextSet.add(moduleId);
  }

  collapsedModuleIds.value = nextSet;
});

const rootModule = computed<Api.Project.ProjectRequirementModule | null>(() => {
  return moduleTree.value.length ? moduleTree.value[0] : null;
});

const moduleRequirementCountMap = computed(() => {
  const countMap = new Map<string, number>();

  function countRequirementsByModule(nodes: Api.Project.ProjectRequirement[]) {
    for (const node of nodes) {
      countMap.set(node.moduleId, (countMap.get(node.moduleId) || 0) + 1);

      if (node.children?.length) {
        countRequirementsByModule(node.children);
      }
    }
  }

  if (props.requirementTree.length) {
    countRequirementsByModule(props.requirementTree);
  }

  return countMap;
});

async function loadModuleTree() {
  if (!currentObjectId.value) {
    moduleTree.value = [];
    return;
  }

  const { error, data } = await fetchGetProjectRequirementModuleTree(currentObjectId.value);

  if (error || !data) {
    moduleTree.value = [];
    return;
  }

  moduleTree.value = data;

  if (data.length > 0 && !selectedModuleId.value) {
    selectedModuleId.value = data[0].id;
    emit('select', data[0].id);
  }
}

function handleNodeSelect(moduleId: string) {
  if (editingNodeId.value || addingChildParentId.value) {
    return;
  }

  selectedModuleId.value = moduleId;
  emit('select', moduleId);
}

function handleStartEdit(module: Api.Project.ProjectRequirementModule) {
  editingNodeId.value = module.id;
  editingName.value = module.moduleName;

  nextTick(() => {
    const input = document.querySelector('.module-tree-item.is-editing .el-input__inner') as HTMLInputElement | null;
    input?.focus();
    input?.select();
  });
}

async function handleEditConfirm(module: Api.Project.ProjectRequirementModule) {
  const moduleName = editingName.value.trim();
  editingNodeId.value = undefined;

  if (!moduleName || moduleName === module.moduleName || !currentObjectId.value) {
    return;
  }

  const { error } = await fetchUpdateProjectRequirementModule({
    id: module.id,
    projectId: currentObjectId.value,
    parentId: module.parentId,
    moduleName,
    remark: module.remark,
    icon: module.icon,
    sort: module.sort
  });

  if (error) {
    return;
  }

  window.$message?.success('模块名称更新成功');
  await loadModuleTree();
  emit('refresh');
}

function handleEditCancel() {
  editingNodeId.value = undefined;
}

function handleStartAddChild(module: Api.Project.ProjectRequirementModule) {
  if (addingChildParentId.value) {
    return;
  }

  addingChildParentId.value = module.id;
  newChildModuleName.value = '';

  nextTick(() => {
    const input = document.querySelector('.new-child-module-input input') as HTMLInputElement | null;
    input?.focus();
  });
}

async function handleAddChildConfirm() {
  const moduleName = newChildModuleName.value.trim();
  const parentId = addingChildParentId.value;

  addingChildParentId.value = undefined;
  newChildModuleName.value = '';

  if (!moduleName || !parentId || !currentObjectId.value) {
    return;
  }

  const { error } = await fetchCreateProjectRequirementModule({
    projectId: currentObjectId.value,
    parentId,
    moduleName,
    remark: null,
    icon: null,
    sort: 0
  });

  if (error) {
    return;
  }

  window.$message?.success('子模块新增成功');
  await loadModuleTree();
  emit('refresh');
}

function handleAddChildCancel() {
  addingChildParentId.value = undefined;
  newChildModuleName.value = '';
}

async function handleDeleteModule(module: Api.Project.ProjectRequirementModule) {
  if (!currentObjectId.value) {
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除模块“${module.moduleName}”吗？`, '删除确认', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch {
    return;
  }

  const { error } = await fetchDeleteProjectRequirementModule({
    id: module.id,
    projectId: currentObjectId.value
  });

  if (error) {
    return;
  }

  window.$message?.success('模块删除成功');

  if (selectedModuleId.value === module.id) {
    const rootId = rootModule.value?.id || '';
    selectedModuleId.value = rootId;
    emit('select', rootId);
  }

  await loadModuleTree();
  emit('refresh');
}

watch(
  () => currentObjectId.value,
  async id => {
    if (!id) {
      moduleTree.value = [];
      return;
    }

    selectedModuleId.value = '';
    await loadModuleTree();
  },
  { immediate: true }
);

defineExpose({
  loadModuleTree,
  selectedModuleId
});
</script>

<template>
  <ElCard class="requirement-module-tree-card card-wrapper">
    <template #header>
      <div class="module-tree-header">
        <span class="module-tree-header__title">模块</span>
      </div>
    </template>

    <div class="module-tree-list">
      <template v-for="item in moduleTree" :key="item.id">
        <ModuleTreeNode
          :module="item"
          :level="0"
          :selected-module-id="selectedModuleId"
          :editing-node-id="editingNodeId"
          :editing-name="editingName"
          :adding-child-parent-id="addingChildParentId"
          :new-child-module-name="newChildModuleName"
          :root-module-id="rootModule?.id"
          :module-requirement-count-map="moduleRequirementCountMap"
          @select="handleNodeSelect"
          @edit="handleStartEdit"
          @edit-confirm="handleEditConfirm"
          @edit-cancel="handleEditCancel"
          @delete="handleDeleteModule"
          @add-child="handleStartAddChild"
          @add-child-confirm="handleAddChildConfirm"
          @add-child-cancel="handleAddChildCancel"
          @update-editing-name="editingName = $event"
          @update-new-child-module-name="newChildModuleName = $event"
        />
      </template>
    </div>
  </ElCard>
</template>

<style scoped>
.requirement-module-tree-card {
  height: 100%;
}

.requirement-module-tree-card :deep(.el-card__header) {
  padding: 12px 16px;
  border-bottom: 1px solid #f1f5f9;
}

.requirement-module-tree-card :deep(.el-card__body) {
  padding: 12px 8px;
  height: calc(100% - 49px);
  overflow: hidden;
}

.module-tree-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.module-tree-header__title {
  color: #1e293b;
  font-size: 15px;
  font-weight: 600;
}

.module-tree-list {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-height: 0;
  height: 100%;
  overflow-y: auto;
}

.module-tree-list::-webkit-scrollbar {
  width: 4px;
}

.module-tree-list::-webkit-scrollbar-track {
  background: transparent;
}

.module-tree-list::-webkit-scrollbar-thumb {
  background-color: #e2e8f0;
  border-radius: 2px;
}

.module-tree-list::-webkit-scrollbar-thumb:hover {
  background-color: #cbd5e1;
}
</style>
