<template>
  <div class="project-member-page">
    <div class="header-section">
      <h3>{{ t('project.management.detail.menu.projectMember') }}</h3>
      <el-button
        v-hasPermi="['project:management:queryProjectMemberInviteMember']"
        type="primary"
        @click="openInviteDialog"
      >
        {{ t('project.management.member.inviteMember') }}
      </el-button>
    </div>
    <el-divider />

    <el-card shadow="never">
      <el-table
        v-loading="loading"
        border
        :data="memberList"
        style="width: 100%"
      >
        <el-table-column type="index" :label="t('project.management.table.id')" width="60" align="center" />
        <el-table-column :label="t('project.management.member.name')" align="center" prop="name" width="150" />
        <el-table-column :label="t('project.management.member.phoneNumber')" align="center" prop="phoneNumber" width="150" />
        <el-table-column :label="t('project.management.member.dept')" align="center" prop="dept" width="200" />
        <el-table-column :label="t('project.management.member.note')" align="center" prop="note" show-overflow-tooltip />
        <el-table-column :label="t('project.management.member.time')" align="center" prop="time" width="180" />
        <el-table-column :label="t('project.management.member.operation')" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button
              v-hasPermi="['project:management:queryProjectMemberRemove']"
              type="danger"
              size="small"
              link
              @click="handleRemoveMember(scope.row)"
            >
              {{ t('project.management.member.remove') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 邀请成员对话框 -->
    <el-dialog
      v-model="inviteDialogVisible"
      :title="t('project.management.member.inviteDialogTitle')"
      width="700px"
      @close="handleInviteDialogClose"
    >
      <el-form :model="inviteForm" label-width="130px">
        <el-form-item :label="t('project.management.member.userNickname')">
          <el-select
            v-model="searchKeyword"
            filterable
            remote
            reserve-keyword
            :placeholder="t('project.management.member.userNicknamePlaceholder')"
            :remote-method="searchUsers"
            :loading="searchLoading"
            @change="handleSelectUser"
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="`${user.name} - ${user.deptName} - ${user.phoneNumber}`"
              :value="user.id"
            />
            <template #footer>
              <div v-if="userTotal > userQueryParams.pageSize" class="select-pagination">
                <el-button
                  text
                  :disabled="userQueryParams.pageNum === 1"
                  @click="loadPrevPage"
                >
                  {{ t('project.management.member.previousPage') }}
                </el-button>
                <span>{{ userQueryParams.pageNum }} / {{ Math.ceil(userTotal / userQueryParams.pageSize) }}</span>
                <el-button
                  text
                  :disabled="userQueryParams.pageNum * userQueryParams.pageSize >= userTotal"
                  @click="loadNextPage"
                >
                  {{ t('project.management.member.nextPage') }}
                </el-button>
              </div>
            </template>
          </el-select>
        </el-form-item>

        <!-- 已选择的用户列表 -->
        <el-form-item :label="t('project.management.member.selectedUsers')" v-if="selectedUsers.length > 0">
          <div class="selected-users-list">
            <div
              v-for="(user, index) in selectedUsers"
              :key="user.id"
              class="user-card"
            >
              <div class="user-info-left">
                <div class="info-value">{{ user.name }} / {{ user.deptName }}</div>
                <div class="info-value">{{ user.phoneNumber }}</div>
              </div>
              <div class="user-note-right">
                <el-input
                  v-model="user.note"
                  type="textarea"
                  :rows="2"
                  :placeholder="t('project.management.member.notePlaceholder')"
                  maxlength="50"
                  show-word-limit
                />
              </div>
              <el-button
                type="danger"
                size="small"
                text
                @click="removeSelectedUser(index)"
                class="remove-btn"
              >
                {{ t('project.management.member.remove') }}
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="inviteDialogVisible = false">{{ t('project.management.member.cancel') }}</el-button>
          <el-button
            type="primary"
            @click="handleInvite"
            :disabled="selectedUsers.length === 0"
          >
            {{ t('project.management.member.invite') }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认邀请对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      :title="t('project.management.member.confirmInviteTitle')"
      width="500px"
    >
      <div class="confirm-content">
        <p style="margin-bottom: 15px; font-weight: bold;">{{ t('project.management.member.confirmInviteMessage') }}</p>
        <div class="confirm-user-list">
          <div
            v-for="user in selectedUsers"
            :key="user.id"
            class="confirm-user-item"
          >
            <span>{{ user.name }} - {{ user.deptName }}</span>
            <span v-if="user.note" class="user-note">({{ t('project.management.member.note') }}: {{ user.note }})</span>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">{{ t('project.management.member.cancel') }}</el-button>
          <el-button
            type="primary"
            @click="confirmInvite"
            :loading="inviteLoading"
          >
            {{ t('project.management.member.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 移除成员确认对话框 -->
    <el-dialog
      v-model="removeDialogVisible"
      :title="t('project.management.member.removeMemberTitle')"
      width="400px"
    >
      <div style="padding: 20px 0; text-align: center; font-size: 14px;">
        {{ t('project.management.member.confirmRemoveMessage', { dept: removingMember?.dept, name: removingMember?.name }) }}
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeDialogVisible = false">{{ t('project.management.member.cancel') }}</el-button>
          <el-button
            type="danger"
            @click="confirmRemoveMember"
            :loading="removeLoading"
          >
            {{ t('project.management.member.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { inject, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { queryProjectMember, listOnNameNotJoinProject, inviteProjectMember, removeProjectMember } from '@/api/project/management';
import { ProjectMemberVO, ProjectMemberQuery, UserVO, UserNotInProjectQuery, InviteMemberForm } from '@/api/project/management/types';

const { t } = useI18n();

// 接收从父组件传递的项目ID
const projectId = inject<any>('projectId');

// 列表数据
const memberList = ref<ProjectMemberVO[]>([]);
const loading = ref(true);
const total = ref(0);

// 查询参数
const queryParams = ref<ProjectMemberQuery>({
  pageNum: 1,
  pageSize: 10,
  id: projectId?.value || 0
});

/** 查询项目成员列表 */
const getList = async () => {
  loading.value = true;
  try {
    queryParams.value.id = projectId?.value || 0;
    const res = await queryProjectMember(queryParams.value);
    memberList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('Failed to fetch project members:', error);
  } finally {
    loading.value = false;
  }
};

// ========== 邀请成员相关 ==========
// 对话框状态
const inviteDialogVisible = ref(false);
const confirmDialogVisible = ref(false);

// 搜索相关
const searchKeyword = ref('');
const searchLoading = ref(false);
const userOptions = ref<UserVO[]>([]);
const userTotal = ref(0);

// 用户查询参数
const userQueryParams = ref<UserNotInProjectQuery>({
  pageNum: 1,
  pageSize: 5,
  id: projectId?.value || 0,
  name: ''
});

// 已选择的用户列表（包含用户信息和备注）
interface SelectedUser extends UserVO {
  note?: string;
}
const selectedUsers = ref<SelectedUser[]>([]);

// 邀请表单
const inviteForm = ref({});

// 邀请加载状态
const inviteLoading = ref(false);

// ========== 移除成员相关 ==========
// 移除对话框状态
const removeDialogVisible = ref(false);
const removeLoading = ref(false);
const removingMember = ref<ProjectMemberVO | null>(null);

/** 打开邀请对话框 */
const openInviteDialog = () => {
  inviteDialogVisible.value = true;
};

/** 搜索用户 */
const searchUsers = async (query: string) => {
  if (!query || query.trim() === '') {
    userOptions.value = [];
    userTotal.value = 0;
    return;
  }

  searchLoading.value = true;
  userQueryParams.value.name = query;
  userQueryParams.value.pageNum = 1;
  userQueryParams.value.id = projectId?.value || 0;

  try {
    const res = await listOnNameNotJoinProject(userQueryParams.value);
    userOptions.value = res.rows || [];
    userTotal.value = res.total || 0;
  } catch (error) {
    console.error('Failed to search users:', error);
    ElMessage.error(t('project.management.member.searchUserFailed'));
  } finally {
    searchLoading.value = false;
  }
};

/** 加载上一页 */
const loadPrevPage = async () => {
  if (userQueryParams.value.pageNum > 1) {
    userQueryParams.value.pageNum--;
    await searchUsers(userQueryParams.value.name || '');
  }
};

/** 加载下一页 */
const loadNextPage = async () => {
  const maxPage = Math.ceil(userTotal.value / userQueryParams.value.pageSize);
  if (userQueryParams.value.pageNum < maxPage) {
    userQueryParams.value.pageNum++;
    await searchUsers(userQueryParams.value.name || '');
  }
};

/** 选择用户 */
const handleSelectUser = (userId: string | number) => {
  const user = userOptions.value.find(u => u.id === userId);
  if (user) {
    // 检查是否已经选择过该用户
    const isAlreadySelected = selectedUsers.value.some(u => u.id === userId);
    if (!isAlreadySelected) {
      selectedUsers.value.push({
        ...user,
        note: ''
      });
    } else {
      ElMessage.warning(t('project.management.member.userAlreadySelected'));
    }
  }
  // 清空搜索框
  searchKeyword.value = '';
};

/** 移除已选择的用户 */
const removeSelectedUser = (index: number) => {
  selectedUsers.value.splice(index, 1);
};

/** 点击邀请按钮 */
const handleInvite = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning(t('project.management.member.selectAtLeastOneUser'));
    return;
  }
  // 打开确认对话框
  confirmDialogVisible.value = true;
};

/** 确认邀请 */
const confirmInvite = async () => {
  inviteLoading.value = true;
  try {
    const inviteData: InviteMemberForm = {
      projectId: projectId?.value || 0,
      users: selectedUsers.value.map(user => ({
        id: user.id,
        note: user.note || ''
      }))
    };

    await inviteProjectMember(inviteData);
    ElMessage.success(t('project.management.member.inviteSuccess'));

    // 关闭所有对话框
    confirmDialogVisible.value = false;
    inviteDialogVisible.value = false;

    // 重新初始化
    resetInviteForm();

    // 刷新成员列表
    await getList();
  } catch (error) {
    console.error('Failed to invite members:', error);
    ElMessage.error(t('project.management.member.inviteFailed'));
  } finally {
    inviteLoading.value = false;
  }
};

/** 关闭邀请对话框 */
const handleInviteDialogClose = () => {
  resetInviteForm();
};

/** 重置邀请表单 */
const resetInviteForm = () => {
  searchKeyword.value = '';
  selectedUsers.value = [];
  userOptions.value = [];
  userTotal.value = 0;
  userQueryParams.value = {
    pageNum: 1,
    pageSize: 5,
    id: projectId?.value || 0,
    name: ''
  };
};

/** 点击移除成员 */
const handleRemoveMember = (member: ProjectMemberVO) => {
  removingMember.value = member;
  removeDialogVisible.value = true;
};

/** 确认移除成员 */
const confirmRemoveMember = async () => {
  if (!removingMember.value) return;

  removeLoading.value = true;
  try {
    await removeProjectMember(projectId?.value || 0, removingMember.value.id);
    ElMessage.success(t('project.management.member.removeSuccess'));
    
    // 关闭对话框
    removeDialogVisible.value = false;
    removingMember.value = null;
    
    // 刷新成员列表
    await getList();
  } catch (error) {
    console.error('Failed to remove member:', error);
    ElMessage.error(t('project.management.member.removeFailed'));
  } finally {
    removeLoading.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.project-member-page {
  height: 100%;
}

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

.info-section {
  padding: 16px 0;
}

.info-section p {
  line-height: 2;
  font-size: 14px;
  color: #606266;
  margin: 8px 0;
}

.info-section strong {
  color: #303133;
  margin-right: 8px;
}

h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.info-tip {
  color: #909399;
  font-style: italic;
  margin-top: 16px;
}

/* 邀请成员对话框样式 */
.selected-users-list {
  width: 100%;
  max-height: 400px;
  overflow-y: auto;
}

.user-card {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 8px;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
}

.user-info-left {
  flex-shrink: 0;
  width: 120px;
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding-top: 6px;
}

.info-value {
  font-size: 13px;
  color: #303133;
  line-height: 1.3;
}

.user-note-right {
  flex: 3;
  min-width: 0;
}

.remove-btn {
  flex-shrink: 0;
  margin-left: 4px;
  align-self: center;
}

/* 确认对话框样式 */
.confirm-content {
  padding: 10px 0;
}

.confirm-user-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  background-color: #f5f7fa;
}

.confirm-user-item {
  padding: 8px 0;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  color: #303133;
}

.confirm-user-item:last-child {
  border-bottom: none;
}

.user-note {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}

/* 下拉选择分页样式 */
.select-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-top: 1px solid #e4e7ed;
  background-color: #f5f7fa;
}

.select-pagination span {
  font-size: 12px;
  color: #606266;
}
</style>
