<template>
  <div class="page-dev-create-template">
    <n-card :title="t('Create PageType Template Files')">
      <n-form :model="form" :rules="rules" ref="formRef" label-width="120">
        <n-form-item :label="t('PageType')" path="pagetype">
          <n-select v-model:value="form.pagetype" :options="pagetypeOptions" filterable clearable :loading="loading" :placeholder="t('Select PageType')" @update:show="onDropdownShow" @update:value="onPagetypeChange" />
        </n-form-item>
        <n-form-item :label="t('Create Frontend')">
          <n-switch v-model:value="form.createFrontend" @update:value="onFrontendToggle" />
        </n-form-item>
        <n-form-item v-if="form.createFrontend" label="" style="margin-top: 0;">
          <n-checkbox-group v-model:value="form.frontendOptions" @update:value="onFrontendOptionsChange">
            <n-space vertical>
              <n-checkbox value="toolbar" :label="t('Toolbar')" />
              <n-checkbox value="sidebar" :label="t('Sidebar')" />
              <div class="field-types-row">
                <n-checkbox value="field_types" :label="t('Field Types')" />
                <n-select 
                  v-if="form.frontendOptions.includes('field_types')" 
                  v-model:value="form.fieldTypeNames" 
                  :options="fieldTypeOptions" 
                  multiple 
                  filterable 
                  :placeholder="t('Select Field Types')"
                  style="width: 200px; margin-left: 16px;"
                  @update:value="updateFieldTypesPreview"
                />
              </div>
              <n-checkbox value="page" :label="t('Page')" />
            </n-space>
          </n-checkbox-group>
        </n-form-item>
        <n-form-item :label="t('Create Backend')">
          <n-switch v-model:value="form.createBackend" />
        </n-form-item>
        <n-form-item>
          <n-button type="primary" :loading="submitting" @click="handleSubmit">{{ t('Create') }}</n-button>
        </n-form-item>
        <n-form-item v-if="appName || moduleName" :label="t('Preview')">
          <div class="preview">
            <div v-if="form.createFrontend && frontendPath">
              <div><strong>{{ t('Frontend') }}:</strong></div>
              <pre class="path-preview">{{ frontendPath }}</pre>
            </div>
            <div v-if="form.createBackend && backendPath">{{ t('Backend') }}: {{ backendPath }}</div>
          </div>
        </n-form-item>
      </n-form>
      <div v-if="result" class="result">
        <div v-if="result.success">
          <p>{{ t('Created successfully') }}</p>
          <p v-if="result.frontend_path">Frontend: {{ result.frontend_path }}</p>
          <p v-if="result.backend_path">Backend: {{ result.backend_path }}</p>
        </div>
        <div v-else>
          <p style="color:#ef4444">{{ result.message }}</p>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { NCard, NForm, NFormItem, NSelect, NSwitch, NButton, NSpace, NCheckbox, NCheckboxGroup, useMessage, type FormInst, type FormRules } from 'naive-ui'
import axios from 'axios'
import { t } from '@/shared/i18n'

const message = useMessage()

const loading = ref(false)
const submitting = ref(false)
const result = ref<any>(null)
const formRef = ref<FormInst | null>(null)
const form = ref({ pagetype: '', createFrontend: false, createBackend: true, frontendOptions: ['toolbar'], fieldTypeNames: [] })
const pagetypeOptions = ref<{ label: string; value: string }[]>([])

// 可用的字段类型列表（从 /core/pagetype/form/controls 目录自动生成）
const fieldTypeOptions = ref<{ label: string; value: string }[]>([])
const appName = ref('')
const moduleName = ref('')

// 动态加载字段类型选项（从 /core/pagetype/form/controls 目录）
const loadFieldTypeOptions = () => {
  try {
    const modules = import.meta.glob('@/core/pagetype/form/controls/*.vue', { eager: true })
    const fileNames = Object.keys(modules)
      .map(path => path.split('/').pop()?.replace('.vue', '') || '')
      .filter(name => name && !name.startsWith('_')) // 过滤私有文件
    
    fieldTypeOptions.value = fileNames
      .map(name => ({ label: name, value: name }))
      .sort((a, b) => a.label.localeCompare(b.label))
  } catch (e) {
    console.warn('Failed to load field type options from filesystem:', e)
    // 如果加载失败，使用基础选项列表
    fieldTypeOptions.value = [
      'Attach', 'AttachImage', 'Autocomplete', 'Barcode', 'Button',
      'Check', 'Code', 'Color', 'Comment', 'CronEditor', 'Currency',
      'Data', 'Date', 'DateRange', 'Datetime', 'Duration', 'DynamicLink',
      'Float', 'Geolocation', 'Heading', 'HTML', 'HTMLEditor', 'Icon',
      'Image', 'Int', 'Jeditor', 'JSON', 'Link', 'LongText', 'MarkdownEditor',
      'MultiCheck', 'MultiSelect', 'MultiSelectList', 'MultiSelectPills',
      'Password', 'Percent', 'Phone', 'Rating', 'Select', 'Signature',
      'SmallText', 'Table', 'TableMultiSelect', 'Text', 'TextEditor', 'Time'
    ].map(name => ({ label: name, value: name }))
  }
}

