<template>
  <div class="home-page">
    <el-header>
      <myheader />
    </el-header>
    <el-main>
      <div class="home-page-container">
        <div class="home-page-header">
          <HeaderTabs @button-click="handleButtonClick" />
        </div>
        <div class="home-page-content">
          <router-view :key="activeProjectId"  @save="handleSave" @copy="handleCopy" @cut="handleCut" @paste="handlePaste"/>
        </div>
        <!-- 底部项目标签栏 -->
        <div class="project-tabs">
          <el-tabs
            v-model="activeProjectId"
            type="card"
            closable
            class="project-tabs-bar"
            @tab-click="handleProjectTabClick"
            @tab-remove="handleProjectTabRemove"
          >
            <el-tab-pane
              v-for="project in projectStore.projects"
              :key="project.projectId"
              :name="project.projectId"
            >
              <template #label>
                <span class="project-tab-label">
                  <img :src="modelIcon" alt="Project Icon" class="tab-icon" />
                  {{ project.projectName }}
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
          <el-button class="add-project-btn" type="text" @click="addProjectdialog = true">
            <el-icon><Plus /></el-icon>
          </el-button>
        </div>
      </div>
    </el-main>
  </div>
  <el-dialog
    v-model="addProjectdialog"
    align-center
    :append-to-body="true"
    width="500"
    class="dialog_class"
    draggable
  >
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <!-- <el-image :src="icon" fit="contain"></el-image> -->
        <h4 :id="titleId" :class="titleClass">{{ $t("dialog.new") }}</h4>
      </div>
    </template>
    <el-form
      :model="newproject"
      :rules="rules"
      ref="projectForm"
      :label-width="labelWidth"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item :label="`${$t('project.name')}：`" prop="name">
            <el-input
              v-model="newproject.name"
              class="w-50 m-2"
              :placeholder="$t('project.inputProjectName')"
              maxlength="100"
            />
          </el-form-item>
        </el-col>   
        <el-col :span="24">
          <el-form-item :label="`${$t('project.keywords')}：`" prop="keywords">
            <el-input
              v-model="newproject.keywords"
              class="w-50 m-2"
              :placeholder="$t('project.inputProjectKeywords')"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="`${$t('project.description')}：`" prop="description">
            <el-input
              v-model="newproject.description"
              class="w-50 m-2"
              :placeholder="$t('project.inputProjectDescription')"
              maxlength="500"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="lastbtn">
        <el-button @click="addProjectdialog = false">{{
          $t("dialog.cancel")
        }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("dialog.ok") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
  <ProjectListDialog
    v-model:visible="dialog.projectListDialog"
    identify="importProject"
    @confirm="handleProjectConfirm"
    @refresh-flow="handleRefreshFlow"
  />

</template>

<script setup>
import myheader from '@/components/layout/header.vue';
import HeaderTabs from './HeaderButtonBar.vue';
import { RouterView, useRouter, useRoute } from 'vue-router';
import { ElMessage, ElIcon } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useProjectStore } from '@/store/project';
import { useI18n } from 'vue-i18n';
import modelIcon from '@/assets/icons/model.png';
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { request } from "@/utils/request"
import emitter from "@/utils/emitter"
import FileUploadDialog from '@/components/dialog/FileUploadDialog.vue';
import ProjectListDialog from "@/components/dialog/ProjectListDialog.vue";
const { t, locale } = useI18n()
const router = useRouter();
const route = useRoute();
const projectStore = useProjectStore();
const addButtonLeft = ref(70); // 默认位置

// 根据当前路由路径设置 activeTab
const activeTab = ref(route.path.slice(1) || 'model');
const activeProjectId = computed(() => projectStore.activeProjectId);

// 控制添加项目对话框显示
let addProjectdialog = ref(false);
// 表单引用
const projectForm = ref(null);

// 控制 FileSelector 对话框显示
const showFileSelector = ref(false);

// 添加当前操作标识
const currentIdentify = ref("openProject")

let newproject = ref({
  name: "",
  description: "",
  keywords: ""
})

// 弹窗开关
let dialog = ref({
  projectListDialog: false
})

const labelWidth = computed(() => {
  return locale.value === "zh-CN" ? "80px" : "120px"
})
// 监听路由变化，同步 activeTab
watch(
  () => route.path,
  (newPath) => {
    const tabName = newPath.slice(1);
    if (tabName) {
      activeTab.value = tabName;
    }
  }
);

// 监听 activeTab 变化，导航到对应路由
watch(activeTab, (newTab) => {
  if (newTab && route.path !== `/${newTab}`) {
    router.push(`/${newTab}`);
  }
});

// 更新 + 按钮位置
const updateAddButtonPosition = () => {
  nextTick(() => {
    const navWrap = document.querySelector('.project-tabs-bar .el-tabs__nav-wrap');
    const nav = document.querySelector('.project-tabs-bar .el-tabs__nav');
    if (nav && navWrap) {
      const tabs = nav.querySelectorAll('.el-tabs__item');
      const lastTab = tabs[tabs.length - 1];
      if (lastTab) {
        const rect = lastTab.getBoundingClientRect();
        const navWrapRect = navWrap.getBoundingClientRect();
        addButtonLeft.value = rect.right - navWrapRect.left + 40;
        
      } else {
        addButtonLeft.value = 70; // 默认位置
      }
    } else {
      addButtonLeft.value = 70; // 默认位置
    }
  });
};

// 监听 projects 和 activeProjectId 变化，更新按钮位置
watch(() => projectStore.projects.length, updateAddButtonPosition);
watch(() => projectStore.activeProjectId, updateAddButtonPosition);

