<template>
  <el-dialog v-model="dialogVisible" title="黑名单" width="600px" destroy-on-close @close="handleClose">
    <div class="blacklist-content">
      <!-- 黑名单列表 -->
      <div class="blacklist-list">
        <div v-for="user in blacklist" :key="user.id" class="blacklist-item">
          <div class="user-info">
            <div class="user-avatar">
              <img v-if="user.avatar" :src="user.avatar" :alt="user.name" />
              <el-icon v-else :size="40">
                <Avatar />
              </el-icon>
            </div>
            <span class="user-name">{{ user.name }}</span>
          </div>
          <el-button type="primary" plain size="small" :loading="user.unblocking" @click="handleUnblock(user)">
            解除拉黑
          </el-button>
        </div>

        <!-- 空状态 -->
        <el-empty v-if="blacklist.length === 0" description="暂无黑名单用户" />
      </div>

      <!-- 已解除拉黑的用户提示 -->
      <div v-if="unblockedUsers.length > 0" class="unblocked-section">
        <div class="unblocked-title">已解除拉黑 ({{ unblockedUsers.length }})</div>
        <div class="unblocked-list">
          <el-tag v-for="user in unblockedUsers" :key="user.id" type="info" closable @close="removeUnblockedUser(user.id)">
            {{ user.name }}
          </el-tag>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Avatar } from "@element-plus/icons-vue";
import { getBlackList, unblockUser } from "@/api/modules/dynamicManagement";
import { useUserStore } from "@/stores/modules/user";

interface BlacklistUser {
  id: number;
  name: string;
  avatar: string;
  unblocking: boolean;
  blockedId: number | string; // 被拉黑方ID
  blockedType: number; // 被拉黑方类型
  blockerId: number | string; // 拉黑方ID
  blockerType: number; // 拉黑方类型
}

const userStore = useUserStore();

const dialogVisible = ref(false);
const blacklist = ref<BlacklistUser[]>([]);
const unblockedUsers = ref<BlacklistUser[]>([]);
const submitting = ref(false);

// 打开对话框
const openDialog = () => {
  dialogVisible.value = true;
  loadBlacklist();
  unblockedUsers.value = [];
};

// 暴露方法给父组件使用
defineExpose({
  openDialog
});

// 加载黑名单列表
const loadBlacklist = async () => {
  try {
    // 获取当前用户信息
    const userId = userStore.userInfo?.id || userStore.userInfo?.userId || "";
    const userType = userStore.userInfo?.userType || userStore.userInfo?.type || 1; // 用户类型：1商家，2用户，默认1

    if (!userId) {
      ElMessage.warning("用户信息异常");
      return;
    }

    console.log("当前用户信息:", userStore.userInfo);
    console.log("当前用户类型:", userType);

    const res = await getBlackList({
      userType: userType, // 使用动态获取的用户类型
      userId: userId,
      type: 0
    });

    // 处理返回数据
    if (res.data) {
      const responseData = res.data as any;
      const list = responseData.records || responseData.list || responseData || [];
      blacklist.value = list.map((item: any) => ({
        id: item.id,
        name: item.blockedName || item.userName || item.name || "用户",
        avatar: item.userImage || item.avatar || "",
        unblocking: false,
        blockedId: item.blockedId,
        blockedType: item.blockedType || 1,
        blockerId: item.blockerId,
        blockerType: item.blockerType || 1
      }));
    }
  } catch (error) {
    console.error("加载黑名单失败:", error);
    ElMessage.error("加载黑名单失败");
  }
};

// 解除拉黑
const handleUnblock = async (user: BlacklistUser) => {
  try {
    await ElMessageBox.confirm(`确定要将"${user.name}"移出黑名单吗？`, "解除拉黑", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    user.unblocking = true;

    // 调用取消拉黑接口
    await unblockUser({
      id: user.id,
      blockedId: user.blockedId,
      blockedType: user.blockedType,
      blockerId: user.blockerId,
      blockerType: user.blockerType
    });

    // 从黑名单中移除
    const index = blacklist.value.findIndex(u => u.id === user.id);
    if (index > -1) {
      const removedUser = blacklist.value.splice(index, 1)[0];
      unblockedUsers.value.push(removedUser);
    }

    ElMessage.success("解除拉黑成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("解除拉黑失败:", error);
      ElMessage.error("解除拉黑失败");
    }
  } finally {
    user.unblocking = false;
  }
};

// 移除已解除的用户标签
const removeUnblockedUser = (userId: number) => {
  const index = unblockedUsers.value.findIndex(u => u.id === userId);
  if (index > -1) {
    unblockedUsers.value.splice(index, 1);
  }
};

// 提交（关闭对话框）
const handleSubmit = () => {
  if (unblockedUsers.value.length > 0) {
    ElMessage.success(`已成功解除 ${unblockedUsers.value.length} 位用户的拉黑`);
  }
  handleClose();
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  unblockedUsers.value = [];
};
</script>

<style scoped lang="scss">
.blacklist-content {
  .blacklist-list {
    max-height: 400px;
    overflow-y: auto;
    .blacklist-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 0;
      border-bottom: 1px solid #f0f0f0;
      &:last-child {
        border-bottom: none;
      }
      .user-info {
        display: flex;
        flex: 1;
        gap: 12px;
        align-items: center;
        .user-avatar {
          display: flex;
          flex-shrink: 0;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          overflow: hidden;
          background: #f5f7fa;
          border-radius: 50%;
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        .user-name {
          font-size: 15px;
          font-weight: 500;
          color: #303133;
        }
      }
    }
  }
  .unblocked-section {
    padding-top: 24px;
    margin-top: 24px;
    border-top: 1px solid #e4e7ed;
    .unblocked-title {
      margin-bottom: 12px;
      font-size: 14px;
      font-weight: 500;
      color: #606266;
    }
    .unblocked-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      .el-tag {
        font-size: 13px;
      }
    }
  }
}
.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
