<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createLive, type LiveCreateRequest } from '@/api/live'
import { apiClient } from '@/api/client'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const fromInstance = ref('')

const form = ref<LiveCreateRequest>({
  name: 'live-600000',
  account: '66639661',
  vt_symbol: '600000.SSE',
  strategy_class: 'AShareDoubleMaStrategy',
  strategy_name: 'AShareDoubleMa_600000',
  setting: {
    fast_window: 5,
    slow_window: 20,
    window: 15,
    size: 100,
    forbid_short: true,
  },
  interval: '15m',
  initial_capital: 1_000_000,
  connect_wait_sec: 10,
  init_wait_sec: 60,
  mini_path: 'C:\\国金QMT交易端模拟\\userdata_mini',
})

const strategyClassOptions = [
  { value: 'AShareDoubleMaStrategy', label: 'AShareDoubleMaStrategy(双均线 A 股策略)' },
]

onMounted(async () => {
  const instId = route.query.instance
  if (!instId) return
  try {
    const [{ data: ir }, { data: fr }] = await Promise.all([
      apiClient.get<{ instance: { name?: string; code_file: string; symbol_or_pool: string; interval: string; params: Record<string, unknown> } }>(`/strategy/instances/${instId}`),
      apiClient.get<{ files: { name: string; class_name: string }[] }>('/strategy/files'),
    ])
    const inst = ir.instance
    fromInstance.value = inst.name || String(instId)
    const file = fr.files.find((f) => f.name === inst.code_file)
    const cls = file?.class_name || inst.code_file
    form.value.strategy_class = cls
    form.value.vt_symbol = inst.symbol_or_pool || form.value.vt_symbol
    form.value.strategy_name = inst.name || form.value.strategy_name
    form.value.interval = inst.interval || form.value.interval
    form.value.setting = { ...form.value.setting, ...(inst.params as object) }
  } catch {
    /* 预填失败走默认 */
  }
})

async function onSubmit(): Promise<void> {
  if (!form.value.name.trim()) {
    ElMessage.warning('请填写实例名')
    return
  }
  if (!form.value.account.trim()) {
    ElMessage.warning('请填写交易账号')
    return
  }
  if (!form.value.strategy_name.trim()) {
    ElMessage.warning('请填写策略实例名')
    return
  }
  loading.value = true
  try {
    const res = await createLive(form.value)
    ElMessage.success(`已创建实盘实例 #${res.accountId}(stopped),请到列表点"启动"`)
    router.push('/live')
  } catch (e: unknown) {
    ElMessage.error(e instanceof Error ? e.message : '创建失败')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="page live-new">
    <div class="page-head">
      <div>
        <h2 class="page-title">新建实盘模拟</h2>
        <p class="page-subtitle">miniQMT 直连 · A 股实盘模拟(supervisor 轮询)</p>
      </div>
    </div>

    <el-alert
      type="info"
      :closable="false"
      title="创建后状态为 stopped,需到列表点『启动』才会启动(supervisor 轮询发现后起 engine)"
    />

    <el-card class="blk" shadow="never">
      <template #header><span class="section-title">基本配置</span></template>
      <el-form :model="form" label-width="140px">
        <el-form-item label="实例名" required>
          <el-input v-model="form.name" placeholder="live-600000" style="width: 320px" />
          <span class="muted form-hint">页面显示用</span>
        </el-form-item>
        <el-form-item label="交易账号" required>
          <el-input v-model="form.account" placeholder="66639661" style="width: 320px" />
          <span class="muted form-hint">QMT 账号</span>
        </el-form-item>
        <el-form-item label="策略类">
          <el-select v-model="form.strategy_class" style="width: 360px">
            <el-option
              v-for="opt in strategyClassOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
          <span class="muted form-hint">MVP 仅支持 AShareDoubleMaStrategy</span>
        </el-form-item>
        <el-form-item label="策略实例名" required>
          <el-input v-model="form.strategy_name" placeholder="AShareDoubleMa_600000" style="width: 320px" />
          <span class="muted form-hint">engine 内唯一</span>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="blk" shadow="never">
      <template #header><span class="section-title">标的与频率</span></template>
      <el-form :model="form" label-width="140px">
        <el-form-item label="标的(vt_symbol)">
          <el-input v-model="form.vt_symbol" placeholder="600000.SSE" style="width: 320px" />
          <span class="muted form-hint">交易所代码 .SSE / .SZSE</span>
        </el-form-item>
        <el-form-item label="K 线周期">
          <el-input v-model="form.interval" placeholder="15m" style="width: 160px" />
          <span class="muted form-hint">如 15m / 1m / d</span>
        </el-form-item>
        <el-form-item label="起始资金">
          <el-input-number v-model="form.initial_capital" :min="10000" :step="100000" style="width: 240px" />
          <span class="muted form-hint">单位:元</span>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="blk" shadow="never">
      <template #header><span class="section-title">策略参数(setting)</span></template>
      <el-form :model="form.setting" label-width="140px">
        <el-form-item label="fast_window">
          <el-input-number v-model="form.setting.fast_window as number" :min="1" :step="1" style="width: 200px" />
          <span class="muted form-hint">快均线周期</span>
        </el-form-item>
        <el-form-item label="slow_window">
          <el-input-number v-model="form.setting.slow_window as number" :min="1" :step="1" style="width: 200px" />
          <span class="muted form-hint">慢均线周期</span>
        </el-form-item>
        <el-form-item label="window">
          <el-input-number v-model="form.setting.window as number" :min="1" :step="1" style="width: 200px" />
          <span class="muted form-hint">辅助计算窗口</span>
        </el-form-item>
        <el-form-item label="size">
          <el-input-number v-model="form.setting.size as number" :min="1" :step="100" style="width: 200px" />
          <span class="muted form-hint">定寸股数(A 股 100 的倍数)</span>
        </el-form-item>
        <el-form-item label="forbid_short">
          <el-switch v-model="form.setting.forbid_short as boolean" />
          <span class="muted form-hint">禁止做空(A 股默认开)</span>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="blk" shadow="never">
      <template #header><span class="section-title">连接参数(可选)</span></template>
      <el-form :model="form" label-width="140px">
        <el-form-item label="connect_wait_sec">
          <el-input-number v-model="form.connect_wait_sec as number" :min="1" :step="5" style="width: 200px" />
          <span class="muted form-hint">连接 QMT 等待秒数</span>
        </el-form-item>
        <el-form-item label="init_wait_sec">
          <el-input-number v-model="form.init_wait_sec as number" :min="1" :step="10" style="width: 200px" />
          <span class="muted form-hint">策略初始化等待秒数</span>
        </el-form-item>
        <el-form-item label="mini_path">
          <el-input v-model="form.mini_path" placeholder="C:\\国金QMT交易端模拟\\userdata_mini" style="width: 480px" />
          <span class="muted form-hint">miniQMT userdata_mini 路径;空时后端用 env SANGUO_QMT_PATH 或内置默认</span>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="submit-bar">
      <el-button type="primary" size="large" :loading="loading" @click="onSubmit">
        创建实盘实例
      </el-button>
      <el-button size="large" @click="router.push('/live')">取消</el-button>
    </div>
  </div>
</template>

<style scoped>
.live-new { display: flex; flex-direction: column; gap: 16px; }
.blk { border: 1px solid var(--border-2); }
.form-hint { margin-left: 10px; }
.submit-bar { padding: 4px 0; display: flex; gap: 12px; }
</style>
