<template>
  <div class="template-editor">
    <n-tabs
      v-model:value="activeTab"
      type="line"
    >
      <!-- 现有模板 -->
      <n-tab-pane
        name="existing"
        tab="编辑模板"
      >
        <n-space
          vertical
          :size="16"
        >
          <n-select
            v-model:value="selectedTemplateKey"
            :options="templateList"
            placeholder="选择要编辑的模板"
          />

          <div
            v-if="selectedTemplateKey"
            class="template-form"
          >
            <n-form
              ref="formRef"
              :model="editForm"
            >
              <n-form-item label="模板名称">
                <n-input
                  v-model:value="editForm.name"
                  placeholder="输入模板名称"
                />
              </n-form-item>

              <n-form-item label="包含任务">
                <n-checkbox-group v-model:value="editForm.tasks">
                  <n-space vertical>
                    <n-checkbox
                      v-for="task in availableTasks"
                      :key="task.value"
                      :value="task.value"
                      :label="task.label"
                    />
                  </n-space>
                </n-checkbox-group>
              </n-form-item>

              <n-space>
                <n-button
                  type="primary"
                  @click="handleUpdate"
                >
                  保存修改
                </n-button>
                <n-button
                  type="error"
                  @click="handleDelete"
                >
                  删除模板
                </n-button>
              </n-space>
            </n-form>
          </div>
        </n-space>
      </n-tab-pane>

      <!-- 新建模板 -->
      <n-tab-pane
        name="new"
        tab="新建模板"
      >
        <n-form
          ref="newFormRef"
          :model="newForm"
        >
          <n-form-item label="模板名称">
            <n-input
              v-model:value="newForm.name"
              placeholder="输入模板名称"
            />
          </n-form-item>

          <n-form-item label="包含任务">
            <n-checkbox-group v-model:value="newForm.tasks">
              <n-space vertical>
                <n-checkbox
                  v-for="task in availableTasks"
                  :key="task.value"
                  :value="task.value"
                  :label="task.label"
                />
              </n-space>
            </n-checkbox-group>
          </n-form-item>

          <n-button
            type="primary"
            @click="handleCreate"
          >
            创建模板
          </n-button>
        </n-form>
      </n-tab-pane>
    </n-tabs>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useMessage } from 'naive-ui'

const props = defineProps({
  templates: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['save', 'delete', 'close'])

const message = useMessage()

// 可用任务列表
const availableTasks = [
  { value: 'dailyFix', label: '一键补差（包含所有每日任务）' },
  { value: 'legionSignIn', label: '俱乐部签到' },
  { value: 'autoStudy', label: '一键答题' },
  { value: 'claimHangupReward', label: '领取奖励（挂机）' },
  { value: 'addClock', label: '加钟' },
  { value: 'sendCar', label: '发车' },
  { value: 'climbTower', label: '爬塔' },
  { value: 'restartBottle', label: '重启盐罐机器人' },
  { value: 'blackMarket', label: '小号黑市购买（青铜、铂金必买，黄金≤5折）' }
]

const activeTab = ref('existing')
const selectedTemplateKey = ref(null)
const editForm = ref({
  name: '',
  tasks: []
})
const newForm = ref({
  name: '',
  tasks: []
})

// 模板列表
const templateList = computed(() => {
  return Object.keys(props.templates).map(key => ({
    label: props.templates[key].name,
    value: key
  }))
})

// 监听模板选择变化
watch(selectedTemplateKey, (newKey) => {
  if (newKey && props.templates[newKey]) {
    const template = props.templates[newKey]
    editForm.value = {
      name: template.name,
      tasks: [...template.tasks]
    }
  }
})

// 更新模板
const handleUpdate = () => {
  if (!editForm.value.name) {
    message.error('请输入模板名称')
    return
  }
  if (editForm.value.tasks.length === 0) {
    message.error('请至少选择一个任务')
    return
  }

  emit('save', selectedTemplateKey.value, editForm.value.tasks)
  message.success('模板已更新')
}

// 删除模板
const handleDelete = () => {
  if (confirm(`确定要删除模板"${editForm.value.name}"吗？`)) {
    emit('delete', selectedTemplateKey.value)
    selectedTemplateKey.value = null
    editForm.value = { name: '', tasks: [] }
  }
}

// 创建新模板
const handleCreate = () => {
  if (!newForm.value.name) {
    message.error('请输入模板名称')
    return
  }
  if (newForm.value.tasks.length === 0) {
    message.error('请至少选择一个任务')
    return
  }

  emit('save', newForm.value.name, newForm.value.tasks)
  newForm.value = { name: '', tasks: [] }
  activeTab.value = 'existing'
}
</script>

<style scoped lang="scss">
.template-editor {
  .template-form {
    margin-top: 16px;
  }
}
</style>

