<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue'
import { NCheckbox, NButton, NModal, NScrollbar } from 'naive-ui'
import { api } from '@/shared/api/common'
import { usePermissionStore } from '@/shared/stores/permissions'

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

const permissionStore = usePermissionStore()

// Label布局
const labelLayout = computed(() => props.df.label_layout || 'vertical')

// 判断是哪个HTML字段
const isRolesHtml = computed(() => props.df.fieldname === 'roles_html')
const isModulesHtml = computed(() => props.df.fieldname === 'modules_html')

// Check if user has permlevel 1 write access
const hasPermlevel1Write = ref(false)

// 对于roles_html和modules_html，需要检查permlevel 1权限
// 因为这些字段用于编辑受保护的角色和模块信息
const actualCanEdit = computed(() => {
  if (isRolesHtml.value || isModulesHtml.value) {
    // 需要 permlevel 1 write 权限才能编辑角色/模块
    // Administrator总是可以编辑
    return hasPermlevel1Write.value
  }
  // 其他HTML字段遵循标准逻辑
  return props.canEdit && !props.df.read_only
})

// 对于roles_html和modules_html，即使没有编辑权限，也应该显示（只读）
const shouldShowEditor = computed(() => {
  if (isRolesHtml.value || isModulesHtml.value) {
    // 只有有 permlevel 1 read 权限才显示编辑器（可能只读）
    return hasPermlevel1Write.value // For simplicity, only show if can write
  }
  return true
})

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

// 从 record.roles 中提取已选中的角色
function loadSelectedRoles() {
  if (!props.record?.roles) return
  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() {
  if (selectAllRoles.value) {
    selectedRoles.value = [...allRoles.value]
  } else {
    selectedRoles.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()
}

// 更新 record.roles
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: role,
        __islocal: 1
      })
    }
  })
}

// 显示角色权限
const showPermDialog = ref(false)
const permDialogTitle = ref('')
const permDialogData = ref<any[]>([])
const permRights = ['select', 'read', 'write', 'create', 'delete', 'submit', 'cancel', 'amend', 'print', 'email', 'report', 'import', 'export', 'share']

async function showRolePermissions(role: string) {
  try {
    const res = await api.call('jingrow.core.pagetype.user.user.get_perm_info', { role })
    permDialogTitle.value = props.ctx.t(role)
    permDialogData.value = res.message || []
    showPermDialog.value = true
  } catch (e) {
    console.error('Failed to load permissions:', e)
  }
}

// ======= 模块编辑器 =======
const allModules = ref<string[]>([])
const blockedModules = ref<string[]>([])
const selectAllModules = ref(false)

// 从 record.block_modules 中提取被阻止的模块
function loadBlockedModules() {
  if (!props.record?.block_modules) return
  const modules = Array.isArray(props.record.block_modules) ? props.record.block_modules : []
  blockedModules.value = modules.map((m: any) => m.module).filter(Boolean)
}

// 加载所有可用模块
async function loadAllModules() {
  // 优先从 __onload 获取（编辑已有记录时），否则通过 API 获取（新建记录时）
  const onloadModules = props.record?.__onload?.all_modules
  if (Array.isArray(onloadModules) && onloadModules.length > 0) {
    allModules.value = onloadModules
  } else {
    try {
      const res = await api.call('jingrow.core.pagetype.module_profile.module_profile.get_all_modules')
      allModules.value = res.message || []
    } catch (e) {
      console.error('Failed to load modules:', e)
      allModules.value = []
    }
  }
  
  loadBlockedModules()
  // 更新全选状态：如果没有被阻止的模块，则为全选状态
  selectAllModules.value = blockedModules.value.length === 0
}

// 模块是否被选中（未被阻止）
function isModuleSelected(module: string) {
  return !blockedModules.value.includes(module)
}

// 全选/取消全选模块
function toggleSelectAllModules() {
  if (selectAllModules.value) {
    blockedModules.value = []
  } else {
    blockedModules.value = [...allModules.value]
  }
  updateModulesInRecord()
}

// 单个模块选择变化
function onModuleChange(module: string, checked: boolean) {
  if (checked) {
    // 选中模块 = 从阻止列表中移除
    blockedModules.value = blockedModules.value.filter(m => m !== module)
  } else {
    // 取消选中 = 添加到阻止列表
    if (!blockedModules.value.includes(module)) {
      blockedModules.value.push(module)
    }
  }
  selectAllModules.value = blockedModules.value.length === 0
  updateModulesInRecord()
}

// 更新 record.block_modules
function updateModulesInRecord() {
  if (!props.record) return
  
  const existingModules = Array.isArray(props.record.block_modules) ? props.record.block_modules : []
  const existingModuleNames = existingModules.map((m: any) => m.module)
  
  // 移除不再阻止的模块
  props.record.block_modules = existingModules.filter((m: any) => blockedModules.value.includes(m.module))
  
  // 添加新阻止的模块
  blockedModules.value.forEach(module => {
    if (!existingModuleNames.includes(module)) {
      props.record.block_modules.push({
        pagetype: 'Block Module',
        module: module,
        __islocal: 1
      })
    }
  })
}

// ======= Role Profile 自动加载 =======
// 当用户选择 Role Profile 后，自动从 profile 加载角色到编辑器
async function loadRolesFromProfile(profileName: string) {
  if (!profileName) return
  try {
    const res = await api.call('jingrow.core.pagetype.user.user.get_role_profile', { role_profile: profileName })
    const profileRoles = Array.isArray(res.message) ? res.message : []
    selectedRoles.value = profileRoles.map((r: any) => r.role).filter(Boolean)
    selectAllRoles.value = selectedRoles.value.length === allRoles.value.length
    updateRolesInRecord()
  } catch (e) {
    console.error('Failed to load roles from profile:', e)
  }
}

