<script setup lang="ts">
import { ref } from 'vue'
import type { ModelItem } from '@/types'
import type { GenerationControlOptions } from './types'

const props = defineProps<{
  options: GenerationControlOptions
  models?: ModelItem[]
  section: 'model' | 'quality'
  validationMessage?: string
}>()

const emit = defineEmits<{
  'update:options': [value: GenerationControlOptions]
}>()

function updateField<K extends keyof GenerationControlOptions>(
  field: K,
  value: GenerationControlOptions[K],
) {
  emit('update:options', { ...props.options, [field]: value })
}

function updateQualityRules(value: Array<string | number>) {
  const rules = value.filter((item): item is string => typeof item === 'string')
  emit('update:options', {
    ...props.options,
    filterLowQuality: rules.includes('low_quality'),
    filterShortContent: rules.includes('short_content'),
  })
}

const selectedQualityRules = () => [
  props.options.filterLowQuality ? 'low_quality' : '',
  props.options.filterShortContent ? 'short_content' : '',
].filter(Boolean)

function sectionValidationMessage() {
  if (!props.validationMessage) return ''
  const isModelMessage = props.validationMessage.includes('数据生成模型')
  if (props.section === 'model') return isModelMessage ? props.validationMessage : ''
  return isModelMessage ? '' : props.validationMessage
}
</script>

<template>
  <div v-if="section === 'model'" class="generation-config-group model-config-group">
    <div class="model-field">
      <div class="field-copy">
        <strong>数据生成模型 <em>*</em></strong>
        <small>选择负责生成问答、指令或结构化内容的大模型</small>
      </div>
      <el-select
        class="model-select"
        :model-value="options.generationModelId"
        filterable
        placeholder="请选择用于生成数据的模型"
        aria-label="数据生成模型"
        @update:model-value="updateField('generationModelId', $event)"
      >
        <el-option
          v-for="model in models || []"
          :key="model.id"
          :label="model.name"
          :value="model.id"
        >
          <div class="model-option">
            <span>{{ model.name }}</span>
            <small>{{ model.model_source === 'api' ? '在线模型' : '本地模型' }}</small>
          </div>
        </el-option>
        <template #empty>
          <div class="model-empty">暂无可用的大模型，请先在模型管理中添加</div>
        </template>
      </el-select>
    </div>

    <div class="model-field">
      <div class="field-copy">
        <strong>默认提示语</strong>
        <small>用于约束生成内容的格式、语气和完整性，可按任务需要修改</small>
      </div>
      <el-input
        class="prompt-input"
        :model-value="options.generationPrompt"
        type="textarea"
        :rows="4"
        maxlength="500"
        show-word-limit
        resize="vertical"
        placeholder="请输入模型生成内容时需要遵循的要求"
        aria-label="模型默认提示语"
        @update:model-value="updateField('generationPrompt', $event)"
      />
      <div class="prompt-variables-hint">
        提示：可在文本中通过 <code v-text="'{{ content }}'" /> 引用当前正在处理的数据内容。
      </div>
    </div>

    <div class="advanced-settings-grid">
      <label class="config-field">
        <span class="config-field-label">生成温度 (Temperature)</span>
        <el-slider
          :model-value="options.temperature"
          :min="0"
          :max="1"
          :step="0.1"
          show-input
          @update:model-value="updateField('temperature', Number($event) || 0)"
        />
        <small>较低值输出更确定、保守，较高值输出更多样、有创造性</small>
      </label>

      <label class="config-field">
        <span class="config-field-label">最大输出长度 (Max Tokens)</span>
        <span class="unit-input">
          <el-input-number
            :model-value="options.maxTokens"
            :min="100"
            :max="8192"
            :step="256"
            controls-position="right"
            @update:model-value="updateField('maxTokens', Number($event) || 1024)"
          />
          <span>Token</span>
        </span>
        <small>限制单次生成的最大内容长度，防止过度发散</small>
      </label>
    </div>

    <div class="json-mode-row">
      <div class="field-copy">
        <strong>强制 JSON 格式输出</strong>
        <small>要求大模型返回纯 JSON 对象，有助于提高下游结构化提取的稳定性</small>
      </div>
      <el-switch
        :model-value="options.jsonMode"
        inline-prompt
        active-text="开"
        inactive-text="关"
        @update:model-value="updateField('jsonMode', Boolean($event))"
      />
    </div>

    <p v-if="sectionValidationMessage()" class="generation-validation-message" role="alert">
      {{ sectionValidationMessage() }}
    </p>
  </div>

  <div v-else class="generation-config-group quality-config-group">
    <div class="quality-switch-row">
      <div class="config-group-heading">
        <div>
          <h4>质量筛选</h4>
          <p>生成后自动过滤不符合要求的内容，不影响源数据预处理</p>
        </div>
      </div>
      <el-switch
        :model-value="options.qualityFilterEnabled"
        inline-prompt
        active-text="开"
        inactive-text="关"
        aria-label="质量筛选"
        @update:model-value="updateField('qualityFilterEnabled', Boolean($event))"
      />
    </div>

    <div v-if="options.qualityFilterEnabled" class="quality-rule-panel">
      <el-checkbox-group
        :model-value="selectedQualityRules()"
        class="quality-rule-list"
        @update:model-value="updateQualityRules"
      >
        <el-checkbox value="low_quality">
          <span class="rule-copy">
            <strong>过滤低质量内容</strong>
            <small>按相关性、完整性和可读性过滤明显不合格的生成结果</small>
          </span>
        </el-checkbox>
        <el-checkbox value="short_content">
          <span class="rule-copy">
            <strong>过滤过短内容</strong>
            <small>过滤正文长度低于指定字数的生成结果</small>
          </span>
        </el-checkbox>
      </el-checkbox-group>

      <label v-if="options.filterShortContent" class="minimum-length-field">
        <span>最少字数</span>
        <span class="minimum-length-input">
          <el-input-number
            :model-value="options.minOutputLength"
            :min="1"
            :max="1000"
            :step="5"
            :precision="0"
            controls-position="right"
            aria-label="生成内容最少字数"
            @update:model-value="updateField('minOutputLength', Number($event) || 1)"
          />
          <span>字</span>
        </span>
        <small>少于该字数的生成结果将被过滤</small>
      </label>

      <p v-if="!options.filterLowQuality && !options.filterShortContent" class="quality-rule-warning" role="alert">
        请至少选择一项质量筛选规则
      </p>
    </div>
    <p v-if="sectionValidationMessage()" class="generation-validation-message" role="alert">
      {{ sectionValidationMessage() }}
    </p>
  </div>
