<template>
  <div class="composer-wrap">
    <!-- 工具栏：模型 / 技能 / 会话操作 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <n-select
          v-model:value="modelId"
          :options="modelOptions"
          size="small"
          placeholder="默认模型"
          consistent-menu-width
          style="width: 180px"
        />
        <n-select
          v-model:value="skillFolder"
          :options="skillOptions"
          size="small"
          placeholder="无技能"
          consistent-menu-width
          style="width: 200px"
        />
      </div>
      <div class="toolbar-right">
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button size="small" quaternary :disabled="!canOperateSession" @click="$emit('export')">
              导出
            </n-button>
          </template>
          导出为 Markdown
        </n-tooltip>
        <n-popconfirm trigger="click" @positive-click="$emit('reset')">
          <template #trigger>
            <n-button size="small" quaternary :disabled="!canOperateSession">
              重置
            </n-button>
          </template>
          重置后当前对话历史将不再展示（数据保留），确定？
        </n-popconfirm>
        <n-popconfirm trigger="click" @positive-click="$emit('delete')">
          <template #trigger>
            <n-button size="small" quaternary type="error" :disabled="!canOperateSession">
              删除
            </n-button>
          </template>
          删除后会话归档（数据保留供审计），确定？
        </n-popconfirm>
      </div>
    </div>

    <!-- 输入框 + 发送按钮 -->
    <div class="composer">
      <n-input
        v-model:value="text"
        type="textarea"
        :autosize="{ minRows: 1, maxRows: 6 }"
        :maxlength="10000"
        :show-count="false"
        placeholder="输入消息，Enter 发送，Shift+Enter 换行"
        :disabled="sending"
        @keydown.enter.exact.prevent="onEnter"
      />
      <n-button type="primary" :loading="sending" :disabled="!canSend" @click="onSend">
        发送
      </n-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { NInput, NButton, NSelect, NTooltip, NPopconfirm } from 'naive-ui'
import { getModelList } from '../../api/model'
import { getSkillList } from '../../api/skill'

const props = defineProps({
  sending: { type: Boolean, default: false },
  /** 当前会话是否可用（控制导出/重置/删除按钮） */
  hasSession: { type: Boolean, default: false },
  /** 会话级默认值（切换会话时同步） */
  defaultModelId: { type: [Number, String], default: null },
  defaultSkillFolder: { type: String, default: null }
})

const emit = defineEmits(['send', 'export', 'reset', 'delete'])

const text = ref('')
const modelId = ref(props.defaultModelId)
const skillFolder = ref(props.defaultSkillFolder)

// 模型/技能选项
const modelOptions = ref([])
const skillOptions = ref([])

const canSend = computed(() => text.value.trim().length > 0 && !props.sending)
const canOperateSession = computed(() => props.hasSession)

// 切换会话时同步默认值
watch(() => props.defaultModelId, v => { modelId.value = v })
watch(() => props.defaultSkillFolder, v => { skillFolder.value = v })

async function loadOptions() {
  try {
    const [mr, sr] = await Promise.all([getModelList(), getSkillList()])
    modelOptions.value = (mr.data || []).map(m => ({
      label: m.name || m.modelName || `模型#${m.id}`,
      value: m.id
    }))
    skillOptions.value = (sr.data || []).map(s => ({
      label: s.displayName || s.name || s.folderName,
      value: s.folderName
    }))
  } catch (e) {
    // 静默失败：不影响主流程，下次切换会话时再尝试加载
    console.warn('[ChatComposer] loadOptions 失败', e?.message || e)
  }
}

// 一次性加载选项（组件首次挂载时）
loadOptions()
// 暴露给父组件：技能/模型变化时可能新增，需要外部触发刷新
defineExpose({ refreshOptions: loadOptions })

function onEnter() {
  if (canSend.value) onSend()
}

function onSend() {
  if (!canSend.value) return
  const payload = {
    text: text.value,
    opts: {
      modelId: modelId.value ?? null,
      skillFolder: skillFolder.value ?? null
    }
  }
  emit('send', payload)
  text.value = ''
}
</script>

<style scoped>
/* v1.3：深色主题，与系统深色风格一致；不再用 naive-ui 的 --n-color（白色） */
.composer-wrap {
  display: flex;
  flex-direction: column;
  border-top: 1px solid rgba(255, 255, 255, 0.06);
  background: rgba(0, 0, 0, 0.2);
}

/* 工具栏：模型 / 技能 / 操作按钮 */
.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding: 8px 24px 4px;
  flex-wrap: wrap;
}
.toolbar-left {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 输入框 + 发送按钮 */
.composer {
  display: flex;
  gap: 8px;
  align-items: flex-end;
  padding: 8px 24px 12px;
}
.composer :deep(.n-input) {
  flex: 1;
}
/* 输入框内部也统一深色，避免 NaiveUI 默认白色 textarea */
.composer :deep(.n-input .n-input-wrapper) {
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 4px;
}
.composer :deep(.n-input .n-input-wrapper:hover),
.composer :deep(.n-input .n-input-wrapper:focus-within) {
  border-color: rgba(168, 85, 247, 0.4);
}
.composer :deep(.n-input__textarea-el),
.composer :deep(.n-input__input-el) {
  color: var(--text-primary, #e0e0e0);
}
.composer :deep(.n-input .n-input__placeholder) {
  color: var(--text-tertiary, #666);
}

/* 工具栏按钮统一深色风格（NaiveUI quaternary 按钮在深底下需要显式调整） */
.toolbar :deep(.n-button.n-button--quaternary-type) {
  color: var(--text-secondary, #b0b0b0);
}
.toolbar :deep(.n-button.n-button--quaternary-type:hover) {
  background: rgba(255, 255, 255, 0.06);
}
.toolbar :deep(.n-button.n-button--quaternary-type.n-button--error-type) {
  color: #f87171;
}

/* NaiveUI Select 弹层 menu 是 teleport 到 body 的，不能 scoped，但 trigger 部分可以 */
.toolbar :deep(.n-base-selection) {
  background: rgba(255, 255, 255, 0.04);
}
.toolbar :deep(.n-base-selection .n-base-selection-label) {
  background: transparent;
  color: var(--text-primary, #e0e0e0);
}
.toolbar :deep(.n-base-selection:hover .n-base-selection-label) {
  background: rgba(255, 255, 255, 0.06);
}
</style>