// ======= Module Profile 自动加载 =======
// 当用户选择 Module Profile 后，自动从 profile 加载模块到编辑器
async function loadModulesFromProfile(profileName: string) {
  if (!profileName) return
  try {
    const res = await api.call('jingrow.core.pagetype.user.user.get_module_profile', { module_profile: profileName })
    const profileModules = Array.isArray(res.message) ? res.message : []
    blockedModules.value = profileModules.map((m: any) => m.module).filter(Boolean)
    selectAllModules.value = blockedModules.value.length === 0
    updateModulesInRecord()
  } catch (e) {
    console.error('Failed to load modules from profile:', e)
  }
}

// 监听 role_profile_name 变更，自动加载对应角色
watch(() => props.record?.role_profile_name, (newVal, oldVal) => {
  if (newVal && newVal !== oldVal && isRolesHtml.value) {
    loadRolesFromProfile(newVal)
  }
})

// 监听 module_profile 变更，自动加载对应模块
watch(() => props.record?.module_profile, (newVal, oldVal) => {
  if (newVal && newVal !== oldVal && isModulesHtml.value) {
    loadModulesFromProfile(newVal)
  }
})

// 初始化
onMounted(async () => {
  // Check permlevel 1 write access for roles/modules editing
  if (isRolesHtml.value || isModulesHtml.value) {
    try {
      hasPermlevel1Write.value = await permissionStore.hasPermlevelAccess('User', 1, 'write')
    } catch (error) {
      console.error('Failed to check permlevel access:', error)
      hasPermlevel1Write.value = false
    }
  }

  if (isRolesHtml.value) {
    loadAllRoles()
  } else if (isModulesHtml.value) {
    loadAllModules()
  }
})
</script>

<template>
  <!-- 角色编辑器 -->
  <div v-if="isRolesHtml && shouldShowEditor" class="roles-editor">
    <div class="editor-header">
      <n-checkbox 
        v-model:checked="selectAllRoles" 
        @update:checked="toggleSelectAllRoles"
        :disabled="!actualCanEdit"
      >
        {{ 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="!actualCanEdit"
        >
          <span class="role-label" @click.prevent="showRolePermissions(role)">
            {{ ctx.t(role) }}
          </span>
        </n-checkbox>
      </div>
    </div>
    
    <!-- 权限对话框 -->
    <n-modal
      v-model:show="showPermDialog"
      preset="card"
      :title="permDialogTitle"
      :style="{ width: '90%', maxWidth: '1200px' }"
    >
      <n-scrollbar style="max-height: 60vh">
        <div v-if="permDialogData.length === 0" class="empty-state">
          {{ ctx.t('{0} role does not have permission on any pagetype', [permDialogTitle]) }}
        </div>
        <table v-else class="perm-table">
          <thead>
            <tr>
              <th>{{ ctx.t('Document Type') }}</th>
              <th>{{ ctx.t('Level') }}</th>
              <th>{{ ctx.t('If Owner') }}</th>
              <th v-for="right in permRights" :key="right">{{ ctx.t(right) }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(perm, idx) in permDialogData" :key="idx">
              <td>{{ ctx.t(perm.parent) }}</td>
              <td>{{ perm.permlevel }}</td>
              <td class="text-center">{{ perm.if_owner ? '✓' : '-' }}</td>
              <td v-for="right in permRights" :key="right" class="text-center">
                {{ perm[right] ? '✓' : '-' }}
              </td>
            </tr>
          </tbody>
        </table>
      </n-scrollbar>
    </n-modal>
  </div>
  
  <!-- 模块编辑器 -->
  <div v-else-if="isModulesHtml && shouldShowEditor" class="modules-editor">
    <div class="editor-header">
      <n-checkbox 
        v-model:checked="selectAllModules" 
        @update:checked="toggleSelectAllModules"
        :disabled="!actualCanEdit"
      >
        {{ ctx.t('Select All') }}
      </n-checkbox>
    </div>
    
    <div class="checkbox-grid">
      <div 
        v-for="module in allModules" 
        :key="module" 
        class="checkbox-item"
      >
        <n-checkbox
          :checked="isModuleSelected(module)"
          @update:checked="(checked) => onModuleChange(module, checked)"
          :disabled="!actualCanEdit"
        >
          {{ ctx.t(module) }}
        </n-checkbox>
      </div>
    </div>
  </div>
  
  <!-- 普通HTML字段（兜底） -->
  <div v-else :class="['field-wrapper', `layout-${labelLayout}`]">
    <label class="field-label">
      {{ ctx.t(df.label || df.fieldname) }}
      <span v-if="df.reqd" class="required">*</span>
    </label>
    <div class="html-content" v-html="record[df.fieldname]"></div>
  </div>
</template>

<style scoped>
.roles-editor,
.modules-editor {
  padding: 16px 0;
}

.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;
}

.role-label {
  cursor: pointer;
  color: var(--primary-color, #1890ff);
  text-decoration: none;
}

.role-label:hover {
  text-decoration: underline;
}

.perm-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}

.perm-table th,
.perm-table td {
  padding: 8px 12px;
  border: 1px solid #e0e0e6;
  text-align: left;
}

.perm-table th {
  background: #f5f5f5;
  font-weight: 600;
}

.perm-table .text-center {
  text-align: center;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.field-wrapper {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-wrapper.layout-horizontal {
  flex-direction: row;
  align-items: flex-start;
}

.field-label {
  font-weight: 500;
  font-size: 13px;
  color: #333;
}

.field-label .required {
  color: #f56c6c;
  margin-left: 4px;
}

.html-content {
  flex: 1;
}
</style>