</template>

<style scoped lang="scss">
.generation-config-group {
  padding: 14px;
  border: 1px solid #e2e5ec;
  border-radius: 8px;
  background: #fff;
}

.config-group-heading {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;

  h4 { margin: 0; color: #344054; font-size: 13px; font-weight: 600; }
  p { margin: 4px 0 0; color: #8a93a3; font-size: 12px; line-height: 1.5; }
}

.model-config-group {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 0;
  border: 0;
  border-radius: 0;
  background: transparent;
}

.model-config-group .advanced-settings-grid {
  grid-template-columns: 1fr;
  gap: 20px;
}

.model-config-group .config-field {
  padding: 0;
  border: 0;
  border-radius: 0;
}

.model-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-copy {
  display: grid;
  gap: 4px;

  strong {
    color: #344054;
    font-size: 13px;
    font-weight: 600;
  }

  small {
    color: #8a93a3;
    font-size: 12px;
    line-height: 1.5;
  }

  em { color: var(--el-color-danger); font-style: normal; }
}

.model-select { width: 100%; }
.prompt-input { width: 100%; }
.model-option { width: 100%; display: flex; align-items: center; justify-content: space-between; gap: 16px; }
.model-option small { color: #98a2b3; font-size: 11px; }
.model-empty { padding: 12px; color: #8a93a3; font-size: 12px; text-align: center; }

.prompt-variables-hint {
  color: #8a93a3;
  font-size: 12px;
  code {
    padding: 2px 4px;
    color: #5b50f2;
    background: #f0f0ff;
    border-radius: 4px;
    font-family: inherit;
  }
}

.advanced-settings-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}

.config-field {
  display: grid;
  align-content: start;
  gap: 8px;
  min-width: 0;
  padding: 14px;
  color: #344054;
  background: #fff;
  border: 1px solid #e2e5ec;
  border-radius: 8px;

  > small {
    color: #8a93a3;
    font-size: 12px;
    line-height: 1.5;
  }

  :deep(.el-slider) {
    margin: 0 8px;
  }
}

.config-field-label {
  font-size: 13px;
  font-weight: 600;
}

.unit-input {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #7b8495;
  font-size: 12px;

  :deep(.el-input-number) {
    width: 100%;
  }
}

.json-mode-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  padding: 12px 14px;
  background: #fff;
  border: 1px solid #e2e5ec;
  border-radius: 8px;
}

.quality-switch-row { display: flex; align-items: center; justify-content: space-between; gap: 20px; }
.quality-rule-panel { margin-top: 12px; padding-top: 12px; border-top: 1px solid #e7eaf0; }
.quality-rule-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.quality-rule-list :deep(.el-checkbox) {
  min-height: 62px; height: auto; margin-right: 0; padding: 10px 12px;
  align-items: flex-start; border: 1px solid #e2e5ec; border-radius: 7px; background: #fff;
}
.quality-rule-list :deep(.el-checkbox__input) { margin-top: 3px; }
.quality-rule-list :deep(.el-checkbox__label) { min-width: 0; padding-left: 9px; white-space: normal; }
.rule-copy { display: grid; gap: 3px; }
.rule-copy strong { color: #344054; font-size: 12px; font-weight: 600; }
.rule-copy small { color: #8a93a3; font-size: 11px; line-height: 1.5; }

.minimum-length-field {
  margin-top: 12px; display: grid; grid-template-columns: 110px 220px minmax(0, 1fr);
  align-items: center; gap: 12px; color: #475467; font-size: 12px;
}
.minimum-length-input { display: flex; align-items: center; gap: 8px; }
.minimum-length-input :deep(.el-input-number) { width: 180px; }
.minimum-length-field > small { color: #8a93a3; }
.quality-rule-warning { margin: 10px 0 0; color: #dc2626; font-size: 12px; }
.generation-validation-message { margin: 10px 0 0; color: #dc2626; font-size: 12px; }

@media (max-width: 900px) {
  .advanced-settings-grid { grid-template-columns: 1fr; }
  .quality-rule-list { grid-template-columns: 1fr; }
  .minimum-length-field { grid-template-columns: 1fr; }
}
</style>
