<template>
  <div class="logout-management-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <span>用户注销申请管理</span>
            <el-tag type="info" size="small" class="ml-2">注销申请审批流程</el-tag>
          </div>
          <div class="statistics-info" v-if="total > 0">
            <span>申请总数：{{ total }} 个</span>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
          <el-form-item label="申请用户" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="申请状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
              <el-option label="待审核" value="0" />
              <el-option label="已通过" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </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>
      </div>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedRows.length > 0">
        <el-alert :title="`已选择 ${selectedRows.length} 个申请`" type="info" :closable="false" show-icon>
          <template #default>
            <el-button
              v-if="canBatchApprove"
              type="success"
              size="small"
              icon="Check"
              @click="handleBatchApprove(true)"
            >
              批量通过
            </el-button>
            <el-button
              v-if="canBatchApprove"
              type="danger"
              size="small"
              icon="Close"
              @click="handleBatchApprove(false)"
            >
              批量驳回
            </el-button>
            <el-button
              v-if="canBatchDelete"
              type="danger"
              size="small"
              icon="Delete"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
          </template>
        </el-alert>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="logoutRequestList"
          stripe
          border
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />

          <!-- 序号列 -->
          <el-table-column label="序号" type="index" width="60" align="center">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </el-table-column>

          <!-- 用户名 -->
          <el-table-column label="用户名" width="120" align="center">
            <template #default="scope">
              <div class="username-cell">
                <el-tag type="primary" size="small">{{ scope.row.userName }}</el-tag>
              </div>
            </template>
          </el-table-column>

          <!-- 真实姓名 -->
          <el-table-column label="昵称" width="100" align="center">
            <template #default="scope">
              <div class="real-name-cell">
                <strong>{{ scope.row.nickName }}</strong>
              </div>
            </template>
          </el-table-column>

          <!-- 部门 -->
          <el-table-column label="部门" align="center" width="150" prop="deptName" show-overflow-tooltip />

          <!-- 申请类型 -->
          <el-table-column label="申请类型" width="100" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.isSelfApply" type="success" size="small">
                本人申请
              </el-tag>
              <el-tag v-else type="warning" size="small">
                管理员代申请
              </el-tag>
            </template>
          </el-table-column>

          <!-- 申请人 -->
          <el-table-column label="申请人" width="120" align="center">
            <template #default="scope">
              <div class="apply-user-cell">
                <div class="apply-user-name">{{ scope.row.applyUserName }}</div>
                <div class="apply-user-nick" v-if="scope.row.applyUserNickName">
                  ({{ scope.row.applyUserNickName }})
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 申请原因 -->
          <el-table-column label="申请原因" width="200" show-overflow-tooltip>
            <template #default="scope">
              <el-tooltip :content="scope.row.applyReason" placement="top">
                <div class="reason-text">{{ scope.row.applyReason }}</div>
              </el-tooltip>
            </template>
          </el-table-column>

          <!-- 申请状态 -->
          <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
              <el-tag type="primary" size="small">
                {{ scope.row.statusName }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 申请时间 -->
          <el-table-column label="申请时间" align="center" width="160" sortable prop="applyTime">
            <template #default="scope">
              {{ formatDate(scope.row.applyTime) }}
            </template>
          </el-table-column>

          <!-- 审核人 -->
          <el-table-column label="审核人" width="120" align="center">
            <template #default="scope">
              <div v-if="scope.row.approveUserName" class="approve-user-cell">
                <div class="approve-user-name">{{ scope.row.approveUserName }}</div>
                <div class="approve-user-nick" v-if="scope.row.approveUserNickName">
                  ({{ scope.row.approveUserNickName }})
                </div>
              </div>
              <span v-else class="no-approve">-</span>
            </template>
          </el-table-column>

          <!-- 审核时间 -->
          <el-table-column label="审核时间" align="center" width="160">
            <template #default="scope">
              <div v-if="scope.row.approveTime">
                {{ formatDate(scope.row.approveTime) }}
              </div>
              <span v-else class="no-approve">-</span>
            </template>
          </el-table-column>

          <!-- 审核意见 -->
          <el-table-column label="审核意见" width="150" align="center">
            <template #default="scope">
              <div v-if="scope.row.approveRemark" class="approve-remark-cell">
                <el-tooltip :content="scope.row.approveRemark" placement="top">
                  <span class="remark-text">{{ scope.row.approveRemark }}</span>
                </el-tooltip>
              </div>
              <span v-else class="no-approve">-</span>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" fixed="right" width="180" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <!-- 查看用户详情 -->
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="handleViewUserDetail(scope.row)"
                  title="查看用户详情"
                >
                  用户详情
                </el-button>

                <!-- 审批操作（仅待审核状态） -->
                <template v-if="scope.row.status === '0'">
                  <el-button
                    v-hasPermi="['system:userlogout:approve']"
                    link
                    type="success"
                    size="small"
                    @click="handleApprove(scope.row, true)"
                  >
                    通过
                  </el-button>
                  <el-button
                    v-hasPermi="['system:userlogout:approve']"
                    link
                    type="danger"
                    size="small"
                    @click="handleApprove(scope.row, false)"
                  >
                    驳回
                  </el-button>
                </template>

                <!-- 删除操作（仅限已处理的申请） -->
                <el-button
                  v-if="canDelete(scope.row)"
                  v-hasPermi="['system:userlogout:remove']"
                  link
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>

          <template #empty>
            <div class="empty-data">
              <el-empty description="暂无注销申请" />
            </div>
          </template>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <Pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>

    <!-- 用户详情抽屉 -->
    <UserDetailDrawer
      v-model:visible="userDetailVisible"
      :user-detail="currentUserDetail"
      @approve="handleUserApproveFromDetail"
    />

    <!-- 批量审批对话框 -->
    <el-dialog
      v-model="batchApprovalVisible"
      :title="batchApprovalTitle"
      width="600px"
      :close-on-click-modal="false"
      @closed="resetBatchApprovalForm"
    >
      <div class="batch-approval-content">
        <el-alert
          :title="batchApprovalAlertTitle"
          :type="batchApprovalForm.approve ? 'success' : 'warning'"
          :closable="false"
          show-icon
          class="mb-4"
        />

        <!-- 审批意见输入 -->
        <div class="approval-remark-section">
          <el-divider content-position="left">审批意见</el-divider>
          <el-input
            v-model="batchApprovalForm.approveRemark"
            type="textarea"
            placeholder="请输入审批意见（可选）"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
          <div v-if="!batchApprovalForm.approve" class="reject-notice">
            <el-alert
              title="注意：驳回的申请将被直接删除，用户可重新申请"
              type="warning"
              :closable="false"
              class="mt-3"
            />
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchApprovalVisible = false">取 消</el-button>
          <el-button
            :type="batchApprovalForm.approve ? 'success' : 'danger'"
            :loading="batchApprovalLoading"
            @click="submitBatchApproval"
          >
            确认{{ batchApprovalForm.approve ? '通过' : '驳回' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import Pagination from '@/components/Pagination/index.vue';
import UserDetailDrawer from './components/UserDetailDrawer.vue';
import {
  batchApproveLogoutRequest,
  deleteLogoutRequest,
  listLogoutRequests
} from '@/api/system/approval/logoutRequest';
import { getApprovalUserDetail } from '@/api/system/approval/userApproval';
import {
  BatchLogoutApprovalForm,
  canDeleteLogoutRequest,
  getLogoutRequestStatusTagType,
  LogoutRequestQuery,
  LogoutRequestStatus,
  LogoutRequestVO,
  UserApprovalDetailVO
} from '@/api/system/approval/types';
import { getUserProfile } from '@/api/system/user';

// ======================== 基础设置 ========================
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// ======================== 响应式数据 ========================
const loading = ref(true);
const logoutRequestList = ref<LogoutRequestVO[]>([]);
const total = ref(0);
const dateRange = ref<[string, string]>(['', '']);
const selectedRows = ref<LogoutRequestVO[]>([]);

// 表格引用
const tableRef = ref();
const queryFormRef = ref();

// 用户信息
const userInfo = reactive<Partial<UserVO>>({});

// 查询参数
const queryParams = reactive<LogoutRequestQuery>({
  pageNum: 1,
  pageSize: 10,
  deptId: '',
  status: ''
});

// 申请详情对话框相关
const currentDetail = ref<LogoutRequestVO | null>(null);

// 用户详情抽屉相关
const userDetailVisible = ref(false);
const currentUserDetail = ref<UserApprovalDetailVO | null>(null);

// 批量审批相关状态
const batchApprovalVisible = ref(false);
const batchApprovalLoading = ref(false);
const batchApprovalForm = reactive<BatchLogoutApprovalForm>({
  ids: [],
  approve: true,
  approveRemark: ''
});

// ======================== 计算属性 ========================

// 批量操作按钮显示逻辑
const canBatchApprove = computed(() => {
  return selectedRows.value.every(row => row.status === LogoutRequestStatus.PENDING);
});

const canBatchDelete = computed(() => {
  return selectedRows.value.every(row => row.status !== LogoutRequestStatus.PENDING);
});

const batchApprovalTitle = computed(() => {
  return batchApprovalForm.approve ? '批量审批通过' : '批量审批驳回';
});

const batchApprovalAlertTitle = computed(() => {
  const action = batchApprovalForm.approve ? '通过' : '驳回';
  return `确认${action}选中的 ${batchApprovalForm.ids.length} 个注销申请吗？`;
});

// ======================== 工具方法 ========================
const formatDate = (timestamp: number | Date): string => {
  if (!timestamp) return '';
  const date = timestamp instanceof Date ? timestamp : new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

const getStatusTagType = (status: string): string => {
  return getLogoutRequestStatusTagType(status);
};

const canDelete = (request: LogoutRequestVO): boolean => {
  return canDeleteLogoutRequest(request);
};

// ======================== 数据获取 ========================
const getList = async () => {
  try {
    loading.value = true;
    const params = {
      ...queryParams,
      ...proxy?.addDateRange({}, dateRange.value, 'ApplyTime')
    };

    const res = await listLogoutRequests(params);
    logoutRequestList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    proxy?.$modal.msgError('获取注销申请列表失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 获取当前用户信息
 */
const getUserInfo = async () => {
  const res = await getUserProfile();
  Object.assign(userInfo, res.data.user);
  if (userInfo.userName !== 'superuser') {
    queryParams.deptId = res.data.user.deptId;
  }
};

// ======================== 事件处理 ========================
const handleSelectionChange = (selection: LogoutRequestVO[]) => {
  selectedRows.value = selection;
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  getList();
};

// 查看用户详情
const handleViewUserDetail = async (row: LogoutRequestVO) => {
  try {
    const res = await getApprovalUserDetail(row.userId);
    currentUserDetail.value = res.data;
    userDetailVisible.value = true;
  } catch (error) {
    proxy?.$modal.msgError('获取用户详情失败');
  }
};

// 从用户详情抽屉审批后的回调
const handleUserApproveFromDetail = () => {
  userDetailVisible.value = false;
  // 刷新列表
  getList();
  ElMessage.success('用户审批通过成功，该用户已激活');
};

// 单个审批
const handleApprove = async (row: LogoutRequestVO, approve: boolean) => {
  try {
    const action = approve ? '通过' : '驳回';
    const confirmTitle = approve ? '确认通过注销申请' : '确认驳回注销申请';
    const message = approve ?
      '审批通过后，用户状态将变为注销状态' :
      '驳回后申请记录将被删除，用户可重新申请';

    const { value: approveRemark } = await ElMessageBox.prompt(
      message + '\n\n请输入审批意见（可选）',
      confirmTitle,
      {
        confirmButtonText: `确认${action}`,
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入审批意见...'
      }
    );
    const batchForm: BatchLogoutApprovalForm = { ids: [String(row.id)], approve, approveRemark };
    await batchApproveLogoutRequest(batchForm);
    const successMessage = approve ? '注销申请审批通过成功' : '注销申请驳回成功，申请记录已删除';
    ElMessage.success(successMessage);
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('审批操作失败');
    }
  }
};

// 批量审批
const handleBatchApprove = (approve: boolean) => {
  if (selectedRows.value.length === 0) {
    proxy?.$modal.msgWarning('请先选择要审批的申请');
    return;
  }

  batchApprovalForm.ids = selectedRows.value.map(row => String(row.id));
  batchApprovalForm.approve = approve;
  batchApprovalForm.approveRemark = '';
  batchApprovalVisible.value = true;
};

// 提交批量审批
const submitBatchApproval = async () => {
  try {
    batchApprovalLoading.value = true;
    await batchApproveLogoutRequest(batchApprovalForm);
    const message = batchApprovalForm.approve ? `批量审批通过成功，共处理 ${batchApprovalForm.ids.length} 个申请` : `批量驳回成功，共删除 ${batchApprovalForm.ids.length} 个申请记录`;
    ElMessage.success(message);
    batchApprovalVisible.value = false;
    selectedRows.value = [];
    tableRef.value?.clearSelection();
    await getList();
  } catch (error) {
    proxy?.$modal.msgError('批量审批操作失败');
  } finally {
    batchApprovalLoading.value = false;
  }
};

const resetBatchApprovalForm = () => {
  batchApprovalForm.ids = [];
  batchApprovalForm.approve = true;
  batchApprovalForm.approveRemark = '';
};

// 删除申请
const handleDelete = async (row: LogoutRequestVO) => {
  try {
    await proxy?.$modal.confirm(`是否确认删除该注销申请记录？删除后不可恢复。`);
    await deleteLogoutRequest(row.id);
    ElMessage.success('删除成功');
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('删除操作失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    const ids = selectedRows.value.map(row => row.id);
    await proxy?.$modal.confirm(`是否确认删除选中的 ${ids.length} 个注销申请记录？删除后不可恢复。`);
    await deleteLogoutRequest(ids);
    ElMessage.success(`批量删除成功，共删除 ${ids.length} 个申请`);
    selectedRows.value = [];
    tableRef.value?.clearSelection();
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('批量删除操作失败');
    }
  }
};

// ======================== 生命周期 ========================
onMounted(() => {
  Promise.resolve()
    .then(() => getUserInfo())
    .then(() => {
      getList();
    })
    .catch((error) => {
      console.error('页面初始化失败:', error);
    });
});
</script>

<style lang="scss" scoped>
.logout-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

.statistics-info {
  font-size: 14px;
  color: #606266;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.search-form {
  margin-bottom: 0;
}

.batch-actions {
  margin-bottom: 20px;
}

.table-section {
  margin-bottom: 20px;
}

// 用户名单元格
.username-cell {
  text-align: center;
}

// 真实姓名单元格
.real-name-cell {
  text-align: center;

  strong {
    color: #303133;
    font-weight: 600;
  }
}

// 申请人信息单元格
.apply-user-cell {
  text-align: center;

  .apply-user-name {
    font-weight: 500;
    margin-bottom: 2px;
  }

  .apply-user-nick {
    font-size: 12px;
    color: #909399;
  }
}

// 审核人信息单元格
.approve-user-cell {
  text-align: center;

  .approve-user-name {
    font-weight: 500;
    margin-bottom: 2px;
  }

  .approve-user-nick {
    font-size: 12px;
    color: #909399;
  }
}

// 审核意见单元格
.approve-remark-cell {
  .remark-text {
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 12px;
    color: #606266;
    cursor: help;
  }
}

// 申请原因样式
.reason-text {
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-approve {
  color: #c0c4cc;
  font-style: italic;
}

// 操作按钮样式
.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}

.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

// 详情对话框样式
.detail-content {
  .reason-content,
  .approve-content {
    background-color: #f8f9fa;
    padding: 10px;
    border-radius: 4px;
    word-break: break-all;
    line-height: 1.5;
  }
}

// 批量审批对话框样式
.batch-approval-content {
  .approval-remark-section {
    margin-top: 20px;
  }

  .reject-notice {
    margin-top: 12px;
  }
}

.ml-2 {
  margin-left: 8px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mt-3 {
  margin-top: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .logout-management-container {
    padding: 10px;
  }

  .search-form {
    :deep(.el-form-item) {
      margin-bottom: 15px;
    }
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
}
</style>
