<template>
  <div class="user-approval-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="申请时间">
            <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 type="success" size="small" icon="Check" @click="handleBatchApprove"> 批量审批通过 </el-button>
          </template>
        </el-alert>
      </div>

      <!-- 数据表格 - 多列展示 -->
      <div class="table-section">
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="approvalList"
          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="部门" align="center" width="150" prop="deptName" show-overflow-tooltip /> -->

          <!-- 用户名 -->
          <el-table-column label="用户名" align="center" width="120">
            <template #default="scope">
              <div class="username-cell">
                <el-tag type="primary" size="small">{{ scope.row.userName }}</el-tag>
                <div v-if="getApplicationDays(scope.row.createTime) > 7" class="warning-text">{{ getApplicationDays(scope.row.createTime) }}天前</div>
              </div>
            </template>
          </el-table-column>

          <!-- 用户昵称 -->
          <el-table-column label="用户昵称" align="center" width="100" prop="nickName" show-overflow-tooltip />

          <!-- 角色类型 -->
          <el-table-column label="角色类型" align="center" width="120">
            <template #default="scope">
              <el-tag type="primary" size="small">
                {{ scope.row.roleTypeName || '未设置' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 渠道类型 -->
          <el-table-column label="渠道类型" align="center" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.branchTypeName" type="warning" size="small">
                {{ scope.row.branchTypeName }}
              </el-tag>
              <span v-else class="text-muted">未设置</span>
            </template>
          </el-table-column>

          <!-- 账户类型 -->
          <el-table-column label="账户类型" align="center" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.accType === 0 ? 'success' : 'warning'" size="small">
                {{ scope.row.accTypeName || (scope.row.accType === 0 ? '长期' : '临时') }}
              </el-tag>
            </template>
          </el-table-column>

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

          <!-- 操作列 -->
          <el-table-column label="操作" fixed="right" width="120" align="center">
            <template #default="scope">
              <el-button type="success" link icon="Check" @click="handleViewDetail(scope.row)"> 审批 </el-button>
            </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="批量审批确认" width="800px" :close-on-click-modal="false" @closed="resetBatchApprovalForm">
      <div class="batch-approval-content">
        <el-alert
          :title="`确认审批通过选中的 ${pendingBatchUsers.length} 个用户吗？审批通过后用户状态将变为激活状态。`"
          type="warning"
          :closable="false"
          show-icon
          class="mb-4"
        />

        <!-- 批量审批用户列表 -->
        <div class="batch-user-info">
          <h4>批量审批用户列表</h4>
          <el-table :data="pendingBatchUsers" size="small" max-height="350" border>
            <el-table-column label="序号" type="index" width="60" align="center" />
            <el-table-column label="用户名" prop="userName" width="120" align="center" />
            <el-table-column label="真实姓名" prop="realName" width="100" align="center" />
            <el-table-column label="部门" prop="deptName" width="150" show-overflow-tooltip />
            <el-table-column label="角色类型" width="120" align="center">
              <template #default="scope">
                <el-tag type="primary" size="small">
                  {{ scope.row.roleTypeName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="渠道" width="100" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.branchTypeName" type="warning" size="small">
                  {{ scope.row.branchTypeName }}
                </el-tag>
                <span v-else class="text-muted">未设置</span>
              </template>
            </el-table-column>
            <el-table-column label="账户类型" width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.accType === 0 ? 'success' : 'warning'" size="small">
                  {{ scope.row.accType === 0 ? '长期' : '临时' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 审批意见输入 -->
        <div class="approval-remark-section">
          <el-divider content-position="left">审批意见</el-divider>
          <el-input
            v-model="batchApprovalForm.approvalRemark"
            type="textarea"
            placeholder="请输入审批意见（可选）"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchApprovalVisible = false">取 消</el-button>
          <el-button type="success" :loading="batchApprovalLoading" @click="submitBatchApproval">
            <el-icon><Check /></el-icon>
            确认批量审批通过
          </el-button>
        </div>
      </template>
    </el-dialog>

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

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Check } from '@element-plus/icons-vue';
import { batchApproveUsers, getApprovalUserDetail, listPendingUsers } from '@/api/system/approval/userApproval';
import { SysUserApprovalListVo, UserApprovalDetailVO, UserApprovalQuery } from '@/api/system/approval/types';
import Pagination from '@/components/Pagination/index.vue';
import { getUserProfile } from '@/api/system/user';

// 导入用户详情组件
import UserDetailDrawer from './components/UserDetailDrawer.vue';

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

// ======================== 响应式数据 ========================
const loading = ref(true);
const approvalList = ref<SysUserApprovalListVo[]>([]);
const total = ref(0);
const dateRange = ref<[string, string]>(['', '']);
const selectedRows = ref<SysUserApprovalListVo[]>([]);
// 用户信息
const userInfo = reactive<Partial<UserVO>>({});

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

// 查询参数
const queryParams = reactive<UserApprovalQuery>({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  deptId: '',
  status: '2' // 固定查询待激活状态
});

// 批量审批相关状态
const batchApprovalVisible = ref(false);
const batchApprovalLoading = ref(false);
const pendingBatchUsers = ref<SysUserApprovalListVo[]>([]);

// 批量审批表单
const batchApprovalForm = reactive({
  approvalRemark: ''
});

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

// ======================== 工具方法 ========================
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 getApplicationDays = (createTime: Date | number): number => {
  const now = new Date();
  const create = new Date(createTime);
  return Math.floor((now.getTime() - create.getTime()) / (1000 * 60 * 60 * 24));
};

// 脱敏手机号
const getMaskedPhone = (phone: string): string => {
  if (!phone || phone.length !== 11) return phone;
  return phone.substring(0, 3) + '****' + phone.substring(7);
};

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

    const res = await listPendingUsers(params);
    approvalList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    proxy?.$modal.msgError('获取待审批用户失败');
  } finally {
    loading.value = false;
  }
};

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

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

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

// 批量审批
const handleBatchApprove = () => {
  if (selectedRows.value.length === 0) {
    proxy?.$modal.msgWarning('请先选择要审批的用户');
    return;
  }
  pendingBatchUsers.value = [...selectedRows.value];
  batchApprovalForm.approvalRemark = '';
  batchApprovalVisible.value = true;
};

// 提交批量审批
const submitBatchApproval = async () => {
  try {
    batchApprovalLoading.value = true;
    const userIds = pendingBatchUsers.value.map((user) => user.userId.toString());
    await batchApproveUsers({
      userIds,
      approvalRemark: batchApprovalForm.approvalRemark
    });
    ElMessage.success(`批量审批成功，共审批 ${pendingBatchUsers.value.length} 个用户`);
    batchApprovalVisible.value = false;
    // 清空选择
    selectedRows.value = [];
    tableRef.value?.clearSelection();
    // 刷新列表
    await getList();
  } catch (error) {
    proxy?.$modal.msgError('批量审批操作失败');
  } finally {
    batchApprovalLoading.value = false;
  }
};

const resetBatchApprovalForm = () => {
  pendingBatchUsers.value = [];
  batchApprovalForm.approvalRemark = '';
};

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

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

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

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

<style lang="scss" scoped>
.user-approval-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;

  .warning-text {
    font-size: 11px;
    color: #e6a23c;
    margin-top: 2px;
    font-weight: 500;
  }
}

// 批量审批对话框
.batch-approval-content {
  h4 {
    margin: 0 0 16px 0;
    font-size: 16px;
    color: #374151;
    font-weight: 600;
  }

  .approval-remark-section {
    margin-top: 20px;
  }
}

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

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

.text-muted {
  color: #909399;
}

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

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

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

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