<template>
  <ElMenu class="menu" mode="horizontal" @select="handleSelect">
    <ElMenuItem class="menu-logo" index="logo">
      <img id="global-header-logo" src="@/assets/seec-logo--horizontal.png" >
         Developer
    </ElMenuItem>
    <ElSubmenu index="project">
      <template #title>{{selectedProject.name}}</template>
      <template v-if="projectList.length > 0">
        <ElMenuItem v-for="project in projectList" :key="project.id" :index="`project-${project.id}`">{{project.name}}</ElMenuItem>
      </template>
      <template v-else>
        <ElMenuItem disabled>暂无项目</ElMenuItem>
      </template>
    </ElSubmenu>
      <template v-if="userLoggedIn">
        <ElSubmenu index="user" class="user">
          <template #title>{{userInfo.username}}</template>
          <!-- <ElMenuItem index="user-project">创建项目</ElMenuItem> -->
          <!-- <ElMenuItem index="user-invite">邀请成员</ElMenuItem> -->
          <ElMenuItem index="user-logout">登出</ElMenuItem>
        </ElSubmenu>
        <ElSubmenu index="message" class="message" text-color="#909399">
          <template #title>
            <i class="el-icon-news"></i>
            <i v-if="messageList.length > 0">{{messageList.length}}</i>
          </template>
          <ElMenuItem v-if="messageList.length === 0">暂无未读消息</ElMenuItem>
          <ElMenuItem v-for="(item, index) in messageList" :key="item.id" :index="`message-${index}`">{{item.content}}</ElMenuItem>
        </ElSubmenu>
      </template>
      <template v-else>
        <ElButton type="text" @click="login" class="user">登录</ElButton>
      </template>
  </ElMenu>
  <ElDrawer v-model="showProjectDrawer">
    <template #title><span>创建项目</span></template>
    <div class="drawer-content">
      <div class="form-container">
        <ElForm :model="createProjectForm">
          <ElFormItem label="项目名" prop="name">
            <ElInput v-model="createProjectForm.name" placeholder="请输入要创建的项目名"></ElInput>
          </ElFormItem>
          <ElFormItem label="项目描述" prop="description">
            <ElInput
              v-model="createProjectForm.description"
              placeholder="请输入项目描述"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 3}"
            ></ElInput>
          </ElFormItem>
          <ElFormItem>
            <ElButton @click="createProject" type="primary">创建</ElButton>
          </ElFormItem>
        </ElForm>
      </div>
    </div>
  </ElDrawer>
  <ElDrawer v-model="showInviteDrawer">
    <template #title><span>邀请成员</span></template>
    <div class="drawer-content">
      <div class="form-container">
      <ElForm :model="inviteProjectForm">
        <ElFormItem label="项目" prop="projectId">
          <ElSelect v-model="inviteProjectForm.projectId" placeholder="请选择成员将要加入的项目">
            <ElOption v-for="project in projectList" :key="project.id" :value="project.id" :label="project.name"></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="手机号" prop="phone">
          <ElInput v-model="inviteProjectForm.phone" placeholder="请输入成员注册所用手机号"></ElInput>
        </ElFormItem>
        <ElFormItem>
          <ElButton @click="inviteMember" type="primary">邀请</ElButton>
        </ElFormItem>
      </ElForm>
    </div>
  </div>
  </ElDrawer>
</template>

<script lang="ts">
import { ElMessage } from 'element-plus';

import { useProjectList } from '@/composable/useProject';
import { useUser } from '@/composable/useUser';
import { useMessage } from '@/composable/useMessage';
import { defineComponent, ref, reactive } from 'vue';
import { ProjectAPI } from '@/api';

import { WorkspaceDispatcher } from '@/store/dispatchers';
import { useRouter } from 'vue-router';

export default defineComponent({
  name: 'Menu',
  setup() {
    const { projectList, selectedProject, handleProjectChange } = useProjectList();
    const { userInfo, userLoggedIn, userLogOut } = useUser();
    const { messageList, handleMessageChange } = useMessage();

    const router = useRouter();

    const showProjectDrawer = ref(false);
    const showInviteDrawer = ref(false);

    const openProjectDrawer = () => {
      showProjectDrawer.value = true;
    };
    const openInviteDrawer = () => {
      showInviteDrawer.value = true;
    };
    const createProjectForm = reactive({
      name: '',
      description: '',
    });
    const createProject = async () => {
      await ProjectAPI.createProject(createProjectForm.name, createProjectForm.description);
      showProjectDrawer.value = false;
      WorkspaceDispatcher.refreshProjectList();
    };

    interface InviteProjectForm {
      projectId: undefined | number;
      phone: string;
    }

    const inviteProjectForm = reactive<InviteProjectForm>({
      projectId: undefined,
      phone: '',
    });
    const inviteMember = async () => {
      if (!inviteProjectForm.projectId) {
        ElMessage({
          type: 'error',
          message: '请选择有效的项目',
        });
        return;
      }

      await ProjectAPI.addProjectMember({
        projectId: inviteProjectForm.projectId,
        phone: inviteProjectForm.phone,
      });
      showInviteDrawer.value = false;
      if (selectedProject.value.id !== -1) { WorkspaceDispatcher.changeProject(selectedProject.value.id); }
    };

    const handleSelect = (index: string) => {
      const [type, id] = index.split('-');
      switch (type) {
        case 'logo': {
          router.push('/home');
          break;
        }
        case 'project': {
          handleProjectChange(parseInt(id, 10));
          break;
        }
        case 'user': {
          if (id === 'project') {
            openProjectDrawer();
          } else if (id === 'invite') {
            openInviteDrawer();
          } else if (id === 'logout') {
            userLogOut();
          }
          break;
        }
        case 'message': {
          handleMessageChange(parseInt(id, 10));
          break;
        }
        default:
          console.warn('unknown type of sub-menu');
          break;
      }
    };

    const login = () => {
      window.location = `http://${process.env.VUE_APP_PORTAL_HOST}/interaction?scope=openid&client_id=seec-seec&redirect_uri=${
        encodeURI(`http://${window.location.host}/`)
      }` as unknown as Location;
    };

    return {
      projectList,
      messageList,
      selectedProject,

      handleSelect,

      userInfo,
      userLoggedIn,
      userLogOut,

      showProjectDrawer,
      showInviteDrawer,

      createProjectForm,
      createProject,
      inviteProjectForm,
      inviteMember,

      login,
    };
  },
});
</script>

<style lang="scss" scoped>
.menu {
  margin-left: -20px;
  width: 100%;
  position: fixed;
  z-index: 1000;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.menu-logo {
  color: #000000;
  font-size: 24px;
  font-weight: bolder;
  line-height: 58px;
  /*margin-left: 30px;*/
  transition: all .2s linear;
  user-select: none;
}
.menu-logo.is-disabled {
  opacity: 1;
  cursor: default;
}
.user {
  float: right;
  height: 60px;
  margin: 0 20px 0 0;
}
.drawer-content {
  display: flex;
  justify-content: center;
}
.form-container {
  width: 80%;
}
.message {
  float: right;
  .el-badge {
    height: 20px;
  }
}
#global-header-logo {
  height: 32px;
  margin-left: 10px;
  margin-right: 10px;
  cursor: pointer;
}
</style>