loadFieldTypeOptions()

const slug = computed(() => toSnake(form.value.pagetype || ''))
function dotToSlash(s: string): string { return s ? s.split('.').join('/').toLowerCase() : '' }
const frontendPath = computed(() => {
  if (!appName.value || slug.value === '') return ''
  const files = []
  if (form.value.frontendOptions?.includes('toolbar')) {
    files.push(`apps/${appName.value}/frontend/src/views/pagetype/${slug.value}/${slug.value}_toolbar.vue`)
  }
  if (form.value.frontendOptions?.includes('sidebar')) {
    files.push(`apps/${appName.value}/frontend/src/views/pagetype/${slug.value}/${slug.value}_sidebar.vue`)
  }
  if (form.value.frontendOptions?.includes('page')) {
    files.push(`apps/${appName.value}/frontend/src/views/pagetype/${slug.value}/${slug.value}.vue`)
  }
  if (form.value.frontendOptions?.includes('field_types')) {
    if (form.value.fieldTypeNames && form.value.fieldTypeNames.length > 0) {
      form.value.fieldTypeNames.forEach((name: string) => {
        files.push(`apps/${appName.value}/frontend/src/views/pagetype/${slug.value}/form/controls/${name}.vue`)
      })
    } else {
      files.push(`apps/${appName.value}/frontend/src/views/pagetype/${slug.value}/form/controls/`)
    }
  }
  return files.join('\n')
})
const backendPath = computed(() =>
  appName.value && slug.value !== ''
    ? `apps/${appName.value}/${appName.value}/${dotToSlash(moduleName.value)}/pagetype/${slug.value}/${slug.value}.py`
    : ''
)

const rules: FormRules = {
  pagetype: [{ required: true, message: t('Please select PageType') }]
}


async function onDropdownShow(shown: boolean) {
  if (!shown || pagetypeOptions.value.length) return
  loading.value = true
  try {
    const res = await axios.get(`/api/data/PageType`, { params: { order_by: 'modified desc', limit_page_length: 1000 } })
    const list = res.data?.data || []
    pagetypeOptions.value = list.map((x: any) => ({ label: x.name, value: x.name }))
  } catch (e: any) {
    message.error(e?.response?.data?.message || e?.message || 'Failed to load')
  } finally {
    loading.value = false
  }
}

function toSnake(name: string): string {
  return name.replace(/\s+/g, '_').replace(/-+/g, '_').toLowerCase()
}

function onFrontendToggle(value: boolean) {
  if (value && !form.value.frontendOptions?.length) {
    form.value.frontendOptions = ['toolbar']
  } else if (!value) {
    form.value.frontendOptions = []
    form.value.fieldTypeNames = []
  }
}

function updateFieldTypesPreview() {
  // 触发预览更新
}

function onFrontendOptionsChange(value: (string | number)[]) {
  // 当取消选择字段类型时，清空字段类型名称
  if (!value.includes('field_types')) {
    form.value.fieldTypeNames = []
  }
}

async function onPagetypeChange() {
  appName.value = ''
  moduleName.value = ''
  if (!form.value.pagetype) return
  try {
    const res = await axios.get(`/jingrow/get-module-app`, {
      params: { pagetype: form.value.pagetype }
    })
    const msg = res.data?.message || {}
    if (msg?.success) {
      appName.value = msg.app || ''
      moduleName.value = msg.module || ''
    }
  } catch (e) {
    // ignore preview errors
  }
}

async function handleSubmit() {
  formRef.value?.validate(async (errors) => {
    if (errors) return
    submitting.value = true
    try {
      const res = await axios.post(`/jingrow/dev/create-pagetype-template`, {
        pagetype: form.value.pagetype,
        app: appName.value,
        module: moduleName.value,
        create_frontend: form.value.createFrontend,
        create_backend: form.value.createBackend,
        frontend_options: form.value.frontendOptions || [],
        field_type_names: form.value.fieldTypeNames || []
      }, {})
      result.value = res.data
      if (res.data?.success) {
        const { frontend_exists, backend_exists } = res.data
        if (frontend_exists || backend_exists) {
          const parts = []
          if (frontend_exists) parts.push('前端文件')
          if (backend_exists) parts.push('后端文件')
          message.warning(`${parts.join('、')}已存在`)
        } else {
          message.success(t('Created successfully'))
        }
      }
    } catch (e: any) {
      message.error(e?.response?.data?.detail || e?.message || 'Failed')
    } finally {
      submitting.value = false
    }
  })
}
</script>

<style scoped>
.page-dev-create-template { padding: 16px; }
.result { margin-top: 16px; font-size: 13px; color: #374151; }
.path-preview {
  margin: 4px 0 0 0;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
}
.field-types-row {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>


