<template>
  <el-dialog title="代码模板配置" :visible.sync="open" width="800px" append-to-body @close="closeDialog">
    <el-form ref="form" :model="form" label-width="120px">
      <div v-if="loading" class="loading-text">加载中...</div>
      <div v-else-if="templateTypes.length === 0" class="no-data-text">暂无可配置的模板类型</div>
      <el-form-item v-for="templateType in templateTypes" :key="templateType.id" :label="templateType.name">
        <el-select v-model="form.configurations[templateType.id]" placeholder="请选择模板" clearable>
          <el-option
            v-for="template in availableTemplates[templateType.id]"
            :key="template.id"
            :label="template.name"
            :value="template.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
// Assume API functions are available, e.g., from '@/api/generator/template'
import { getAllTemplates } from '@/api/generator/template'
import { addProjectTemplate, listProjectTemplatesByProjectId, delProjectTemplateByProjectId } from '@/api/generator/project'

export default {
  name: 'ProjectTemplateConfig',
  data() {
    return {
      open: false,
      loading: false,
      submitLoading: false,
      projectId: null,
      templateTypes: [], // Array of { id: 'type1', name: 'Controller' }
      availableTemplates: {}, // Object like { type1: [{ id: 'tpl1', name: 'Template A' }] }
      form: {
        configurations: {} // Object like { type1: 'tpl1_id' }
      },
      existingTemplates: [] // 存储已关联的模板
    }
  },
  methods: {
    init(projectId) {
      this.projectId = projectId
      this.open = true
      this.loadInitialData()
    },
    async loadInitialData() {
      if (!this.projectId) return
      this.loading = true
      try {
        // 1. Define template types (can be static or fetched if an API for types exists)
        // If template types are also dynamic, they should be fetched first.
        this.templateTypes = [
          { id: 'backend', name: '后端模板' },
          { id: 'frontend', name: '前台前端模板' },
          { id: 'admin_frontend', name: '后台前端模板' }
        ]

        // Initialize availableTemplates for each type to an empty array
        // This ensures that even if a type has no templates, the select dropdown still renders correctly.
        this.templateTypes.forEach(type => {
          this.$set(this.availableTemplates, type.id, [])
          this.$set(this.form.configurations, type.id, null)
        })

        // 2. Fetch all available templates
        const response = await getAllTemplates()
        // Assuming response.data is an array of template objects
        // And each template object has: id, name, and type (e.g., 'controller')
        const allTemplates = response.data || []

        allTemplates.forEach(template => {
          if (template.templateType && this.availableTemplates[template.templateType]) {
            this.availableTemplates[template.templateType].push({
              id: template.templateId,
              name: template.templateName
            })
          } else {
            // Optional: Log a warning for templates with missing or unhandled types
            // console.warn(`Template "${template.name}" (ID: ${template.id}) has type "${template.type}" which is not configured in templateTypes or availableTemplates.`);
          }
        })

        // 3. 加载项目已关联的模板
        await this.loadExistingTemplates()
      } catch (error) {
        console.error('Error loading template configuration data:', error)
        this.$modal.msgError('加载模板数据失败')
      } finally {
        this.loading = false
      }
    },
    async loadExistingTemplates() {
      try {
        const res = await listProjectTemplatesByProjectId(this.projectId)
        console.log('API 原始返回数据:', res)
        this.existingTemplates = res || []
        console.log('设置后的existingTemplates:', this.existingTemplates)

        // 设置已选择的模板
        if (this.existingTemplates && this.existingTemplates.length > 0) {
          // 重置表单配置，确保没有过期的值
          this.templateTypes.forEach(type => {
            this.$set(this.form.configurations, type.id, null)
          })
          
          // 根据已有模板设置表单值
          this.existingTemplates.forEach(template => {
            if (template.templateType && this.availableTemplates[template.templateType]) {
              // 确认模板ID存在于可用模板列表中
              const exists = this.availableTemplates[template.templateType].some(
                t => t.id === template.templateId
              )
              if (exists) {
                this.$set(this.form.configurations, template.templateType, template.templateId)
              }
            }
          })
        }
      } catch (error) {
        console.error('Error loading existing templates:', error)
        this.$modal.msgError('加载已有模板失败')
      }
    },
    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          try {
            // 1. 先删除原有的模板配置
            if (this.existingTemplates.length > 0) {
              await delProjectTemplateByProjectId(this.projectId)
            }
            
            // 2. 添加新的模板配置
            const templateIds = Object.values(this.form.configurations).filter(id => id) // Get values and filter out any undefined/null if clearable is used

            const addPromises = templateIds.map(templateId => {
              return addProjectTemplate({ projectId: this.projectId, templateId: templateId })
            })
            
            if (addPromises.length > 0) {
              await Promise.all(addPromises)
            }
            
            this.$modal.msgSuccess('配置保存成功')
            this.open = false
            this.$emit('ok')
          } catch (error) {
            console.error('Error saving template configuration:', error)
            this.$modal.msgError('保存配置失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    cancel() {
      this.open = false
    },
    closeDialog() {
      // Reset state if needed when dialog is closed
      this.projectId = null
      this.templateTypes = []
      this.availableTemplates = {}
      this.form.configurations = {}
      this.existingTemplates = []
      this.loading = false
      this.submitLoading = false
    }
  }
}
</script>

<style scoped>
.loading-text, .no-data-text {
  text-align: center;
  padding: 20px;
  color: #909399;
}
</style>
