<template>
  <el-row>
    <el-dialog v-model="visible" title="选择用户" width="800px" top="5vh" append-to-body>
      <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>
      <el-row>
        <el-table ref="tableRef" :data="userList" height="260px" @row-click="clickRow" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <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>{{ proxy.parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-if="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="submitLoading" @click="handleSelectUser">确 定</el-button>
          <el-button @click="visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 申请授权对话框 -->
    <el-dialog v-model="authDialogVisible" title="批量申请用户授权" width="600px" append-to-body>
      <el-form ref="authFormRef" :model="authForm" :rules="authRules" 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="authForm.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="authDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

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

<script setup name="SelectUser" lang="ts">
import { unallocatedUserList } from '@/api/system/role';
import { UserQuery, UserVO, VerifyResult } from '@/api/system/user/types';
import { batchApplyRoleAuth, RoleAuthBatchRequestForm } from '@/api/system/approval/roleAuthRequest';
import SecondVerify from '@/views/system/user/secondVerify.vue';
import { getUserProfile } from '@/api/system/user';

const props = defineProps({
  roleId: {
    type: [Number, String],
    required: true
  }
});

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

const userList = ref<UserVO[]>([]);
const visible = ref(false);
const total = ref(0);
const userIds = ref<Array<string | number>>([]);
const selectedUsers = ref<UserVO[]>([]);

// 申请授权相关状态
const authDialogVisible = ref(false);
const submitLoading = ref(false);

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

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

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

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

const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  roleId: undefined,
  userName: undefined,
  phonenumber: undefined,
  deptId: undefined
});

const tableRef = ref<ElTableInstance>();
const queryFormRef = ref<ElFormInstance>();
const authFormRef = ref<ElFormInstance>();

const show = async () => {
  await getUserInfo();
  queryParams.roleId = props.roleId;
  await getList();
  visible.value = true;
};

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

/**
 * 选择行
 */
const clickRow = (row: any) => {
  // ele的bug
  tableRef.value?.toggleRowSelection(row, false);
};

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

/** 查询数据 */
const getList = async () => {
  const res = await unallocatedUserList(queryParams);
  userList.value = res.rows;
  total.value = res.total;
};

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

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

const emit = defineEmits(['ok']);

/** 选择授权用户操作 - 打开申请对话框 */
const handleSelectUser = async () => {
  if (userIds.value.length === 0) {
    proxy?.$modal.msgError('请选择要分配的用户');
    return;
  }

  // 重置申请表单
  authForm.applyReason = '';

  // 显示申请对话框
  authDialogVisible.value = true;
};

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

  const valid = await authFormRef.value.validate();
  if (!valid) return;

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

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

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

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

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

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

    // 调用批量申请接口
    await batchApplyRoleAuth(batchRequestData);

    proxy?.$modal.msgSuccess('批量申请用户授权提交成功，请等待审批');
    emit('ok');
    visible.value = false;
  } catch (error) {
    proxy?.$modal.msgError('批量申请用户授权失败，请重试');
  } finally {
    submitLoading.value = false;
  }
};

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

// 暴露
defineExpose({
  show
});
</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>
