<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px">
      <el-form-item label="租户" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="全部租户" filterable clearable size="small">
          <el-option v-for="c in companyOptions" :key="c.value" :label="c.label" :value="c.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="ID" prop="id" width="60" />
      <el-table-column label="租户" prop="companyName" width="120" />
      <el-table-column label="配置名" prop="configName" min-width="140" />
      <el-table-column label="触发策略" prop="triggerStrategy" width="110" />
      <el-table-column label="触发间隔" prop="triggerInterval" width="80" />
      <el-table-column label="模型" prop="modelIdentifier" width="140" />
      <el-table-column label="最大长度" prop="maxSummaryLength" width="80" />
      <el-table-column label="状态" width="80">
        <template slot-scope="{row}"><el-switch v-model="row.enabled" :active-value="1" :inactive-value="0" @change="handleStatusChange(row)" /></template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="{row}">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" style="color:#F56C6C" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="550px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="租户" prop="companyId" v-if="isAdd">
          <el-select v-model="form.companyId" placeholder="选择租户" filterable style="width:100%">
            <el-option v-for="c in companyOptions" :key="c.value" :label="c.label" :value="c.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="配置名" prop="configName">
          <el-input v-model="form.configName" placeholder="配置名称" />
        </el-form-item>
        <el-form-item label="触发策略">
          <el-select v-model="form.triggerStrategy" style="width:100%">
            <el-option label="按消息数" value="message_count" />
            <el-option label="按时长" value="duration" />
            <el-option label="手动" value="manual" />
          </el-select>
        </el-form-item>
        <el-form-item label="触发间隔(消息数)">
          <el-input-number v-model="form.triggerInterval" :min="1" :max="200" />
        </el-form-item>
        <el-form-item label="摘要模型">
          <el-input v-model="form.modelIdentifier" placeholder="模型标识符, 如 gpt-4" />
        </el-form-item>
        <el-form-item label="最大上下文消息">
          <el-input-number v-model="form.maxContextMessages" :min="5" :max="500" />
        </el-form-item>
        <el-form-item label="最大长度(字符)">
          <el-input-number v-model="form.maxSummaryLength" :min="50" :max="5000" :step="50" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAllCompanies } from '@/api/workflow/lobster-admin'
import request from '@/utils/request'

export default {
  name: 'SummaryConfig',
  data() {
    return {
      loading: false, list: [], total: 0, companyOptions: [],
      queryParams: { pageNum: 1, pageSize: 10, companyId: null },
      dialogVisible: false, dialogTitle: '', isAdd: false,
      form: { companyId: null, configName: '', triggerStrategy: 'message_count', triggerInterval: 20, modelIdentifier: '', maxContextMessages: 50, maxSummaryLength: 500, remark: '' },
      rules: { configName: [{ required: true, message: '不能为空', trigger: 'blur' }] }
    }
  },
  created() { this.loadCompanies(); this.getList() },
  methods: {
    async loadCompanies() { try { const res = await listAllCompanies(); this.companyOptions = (res.data || []).map(c => ({ value: c.companyId, label: c.companyName || '未知' })) } catch (e) {} },
    async getList() {
      this.loading = true
      try {
        const res = await request({ url: '/workflow/lobster/summary-config/list', method: 'get', params: this.queryParams })
        this.list = (res.data || [])
        this.total = this.list.length
      } catch (e) { this.list = []
      } finally { this.loading = false }
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    resetQuery() { this.$refs.queryForm.resetFields(); this.handleQuery() },
    handleAdd() { this.isAdd = true; this.dialogTitle = '新增摘要配置'; this.form = { companyId: this.queryParams.companyId, configName: '', triggerStrategy: 'message_count', triggerInterval: 20, modelIdentifier: '', maxContextMessages: 50, maxSummaryLength: 500, remark: '', enabled: 1 }; this.dialogVisible = true },
    handleEdit(row) { this.isAdd = false; this.dialogTitle = '修改摘要配置'; this.form = { ...row }; this.dialogVisible = true },
    async handleStatusChange(row) {
      try {
        await request({ url: '/workflow/lobster/summary-config/save', method: 'post', data: row })
        this.$message.success('状态已更新')
      } catch (e) { this.$message.error('更新失败') }
    },
    async submitForm() {
      this.$refs.formRef.validate(async v => {
        if (!v) return
        try {
          await request({ url: '/workflow/lobster/summary-config/save', method: 'post', data: this.form })
          this.$message.success(this.isAdd ? '新增成功' : '修改成功')
          this.dialogVisible = false; this.getList()
        } catch (e) { this.$message.error('保存失败') }
      })
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除?', '警告', { type: 'warning' })
        await request({ url: `/workflow/lobster/summary-config/${row.id}`, method: 'delete', params: { companyId: row.companyId } })
        this.$message.success('删除成功'); this.getList()
      } catch (e) { if (e !== 'cancel') this.$message.error('删除失败') }
    }
  }
}
</script>
