<template>
  <div class="center-info-page">
    <div class="header-section">
      <h3>{{ t('project.management.detail.menu.centerInfo') }}</h3>
    </div>
    <el-divider />

    <!-- 搜索表单 -->
    <el-form :model="queryParams" :inline="true" class="search-form">
      <el-form-item label="中心名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入中心名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        border
        :data="centerList"
        style="width: 100%"
      >
        <el-table-column label="序号" align="center" prop="id" width="80" />
        <el-table-column label="中心名称" align="center" prop="name" min-width="150" show-overflow-tooltip />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="success">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy" width="120" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="更新人" align="center" prop="updateBy" width="120" show-overflow-tooltip />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" />
      </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="邀请成员"
      width="700px"
      @close="handleInviteDialogClose"
    >
      <el-form label-width="100px">
        <el-form-item label="模糊搜索">
          <el-select
            v-model="searchKeyword"
            filterable
            remote
            reserve-keyword
            placeholder="请输入成员昵称"
            :remote-method="searchMembers"
            :loading="searchLoading"
            @change="handleSelectMember"
            style="width: 100%"
          >
            <el-option
              v-for="member in memberOptions"
              :key="member.id"
              :label="`${member.name} / ${member.dept} --- ${member.phoneNumber}`"
              :value="member.id"
            />
            <template #footer>
              <div v-if="memberTotal > memberQueryParams.pageSize" class="select-pagination">
                <el-button
                  text
                  :disabled="memberQueryParams.pageNum === 1"
                  @click="loadPrevPage"
                >
                  上一页
                </el-button>
                <span>{{ memberQueryParams.pageNum }} / {{ Math.ceil(memberTotal / memberQueryParams.pageSize) }}</span>
                <el-button
                  text
                  :disabled="memberQueryParams.pageNum * memberQueryParams.pageSize >= memberTotal"
                  @click="loadNextPage"
                >
                  下一页
                </el-button>
              </div>
            </template>
          </el-select>
        </el-form-item>

        <!-- 已选择的成员列表 -->
        <el-form-item label="已选成员" v-if="selectedMembers.length > 0">
          <div class="selected-members-list">
            <div
              v-for="(member, index) in selectedMembers"
              :key="member.id"
              class="member-card"
            >
              <div class="member-info">
                {{ member.name }} / {{ member.dept }} / {{ member.phoneNumber }}
              </div>
              <el-button
                type="danger"
                size="small"
                text
                @click="removeSelectedMember(index)"
                class="remove-btn"
              >
                移除
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="inviteDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleConfirmInvite"
            :disabled="selectedMembers.length === 0"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认邀请对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      title="确认邀请"
      width="500px"
    >
      <div class="confirm-content">
        <p style="margin-bottom: 15px; font-weight: bold;">
          确认邀请以下成员进入 {{ currentCenter?.name }} 中？
        </p>
        <div class="confirm-member-list">
          <div
            v-for="member in selectedMembers"
            :key="member.id"
            class="confirm-member-item"
          >
            <span>{{ member.name }} / {{ member.dept }} / {{ member.phoneNumber }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmInvite"
            :loading="inviteLoading"
          >
            确认
          </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 { queryCenterInfo, queryMemberNotInCenter, inviteCenterMember } from '@/api/project/management';
import { CenterInfoVO, CenterInfoQuery, MemberNotInCenterVO, MemberNotInCenterQuery, InviteCenterMemberForm } from '@/api/project/management/types';

const { t } = useI18n();

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

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

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

/** 查询中心信息列表 */
const getList = async () => {
  loading.value = true;
  try {
    queryParams.value.projectId = projectId?.value || 0;
    const res = await queryCenterInfo(queryParams.value);
    centerList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('Failed to fetch center info:', error);
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    projectId: projectId?.value || 0,
    name: ''
  };
  getList();
};

// ========== 邀请成员相关 ==========
const inviteDialogVisible = ref(false);
const confirmDialogVisible = ref(false);
const currentCenter = ref<CenterInfoVO | null>(null);

// 搜索相关
const searchKeyword = ref('');
const searchLoading = ref(false);
const memberOptions = ref<MemberNotInCenterVO[]>([]);
const memberTotal = ref(0);

// 成员查询参数
const memberQueryParams = ref<MemberNotInCenterQuery>({
  pageNum: 1,
  pageSize: 5,
  projectId: projectId?.value || 0,
  folderId: 0,
  name: ''
});

// 已选择的成员
const selectedMembers = ref<MemberNotInCenterVO[]>([]);

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

// 防抖定时器
let searchTimer: NodeJS.Timeout | null = null;

/** 打开邀请成员对话框 */
const handleInviteMember = (center: CenterInfoVO) => {
  currentCenter.value = center;
  memberQueryParams.value.folderId = center.id;
  inviteDialogVisible.value = true;
};

/** 实际搜索成员的函数 */
const doSearchMembers = async () => {
  searchLoading.value = true;
  try {
    const res = await queryMemberNotInCenter(memberQueryParams.value);
    memberOptions.value = res.rows || [];
    memberTotal.value = res.total || 0;
  } catch (error) {
    console.error('Failed to search members:', error);
    ElMessage.error('搜索成员失败');
  } finally {
    searchLoading.value = false;
  }
};

/** 搜索成员（带防抖） */
const searchMembers = async (query: string) => {
  if (!query || query.trim() === '') {
    memberOptions.value = [];
    memberTotal.value = 0;
    return;
  }

  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
  }

  // 设置防抖，停止输入后300ms才发起请求
  searchTimer = setTimeout(async () => {
    memberQueryParams.value.name = query;
    memberQueryParams.value.pageNum = 1;
    memberQueryParams.value.projectId = projectId?.value || 0;
    await doSearchMembers();
  }, 300);
};

