<template>
  <div class="role-auth-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>
            <span class="ml-3 pending-count" v-if="pendingCount > 0">待审核：{{ pendingCount }} 个</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="roleName">
            <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="申请类型" prop="applyType">
            <el-select v-model="queryParams.applyType" placeholder="请选择申请类型" clearable style="width: 150px">
              <el-option label="申请授权" value="1" />
              <el-option label="申请取消授权" value="2" />
            </el-select>
          </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-option label="已拒绝" value="2" />
              <el-option label="已撤销" value="3" />
            </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="canBatchCancel" type="warning" size="small" icon="Close" @click="handleBatchCancel"> 批量撤销 </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="roleAuthRequestList"
          stripe
          border
          highlight-current-row
          size="small"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" align="center" />

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

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

          <!-- 真实姓名 -->
          <el-table-column label="昵称" width="80" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span class="real-name">{{ scope.row.nickName }}</span>
            </template>
          </el-table-column>

          <!-- 部门 -->
          <el-table-column label="部门" width="100" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span class="dept-name">{{ scope.row.deptName }}</span>
            </template>
          </el-table-column>

          <!-- 角色名称 -->
          <el-table-column label="角色名称" width="110" align="center" show-overflow-tooltip>
            <template #default="scope">
              <el-tag type="success" size="small">{{ scope.row.roleName }}</el-tag>
            </template>
          </el-table-column>

          <!-- 角色键 -->
          <el-table-column label="角色键" width="90" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span class="role-key">{{ scope.row.roleKey }}</span>
            </template>
          </el-table-column>

          <!-- 申请类型 -->
          <el-table-column label="类型" width="80" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.applyType === '1' ? 'success' : 'warning'" size="small">
                {{ scope.row.applyType === '1' ? '授权' : '取消' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 申请人姓名 -->
          <el-table-column label="申请人" width="90" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span class="apply-user-name">{{ scope.row.applyUserName }}</span>
            </template>
          </el-table-column>

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

          <!-- 申请状态 -->
          <el-table-column label="状态" align="center" width="80">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                {{ getStatusShortName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 申请时间 -->
          <el-table-column label="申请时间" align="center" width="140" sortable prop="applyTime"> </el-table-column>

          <!-- 审核人 -->
          <el-table-column label="审核人" width="90" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.approveUserName" class="approve-user">{{ scope.row.approveUserName }}</span>
              <span v-else class="no-approve">-</span>
            </template>
          </el-table-column>

          <!-- 审核时间 -->
          <el-table-column label="审核时间" align="center" width="140"> </el-table-column>

          <!-- 审批意见 -->
          <el-table-column label="审批意见" width="120" show-overflow-tooltip>
            <template #default="scope">
              <div v-if="scope.row.approveRemark" class="approve-remark">
                {{ scope.row.approveRemark }}
              </div>
              <span v-else class="no-remark">-</span>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" fixed="right" width="140" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <!-- 审批操作（仅待审核状态） -->
                <template v-if="scope.row.status === '0'">
                  <el-button v-hasPermi="['system:roleauth:approve']" link type="success" size="small" @click="handleApprove(scope.row, true)">
                    通过
                  </el-button>
                  <el-button v-hasPermi="['system:roleauth:approve']" link type="danger" size="small" @click="handleApprove(scope.row, false)">
                    拒绝
                  </el-button>
                </template>

                <!-- 撤销操作（仅本人申请且待审核状态） -->
                <el-button
                  v-if="canCancel(scope.row)"
                  v-hasPermi="['system:roleauth:cancel']"
                  link
                  type="warning"
                  size="small"
                  @click="handleCancel(scope.row)"
                >
                  撤销
                </el-button>

                <!-- 删除操作（仅限已处理的申请） -->
                <!-- <el-button
                  v-if="canDelete(scope.row)"
                  v-hasPermi="['system:roleauth: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>

    <!-- 批量审批对话框 -->
    <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 {
  batchApproveRoleAuthRequest,
  batchCancelRoleAuthRequest,
  batchDeleteRoleAuthRequest,
  listRoleAuthRequests,
  RoleAuthBatchApprovalForm,
  RoleAuthRequestQuery,
  RoleAuthRequestStatus,
  RoleAuthRequestVO
} from '@/api/system/approval/roleAuthRequest';
import { getUserProfile } from '@/api/system/user';

// ======================== 基础设置 ========================
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_project_role_category } = toRefs<any>(proxy?.useDict('sys_project_role_category'));

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

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

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

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

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

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

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

const canBatchCancel = computed(() => {
  return selectedRows.value.every((row) => row.status === RoleAuthRequestStatus.PENDING && row.isSelfApply);
});

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

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

const batchApprovalAlertTitle = computed(() => {
  const action = batchApprovalForm.approve ? '通过' : '拒绝';
  return `确认${action}选中的 ${batchApprovalForm.ids.length} 个角色授权申请吗？`;
});

// ======================== 工具方法 ========================
const formatDateTime = (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 => {
  const statusTypes = {
    '0': 'warning', // 待审核
    '1': 'success', // 已通过
    '2': 'danger', // 已拒绝
    '3': 'info' // 已撤销
  };
  return statusTypes[status] || '';
};

const getStatusShortName = (status: string): string => {
  const statusNames = {
    '0': '待审',
    '1': '通过',
    '2': '拒绝',
    '3': '撤销'
  };
  return statusNames[status] || '';
};

const canCancel = (request: RoleAuthRequestVO): boolean => {
  return request.status === RoleAuthRequestStatus.PENDING && request.isSelfApply;
};

const canDelete = (request: RoleAuthRequestVO): boolean => {
  return request.status !== RoleAuthRequestStatus.PENDING;
};

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

    const res = await listRoleAuthRequests(params);
    roleAuthRequestList.value = res.rows;
    total.value = res.total;

    // 统计待审核数量
    pendingCount.value = roleAuthRequestList.value.filter((item) => item.status === RoleAuthRequestStatus.PENDING).length;
  } 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: RoleAuthRequestVO[]) => {
  selectedRows.value = selection;
};

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

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

// 单个审批
const handleApprove = async (row: RoleAuthRequestVO, 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: RoleAuthBatchApprovalForm = {
      ids: [row.id],
      approve,
      approveRemark
    };
    await batchApproveRoleAuthRequest(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) => row.id);
  batchApprovalForm.approve = approve;
  batchApprovalForm.approveRemark = '';
  batchApprovalVisible.value = true;
};

// 提交批量审批
const submitBatchApproval = async () => {
  try {
    batchApprovalLoading.value = true;
    await batchApproveRoleAuthRequest(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 handleCancel = async (row: RoleAuthRequestVO) => {
  try {
    await proxy?.$modal.confirm(`确认撤销该申请吗？撤销后申请状态将变更为已撤销。`);
    await batchCancelRoleAuthRequest([row.id]);
    ElMessage.success('申请撤销成功');
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('撤销操作失败');
    }
  }
};

// 批量撤销
const handleBatchCancel = async () => {
  try {
    const ids = selectedRows.value.map((row) => row.id);
    await proxy?.$modal.confirm(`是否确认撤销选中的 ${ids.length} 个申请？撤销后申请状态将变更为已撤销。`);
    await batchCancelRoleAuthRequest(ids);
    ElMessage.success(`批量撤销成功，共撤销 ${ids.length} 个申请`);
    selectedRows.value = [];
    tableRef.value?.clearSelection();
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('批量撤销操作失败');
    }
  }
};

// 删除申请
const handleDelete = async (row: RoleAuthRequestVO) => {
  try {
    await proxy?.$modal.confirm(`是否确认删除该申请记录？删除后不可恢复。`);
    await batchDeleteRoleAuthRequest([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 batchDeleteRoleAuthRequest(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>
.role-auth-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;

  .pending-count {
    color: #e6a23c;
    font-weight: 600;
  }
}

.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;
}

// 基础文本样式
.real-name {
  font-size: 12px;
  color: #303133;
  font-weight: 500;
}

.dept-name {
  font-size: 12px;
  color: #606266;
}

.role-key {
  font-family: monospace;
  font-size: 12px;
  color: #606266;
}

.apply-user-name {
  font-size: 12px;
  font-weight: 500;
}

.approve-user {
  font-size: 12px;
  font-weight: 500;
}

.not-self {
  color: #c0c4cc;
  font-size: 12px;
}

// 时间文本样式
.time-text {
  font-size: 12px;
  color: #303133;
}

// 申请原因样式
.reason-text {
  font-size: 12px;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

// 审批意见样式
.approve-remark {
  font-size: 12px;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-approve,
.no-remark {
  color: #c0c4cc;
  font-style: italic;
  font-size: 12px;
}

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

// 紧凑表格全局样式
:deep(.el-table) {
  .el-table__cell {
    padding: 6px 0 !important;
  }

  .el-tag {
    margin: 0;
  }

  .el-button + .el-button {
    margin-left: 4px;
  }
}

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

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

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

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

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

.ml-3 {
  margin-left: 12px;
}

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

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

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

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

  .action-buttons {
    flex-direction: column;
    align-items: center;
    gap: 1px;
  }

  // 移动端表格进一步紧凑
  :deep(.el-table) {
    .el-table__cell {
      padding: 4px 0 !important;
      font-size: 12px;
    }

    .el-tag {
      font-size: 11px;
      height: 20px;
      line-height: 18px;
    }
  }

  .real-name,
  .dept-name,
  .role-key,
  .apply-user-name,
  .approve-user {
    font-size: 11px;
  }
}
</style>
