<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { NCheckbox } from 'naive-ui'
import { api, getRecord } from '@/shared/api/common'
import { usePermissionStore } from '@/shared/stores/permissions'
import LinkField from '@/shared/components/LinkField.vue'

const props = defineProps<{ df: any; record: Record<string, any>; canEdit: boolean; ctx: any }>()

const permissionStore = usePermissionStore()

// ======= 角色编辑器 =======
const canEditRoles = ref(false)
const allRoles = ref<string[]>([])
const selectedRoles = ref<string[]>([])
const selectAllRoles = ref(false)

function loadSelectedRoles() {
  const roles = Array.isArray(props.record?.roles) ? props.record.roles : []
  selectedRoles.value = roles.map((r: any) => r.role).filter(Boolean)
}

async function loadAllRoles() {
  try {
    const res = await api.call('jingrow.core.pagetype.user.user.get_all_roles')
    allRoles.value = res.message || []
    loadSelectedRoles()
    selectAllRoles.value = selectedRoles.value.length === allRoles.value.length
  } catch (e) {
    console.error('Failed to load roles:', e)
  }
}

function toggleSelectAllRoles() {
  selectedRoles.value = selectAllRoles.value ? [...allRoles.value] : []
  updateRolesInRecord()
}

function onRoleChange(role: string, checked: boolean) {
  if (checked) {
    if (!selectedRoles.value.includes(role)) selectedRoles.value.push(role)
  } else {
    selectedRoles.value = selectedRoles.value.filter(r => r !== role)
  }
  selectAllRoles.value = selectedRoles.value.length === allRoles.value.length
  updateRolesInRecord()
}

function updateRolesInRecord() {
  if (!props.record) return
  const existingRoles = Array.isArray(props.record.roles) ? props.record.roles : []
  const existingRoleNames = existingRoles.map((r: any) => r.role)
  // 移除未选中 + 添加新选中
  props.record.roles = existingRoles.filter((r: any) => selectedRoles.value.includes(r.role))
  selectedRoles.value.forEach(role => {
    if (!existingRoleNames.includes(role)) {
      props.record.roles.push({ pagetype: 'Has Role', role, __islocal: 1 })
    }
  })
}

// Copy From: 从源配置复制角色列表（纯前端，选中即触发）
const copyFromValue = ref('')

function onCopyFromChange(value: string) {
  if (!value) return
  loadRolesFromProfile(value)
}

async function loadRolesFromProfile(sourceName: string) {
  if (!sourceName) return
  try {
    const res = await getRecord('Role Profile', sourceName)
    if (res.success && res.data?.roles) {
      const sourceRoles = Array.isArray(res.data.roles) ? res.data.roles : []
      selectedRoles.value = sourceRoles.map((r: any) => r.role).filter(Boolean)
      selectAllRoles.value = selectedRoles.value.length === allRoles.value.length
      updateRolesInRecord()
    }
  } catch (e) {
    console.error('Failed to copy roles:', e)
  }
}

onMounted(async () => {
  try {
    canEditRoles.value = await permissionStore.hasPermlevelAccess('Role Profile', 1, 'write')
  } catch {
    canEditRoles.value = false
  }
  loadAllRoles()
})
</script>

<template>
  <div v-if="canEditRoles" class="roles-editor">
    <div class="copy-from-field">
      <LinkField
        v-model="copyFromValue"
        :options="'Role Profile'"
        :label="ctx.t('Copy From')"
        :enable-create="false"
        @update:model-value="onCopyFromChange"
      />
    </div>

    <div class="editor-header">
      <n-checkbox
        v-model:checked="selectAllRoles"
        @update:checked="toggleSelectAllRoles"
        :disabled="!canEditRoles"
      >
        {{ ctx.t('Select All') }}
      </n-checkbox>
    </div>

    <div class="checkbox-grid">
      <div
        v-for="role in allRoles"
        :key="role"
        class="checkbox-item"
      >
        <n-checkbox
          :checked="selectedRoles.includes(role)"
          @update:checked="(checked) => onRoleChange(role, checked)"
          :disabled="!canEditRoles"
        >
          {{ ctx.t(role) }}
        </n-checkbox>
      </div>
    </div>
  </div>
</template>

<style scoped>

.copy-from-field {
  margin-bottom: 30px;
}

.copy-from-field :deep(.link-field) {
  width: 100%;
}

.copy-from-field :deep(.link-field .n-input) {
  --n-height: 34px;
  font-size: 14px;
}

.copy-from-field :deep(.link-field .dropdown-menu) {
  width: 100%;
}

.editor-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e0e0e6;
}

.checkbox-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
  gap: 8px 16px;
}

.checkbox-item {
  padding: 4px 0;
}
</style>
