<template>
  <el-dialog
    v-model="visible"
    title="角色切换"
    width="50%"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleBeforeClose"
  >
    <el-form>
<!--      <el-form-item label="学校">-->
<!--        <el-tag>{{schoolName}}</el-tag>-->
<!--      </el-form-item>-->
      <el-form-item label="角色" class="role-form-item">
        <el-radio-group v-model="radio" class="role-radio-group" @change="handleChangeRole">
          <el-radio-button
            v-for="item in allRole"
            :key="item.roleCode"
            :label="item.roleCode"
          >
            {{ item.roleName }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>


    <template #footer>
      <!--      <el-button type="primary" @click="handleChangeRole">切换</el-button>-->
      <el-button @click="handleFooterClose">关 闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { listAllRole } from '/@/api/admin/role'
import { Local } from '/@/utils/storage'
import { useMessage } from '/@/hooks/message'

const visible = ref(false)
const radio = ref('')
const allRole = reactive<any[]>([])

const open = () => {
  visible.value = true
  listAllRole().then((res) => {
    Object.assign(allRole, res.data)
    radio.value = Local.get('roleCode')
    visible.value = true
  })
}

const canClose = () => {
  if (!radio.value) {
    useMessage().warning('请选择一个角色')
    return false
  }
  return true
}

const handleBeforeClose = (done: () => void) => {
  if (!canClose()) return
  done()
}

const handleFooterClose = () => {
  if (!canClose()) return
  visible.value = false
}

const handleChangeRole = (label: string) => {
  const obj = allRole.find((v: any) => v.roleCode === label)
  if (!obj) return
  Local.set('roleCode', obj.roleCode)
  Local.set('roleName', obj.roleName)
  Local.set('roleId', obj.roleId)
  useMessage().success('操作成功')
  setTimeout(() => {
    // 切换角色后统一回到首页，避免停留在诸如 jsonflow/run-job/do-job 等内部路由
    window.location.hash = '#/'
    window.location.reload()
  }, 500)
}

defineExpose({
  open
})
</script>

<style scoped lang="scss">
.role-form-item {
  :deep(.el-form-item__content) {
    flex-wrap: wrap;
  }
}
.role-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  /* 每个按钮独立边框，换行后左侧也有边线 */
  :deep(.el-radio-button) {
    margin: 0;
  }
  :deep(.el-radio-button__inner) {
    border-radius: 6px !important;
    border: 1px solid var(--el-border-color) !important;
    margin-left: 0 !important;
  }
  :deep(.el-radio-button.is-active .el-radio-button__inner) {
    border-color: var(--el-color-primary) !important;
  }
}
</style>