<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable @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>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:role:add']" type="primary" plain icon="Plus" @click="openSelectUser">添加用户</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:role:remove']"
              type="danger"
              plain
              icon="CircleClose"
              :disabled="multiple"
              :loading="cancelAuthLoading"
              @click="handleBatchApplyCancelAuth"
            >
              批量申请取消授权
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" :search="true" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="部门" prop="deptName" :show-overflow-tooltip="true" />
        <el-table-column label="用户名称" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" prop="nickName" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="申请取消授权" placement="top">
              <el-button
                v-hasPermi="['system:role:remove']"
                link
                type="primary"
                icon="CircleClose"
                :loading="cancelAuthLoading"
                @click="handleApplyCancelAuth(scope.row)"
              >
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      <select-user ref="selectRef" :role-id="queryParams.roleId" @ok="handleQuery" />
    </el-card>

    <!-- 申请取消授权对话框 -->
    <el-dialog v-model="cancelAuthDialogVisible" title="申请取消授权" width="500px" append-to-body>
      <el-form ref="cancelAuthFormRef" :model="cancelAuthForm" :rules="cancelAuthRules" label-width="100px">
        <el-form-item label="选中用户">
          <div class="selected-users">
            <el-tag v-for="user in selectedUsers" :key="user.userId" class="mr-1 mb-1">
              {{ user.userName }}({{ user.nickName }})
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="申请原因" prop="applyReason">
          <el-input
            v-model="cancelAuthForm.applyReason"
            type="textarea"
            placeholder="请输入申请取消授权的原因"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="proceedWithSecurityVerify">下一步（安全验证）</el-button>
          <el-button @click="cancelAuthDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 二次验证组件 -->
    <SecondVerify
      v-model:visible="secondVerifyVisible"
      :user-info="currentVerifyUser"
      :title="'申请取消用户授权安全验证'"
      :operation-type="'cancelAuthUser'"
      @verify-success="handleVerifySuccess"
      @verify-cancel="handleVerifyCancel"
    />
  </div>
</template>

<script setup name="AuthUser" lang="ts">
import { allocatedUserList } from '@/api/system/role';
import { UserQuery, UserVO, VerifyResult } from '@/api/system/user/types';
import { batchApplyRoleCancelAuth, RoleAuthBatchRequestForm } from '@/api/system/approval/roleAuthRequest';
import SelectUser from './selectUser.vue';
import SecondVerify from '@/views/system/user/secondVerify.vue';
import { RouteLocationNormalized } from 'vue-router';

const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const userList = ref<UserVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const multiple = ref(true);
const total = ref(0);
const userIds = ref<Array<string | number>>([]);
const selectedUsers = ref<UserVO[]>([]);

// 申请取消授权相关状态
const cancelAuthDialogVisible = ref(false);
const cancelAuthLoading = ref(false);

// 二次验证相关状态
const secondVerifyVisible = ref(false);
const currentVerifyUser = ref<Partial<UserVO>>({});

// 申请表单
const cancelAuthForm = reactive({
  applyReason: ''
});

// 表单验证规则
const cancelAuthRules = {
  applyReason: [{ required: true, message: '请输入申请原因', trigger: 'blur' }]
};

const queryFormRef = ref<ElFormInstance>();
const selectRef = ref<InstanceType<typeof SelectUser>>();
const cancelAuthFormRef = ref<ElFormInstance>();

const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  roleId: route.params.roleId as string,
  userName: undefined,
  phonenumber: undefined
});

/** 查询授权用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await allocatedUserList(queryParams);
  userList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

// 返回按钮
const handleClose = () => {
  const obj: RouteLocationNormalized = {
    path: '/system/role',
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined
  };
  proxy?.$tab.closeOpenPage(obj);
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection: UserVO[]) => {
  userIds.value = selection.map((item) => item.userId);
  selectedUsers.value = selection;
  multiple.value = !selection.length;
};

/** 打开授权用户表弹窗 */
const openSelectUser = () => {
  selectRef.value?.show();
};

/** 单个申请取消授权按钮操作 */
const handleApplyCancelAuth = async (row: UserVO) => {
  // 将单个用户设置为选中用户
  selectedUsers.value = [row];
  cancelAuthForm.applyReason = '';
  cancelAuthDialogVisible.value = true;
};

/** 批量申请取消授权按钮操作 */
const handleBatchApplyCancelAuth = async () => {
  if (userIds.value.length === 0) {
    proxy?.$modal.msgWarning('请选择要申请取消授权的用户');
    return;
  }

  // 使用表格选中的用户
  cancelAuthForm.applyReason = '';
  cancelAuthDialogVisible.value = true;
};

/** 进行安全验证前的准备 */
const proceedWithSecurityVerify = async () => {
  if (!cancelAuthFormRef.value) return;

  const formValid = await cancelAuthFormRef.value.validate();
  if (!formValid) return;

  // 设置二次验证用户信息（使用当前登录用户信息）
  currentVerifyUser.value = {
    userId: 'current',
    userName: '当前用户'
  };

  // 关闭申请对话框，显示二次验证对话框
  cancelAuthDialogVisible.value = false;
  secondVerifyVisible.value = true;
};

/** 二次验证成功处理 */
const handleVerifySuccess = async (result: VerifyResult): Promise<void> => {
  if (!result.success) return;

  try {
    await executeApplyCancelAuth();
  } finally {
    handleVerifyCancel();
  }
};

/** 执行申请取消授权 */
const executeApplyCancelAuth = async (): Promise<void> => {
  try {
    cancelAuthLoading.value = true;

    // 构建批量申请数据
    const batchRequestData: RoleAuthBatchRequestForm = {
      userIds: selectedUsers.value.map((user: UserVO) => user.userId),
      roleId: queryParams.roleId as string,
      applyReason: cancelAuthForm.applyReason
    };

    await batchApplyRoleCancelAuth(batchRequestData);

    const message = selectedUsers.value.length === 1
      ? '申请取消授权提交成功，请等待审批'
      : `批量申请取消授权提交成功，共提交 ${selectedUsers.value.length} 个申请，请等待审批`;

    proxy?.$modal.msgSuccess(message);
    getList();
  } catch (error) {
    proxy?.$modal.msgError('申请取消授权失败，请重试');
  } finally {
    cancelAuthLoading.value = false;
  }
};

/** 二次验证取消处理 */
const handleVerifyCancel = (): void => {
  secondVerifyVisible.value = false;
  currentVerifyUser.value = {};
  selectedUsers.value = [];
  cancelAuthForm.applyReason = '';
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.selected-users {
  max-height: 120px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
  background-color: #f5f7fa;
}

.mr-1 {
  margin-right: 0.25rem;
}
.mb-1 {
  margin-bottom: 0.25rem;
}
</style>