onMounted(() => {
  updateAddButtonPosition();
});

// 提交表单
const submitForm = () => {
  projectForm.value.validate((valid) => {
    if (valid) {
      addProject()
    } else {
      return false
    }
  })
}

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: t('project.inputProjectName'), trigger: 'blur' }
  ],
  keywords: [
    { required: false, message: t('project.inputProjectKeywords'), trigger: 'blur' }
  ],
  description: [
    { required: false, message: t('project.inputProjectDescription'), trigger: 'blur' }
  ]
})

const handleButtonClick = (action) => {
    switch (action) {
      case 'copy':
        emitter.emit('copy');
        break;
      case 'cut':
        emitter.emit('cut');
        break;
      case 'paste':
        emitter.emit('paste');
        break;
      case 'save':    
        emitter.emit('save');
        break;
      case 'importProject':
        dialog.value.projectListDialog = true;
        // const newProject = {
        //   projectId: `proj-${Date.now()}`,
        //   projectName: `Project ${projectStore.projects.length + 1}`,
        // };
        // projectStore.addProject(newProject);
        // ElMessage.success(t('message.importSuccess'));
        // nextTick(() => updateAddButtonPosition());
        break;
      default:
        console.log(`Button clicked: ${action}`);
        break;
    }
};

// 处理项目选择确认
const handleProjectConfirm = (project) => {
  router.push({ path: "/home" });
  dialog.value.projectListDialog = false;
};

const handleProjectTabClick = (tab) => {
  projectStore.setActiveProject(tab.props.name);
};

const handleProjectTabRemove = (projectId) => {
  projectStore.removeProject(projectId);
  nextTick(() => {
    updateAddButtonPosition(); // 手动触发位置更新
  });
};

// 处理文件选择
const handleFileSelected = (file) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('transCode', 'ES0029');

  request(formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
    .then((res) => {
      // 假设后端返回项目信息
      const newProject = {
        projectId: res.pid, // 使用后端返回的 pid
        projectName: res.name || `Imported Project ${Date.now()}`,
        keywords: res.keywords || '',
        remark: res.remark || '',
        flow: res.flow || '{"nodes":[],"edges":[]}',
      };
      projectStore.addProject(newProject);
      projectStore.setActiveProject(newProject.projectId);
      ElMessage.success(t('message.importSuccess'));
      nextTick(() => updateAddButtonPosition());
    })
    .catch((err) => {
      ElMessage.error(err.returnMsg || t('message.importFailed'));
    });
};

// 添加项目
const addProject = () => {
  const params = {
    transCode: "ES0002",
    name: newproject.value.name,
    remark: newproject.value.description,
    keywords: newproject.value.keywords
  }
  request(params)
    .then((res) => {
        projectStore.addProject({
          projectId: res.pid, // 使用后端返回的 pid
          projectName: params.name,
          keywords: params.keywords,
          remark: params.remark,
          flow: '{"nodes":[],"edges":[]}',
        });
      ElMessage.success("添加成功")
      addProjectdialog.value = false
      // 设置激活项目
      projectStore.setActiveProject(res.pid);
    })
    .catch((err) => {
      ElMessage.error(err.returnMsg)
    })
}

const handleSave = () => {
  emitter.emit('save');
};

const handleCopy = () => {
  emitter.emit('copy');
};

const handleCut = () => {
  emitter.emit('cut');
};

const handlePaste = () => {
  emitter.emit('paste');
};
</script>

<style scoped>
.el-header {
  background-color: #075679;
  margin: 0 2px 0 0 !important;
}

.home-page {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  overflow: auto;
}

.home-page-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  overflow: auto;
}

.home-page-header {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  width: 100%;
  min-height: 80px;
  background: #ffffff;
}

.project-tabs {
  width: 100%;
  padding: 0 10px;
  background: #f5f7fa;
  border-top: 1px solid #e4e7ed;
  position: relative;
}

.home-page-content {
  display: flex;
  width: 100%;
  height: calc(100vh - 32px - 89px - 39px); /* 减去顶部和底部的高度 */
}

.add-project-btn {
  position: absolute;
  top: 6px;
  left: v-bind('`${addButtonLeft}px`');
  color: #000000;
  font-size: 16px;
  padding: 0;
  height: 32px;
  line-height: 32px;
}

:deep(.el-header) {
  padding: 0;
  margin: 0;
  height: auto;
}

:deep(.el-main) {
  padding: 0;
  margin: 0;
  flex: 1;
}

:deep(.project-tabs-bar .el-tabs__content) {
  display: none; /* 仅隐藏 project-tabs-bar 的标签内容 */
}

:deep(.project-tabs-bar .el-tabs__header) {
  margin: 3px 0 1px;
  background: #f5f7fa;
  position: relative;
}

:deep(.project-tabs-bar .el-tabs__item) {
  color: #000000;
  background: #e3e3e5;
  border: 1px solid #c5c7ca;
  height: 32px;
  line-height: 32px;
  padding: 0 12px;
  display: flex;
  align-items: center;
}

:deep(.project-tabs-bar .el-tabs__item.is-active) {
  background: #ffffff;
  color: #000000;
}

:deep(.el-tabs--card>.el-tabs__header .el-tabs__item.is-active.is-closable){
  padding: 0 3px 0 0 !important;
  margin: 0 !important;
}

:deep(.project-tabs-bar .el-tabs__nav-wrap) {
  overflow-x: auto;
}
</style>