<template>
  <Dialog v-model="dialogVisible" title="web端角色菜单权限配置" width="800">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="角色名称">
            <el-tag>{{ formData.name }}</el-tag>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色标识">
            <el-tag>{{ formData.code }}</el-tag>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">web路由数据权限</el-divider>
      <br/>

      <!-- 字典数据选择 -->
      <el-form-item label="路由类型">
        <el-checkbox-group v-model="formData.dataScopeWebRoute" size="large">
          <el-checkbox-button v-for="dict in routeTypeOptions" :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>

      <!-- Web菜单权限 -->
      <el-form-item label="Web菜单权限">
        <el-select
          v-model="formData.dataScopeWebMenuRoute"
          class="!w-full"
          clearable
          multiple
          filterable
          placeholder="请选择Web菜单权限"
          value-key="value"
          collapse-tags-tooltip
        >
          <template #header>
            <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
          </template>
          <el-option
            v-for="dict in webMenuRouteOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import * as RoleApi from '@/api/system/role'
import * as PermissionApi from '@/api/system/permission'

defineOptions({ name: 'SystemRoleWebMenuPermissionForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const routeTypeOptions = ref(getDictOptions(DICT_TYPE.WEB_ROLE_ROUTE)) // 路由类型字典选项
const webMenuRouteOptions = ref(getDictOptions('web_course_menu_route')) // Web菜单权限字典选项
const selectAll = ref(false) // 全选状态
const formData = reactive({
  id: undefined,
  name: '',
  code: '',
  dataScopeWebRoute: [],
  dataScopeWebMenuRoute: []
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (row: RoleApi.RoleVO) => {
  dialogVisible.value = true
  resetForm()

  // 设置数据
  formData.id = row.id
  formData.name = row.name
  formData.code = row.code
  formData.dataScopeWebRoute = row.dataScopeWebRoute || []
  formData.dataScopeWebMenuRoute = row.dataScopeWebCourseMenuRoute || []
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  formLoading.value = true
  try {
    const data: any = {
      roleId: formData.id,
      dataScopeWebRoute: formData.dataScopeWebRoute,
      dataScopeWebMenuRoute: formData.dataScopeWebMenuRoute
    }

    console.log('提交的数据:', data)
    await PermissionApi.assignRoleWebMenuScope(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  // 重置表单数据
  formData.id = undefined
  formData.name = ''
  formData.code = ''
  formData.dataScopeWebRoute = []
  formData.dataScopeWebMenuRoute = []
  selectAll.value = false

  formRef.value?.resetFields()
}

/** 处理全选 */
const handleSelectAll = (val: boolean) => {
  if (val) {
    // 全选：将所有选项的 value 添加到 dataScopeWebMenuRoute
    formData.dataScopeWebMenuRoute = webMenuRouteOptions.value.map(option => option.value)
  } else {
    // 取消全选：清空 dataScopeWebMenuRoute
    formData.dataScopeWebMenuRoute = []
  }
}
</script>