/** 加载上一页 */
const loadPrevPage = async () => {
  if (memberQueryParams.value.pageNum > 1) {
    memberQueryParams.value.pageNum--;
    await doSearchMembers();
  }
};

/** 加载下一页 */
const loadNextPage = async () => {
  const maxPage = Math.ceil(memberTotal.value / memberQueryParams.value.pageSize);
  if (memberQueryParams.value.pageNum < maxPage) {
    memberQueryParams.value.pageNum++;
    await doSearchMembers();
  }
};

/** 选择成员 */
const handleSelectMember = (memberId: string | number) => {
  const member = memberOptions.value.find(m => m.id === memberId);
  if (member) {
    // 检查是否已经选择过该成员
    const isAlreadySelected = selectedMembers.value.some(m => m.id === memberId);
    if (!isAlreadySelected) {
      selectedMembers.value.push(member);
    } else {
      ElMessage.warning('该成员已选择');
    }
  }
  // 清空搜索框
  searchKeyword.value = '';
};

/** 移除已选择的成员 */
const removeSelectedMember = (index: number) => {
  selectedMembers.value.splice(index, 1);
};

/** 点击确认按钮 */
const handleConfirmInvite = () => {
  if (selectedMembers.value.length === 0) {
    ElMessage.warning('请至少选择一位成员');
    return;
  }
  // 打开确认对话框
  confirmDialogVisible.value = true;
};

/** 确认邀请 */
const confirmInvite = async () => {
  if (!currentCenter.value) return;

  inviteLoading.value = true;
  try {
    const inviteData: InviteCenterMemberForm = {
      folderId: currentCenter.value.id,
      userIds: selectedMembers.value.map(m => m.id)
    };

    await inviteCenterMember(inviteData);
    ElMessage.success('邀请成功');

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

    // 重置表单
    resetInviteForm();

    // 刷新列表
    await getList();
  } catch (error) {
    console.error('Failed to invite members:', error);
    ElMessage.error('邀请失败');
  } finally {
    inviteLoading.value = false;
  }
};

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

/** 重置邀请表单 */
const resetInviteForm = () => {
  searchKeyword.value = '';
  selectedMembers.value = [];
  memberOptions.value = [];
  memberTotal.value = 0;
  memberQueryParams.value = {
    pageNum: 1,
    pageSize: 5,
    projectId: projectId?.value || 0,
    folderId: 0,
    name: ''
  };
  currentCenter.value = null;
  if (searchTimer) {
    clearTimeout(searchTimer);
    searchTimer = null;
  }
};

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

<style scoped>
.center-info-page {
  height: 100%;
}

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

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

.search-form {
  margin-bottom: 16px;
}

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

.member-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 8px;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
}

.member-info {
  flex: 1;
  font-size: 13px;
  color: #303133;
  line-height: 1.5;
}

.remove-btn {
  flex-shrink: 0;
}

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

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

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

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

/* 下拉选择分页样式 */
.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>
