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

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

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

// 从 record.block_modules 中提取被阻止的模块
function loadBlockedModules() {
  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() {
  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 all modules:', e)
  }
  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
      })
    }
  })
}

// Copy From: 从源配置复制模块阻止列表
const copyFromValue = ref('')

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

async function loadModulesFromProfile(sourceName: string) {
  if (!sourceName) return
  try {
    const res = await getRecord('Module Profile', sourceName)
    if (res.success) {
      const sourceModules = Array.isArray(res.data?.block_modules) ? res.data.block_modules : []
      blockedModules.value = sourceModules.map((m: any) => m.module).filter(Boolean)
      selectAllModules.value = blockedModules.value.length === 0
      updateModulesInRecord()
    }
  } catch (e) {
    console.error('Failed to copy modules:', e)
  }
}

onMounted(() => {
  loadAllModules()
})
</script>

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

    <div class="editor-header">
      <n-checkbox
        v-model:checked="selectAllModules"
        @update:checked="toggleSelectAllModules"
        :disabled="!canEdit"
      >
        {{ 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="!canEdit"
        >
          {{ ctx.t(module) }}
        </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%;
}

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