<template>
  <el-dialog
    title="安澜应急指挥 · 智能助手"
    :visible.sync="dialogVisible"
    width="720px"
    append-to-body
    destroy-on-close
    custom-class="gitcc-chat-dialog"
    @open="onOpen"
  >
    <div class="gitcc-wrap">
      <!-- API 仅存储在用户浏览器本地，不经过本系统后端 -->
      <el-card shadow="never" class="config-card">
        <div slot="header" class="config-header">
          <span>API 配置</span>
          <el-tag v-if="keyStatus === 'ok'" type="success" size="mini">已验证</el-tag>
          <el-tag v-else-if="keyStatus === 'bad'" type="danger" size="mini">验证失败</el-tag>
          <el-tag v-else type="info" size="mini">未配置</el-tag>
        </div>
        <p v-if="!keyReady" class="hint">请先配置并验证 API Key 后再开始对话。Key 仅保存在本机浏览器。</p>
        <el-form label-width="100px" size="small" @submit.native.prevent>
          <el-form-item label="API Key">
            <el-input
              v-model="keyInput"
              :type="keyShow ? 'text' : 'password'"
              placeholder="粘贴从平台获取的 Key"
              :disabled="reconfiguring === false && keyReady && !editingKey"
              clearable
            >
              <el-button slot="append" @click="keyShow = !keyShow">{{ keyShow ? '隐藏' : '显示' }}</el-button>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="text" @click="openGetKey">获取 Key</el-button>
            <el-button type="primary" :loading="verifying" @click="verifyAndSave">验证并保存</el-button>
            <el-button v-if="keyReady" @click="startReconfigure">重新配置</el-button>
            <el-button type="danger" plain @click="clearKey">清除 Key</el-button>
          </el-form-item>
          <p v-if="maskedHint" class="masked">已保存：{{ maskedHint }}</p>
        </el-form>
      </el-card>

      <div class="chat-panel">
        <div ref="msgList" class="msg-list">
          <div
            v-for="(m, idx) in messages"
            :key="idx"
            class="msg"
            :class="m.role === 'user' ? 'msg-user' : 'msg-assistant'"
          >
            <div class="msg-bubble">{{ m.content }}</div>
          </div>
          <div v-if="loading" class="msg msg-assistant">
            <div class="msg-bubble typing">正在输入…</div>
          </div>
        </div>
        <div class="chat-input-row">
          <el-input
            v-model="input"
            type="textarea"
            :rows="3"
            placeholder="输入消息，Enter 发送，Shift+Enter 换行"
            :disabled="!keyReady || loading"
            @keydown.native="onKeydown"
          />
          <el-button type="primary" class="send-btn" :disabled="!keyReady || loading || !input.trim()" @click="send">
            发送
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import axios from 'axios'

// API Key 仅存入浏览器 localStorage，不提交到本系统后端；与业务 axios 相互独立，避免将 Key 与业务 token 混用。
const STORAGE_KEY = 'SHUYU_GITCC_API_KEY'
const DEFAULT_WELCOME = '你好！我是智能助手。请先完成上方 API 配置后即可对话。'

/** 将 absolute Base URL 规范为带 /v1 后缀，同源反代路径不改动。 */
function normalizeGitccBaseUrl(raw) {
  let s = (raw == null || raw === '') ? '/gitcc-api' : String(raw).trim()
  s = s.replace(/\/+$/, '')
  if (/^https?:\/\//i.test(s) && /api\.gitcc\.com/i.test(s) && !/\/v1$/i.test(s)) {
    s = s + '/v1'
  }
  return s
}

function gitccClient() {
  const base = normalizeGitccBaseUrl(process.env.VUE_APP_GITCC_API)
  return axios.create({
    baseURL: base,
    timeout: 120000
  })
}

function maskKey(k) {
  if (!k || k.length < 4) return ''
  return k.slice(0, 1) + '******' + k.slice(-1)
}

export default {
  name: 'GitccChat',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      keyInput: '',
      keyShow: false,
      keyReady: false,
      keyStatus: 'none',
      maskedHint: '',
      verifying: false,
      reconfiguring: true,
      editingKey: false,
      messages: [],
      input: '',
      loading: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(v) {
        this.$emit('update:visible', v)
      }
    }
  },
  methods: {
    onOpen() {
      this.loadFromStorage()
      if (this.messages.length === 0) {
        this.messages.push({ role: 'assistant', content: DEFAULT_WELCOME })
      }
    },
    loadFromStorage() {
      const k = localStorage.getItem(STORAGE_KEY)
      if (k) {
        this.keyInput = k
        this.keyReady = true
        this.keyStatus = 'ok'
        this.maskedHint = maskKey(k)
        this.reconfiguring = false
        this.editingKey = false
      } else {
        this.keyInput = ''
        this.keyReady = false
        this.keyStatus = 'none'
        this.maskedHint = ''
        this.reconfiguring = true
      }
    },
    openGetKey() {
      window.open('https://api.gitcc.com/v1', '_blank', 'noopener,noreferrer')
    },
    async verifyAndSave() {
      const k = (this.keyInput || '').trim()
      if (!k) {
        this.$message.warning('请输入 API Key')
        return
      }
      this.verifying = true
      this.keyStatus = 'none'
      try {
        const http = gitccClient()
        await http.get('/v1/models', {
          headers: { Authorization: 'Bearer ' + k }
        })
        localStorage.setItem(STORAGE_KEY, k)
        this.keyReady = true
        this.keyStatus = 'ok'
        this.maskedHint = maskKey(k)
        this.reconfiguring = false
        this.editingKey = false
        this.$message.success('Key 已保存，可以开始对话')
        if (this.messages.length === 1 && this.messages[0].role === 'assistant' && this.messages[0].content === DEFAULT_WELCOME) {
          this.messages = [{ role: 'assistant', content: '配置成功。有什么可以帮你的？' }]
        }
      } catch (e) {
        this.keyStatus = 'bad'
        this.keyReady = false
        const msg = (e.response && e.response.data && e.response.data.error) || e.message || '请求失败'
        this.$message.error('验证失败：' + msg)
      } finally {
        this.verifying = false
      }
    },
    startReconfigure() {
      this.editingKey = true
      this.reconfiguring = true
      this.keyReady = false
    },
    clearKey() {
      this.$confirm('将清除本机保存的 API Key，确定吗？', '提示', { type: 'warning' })
        .then(() => {
          localStorage.removeItem(STORAGE_KEY)
          this.keyInput = ''
          this.keyReady = false
          this.keyStatus = 'none'
          this.maskedHint = ''
          this.reconfiguring = true
          this.editingKey = true
          this.$message.success('已清除')
        })
        .catch(() => {})
    },
    onKeydown(e) {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault()
        this.send()
      }
    },
    async send() {
      const text = (this.input || '').trim()
      if (!text || !this.keyReady || this.loading) return
      const k = localStorage.getItem(STORAGE_KEY)
      if (!k) {
        this.$message.warning('请先配置 API Key')
        return
      }
      this.messages.push({ role: 'user', content: text })
      this.input = ''
      this.loading = true
      this.$nextTick(this.scrollBottom)
      try {
        const http = gitccClient()
        const { data } = await http.post(
          '/v1/chat/completions',
          {
            model: 'gpt-4.1-mini',
            messages: [{ role: 'user', content: text }],
            temperature: 0.7,
            max_tokens: 256
          },
          {
            headers: {
              Authorization: 'Bearer ' + k,
              'Content-Type': 'application/json'
            }
          }
        )
        const out =
          (data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content) ||
          JSON.stringify(data)
        this.messages.push({ role: 'assistant', content: out })
      } catch (e) {
        const msg = (e.response && e.response.data && (e.response.data.error || e.response.data.message)) || e.message
        this.messages.push({ role: 'assistant', content: '请求失败：' + (typeof msg === 'string' ? msg : JSON.stringify(msg)) })
        this.$message.error('对话失败，请检查网络或 API Key')
      } finally {
        this.loading = false
        this.$nextTick(this.scrollBottom)
      }
    },
    scrollBottom() {
      const el = this.$refs.msgList
      if (el) {
        el.scrollTop = el.scrollHeight
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.gitcc-wrap {
  min-height: 360px;
}
.config-card {
  margin-bottom: 12px;
  border-radius: 10px;
}
.config-header {
  display: flex;
  align-items: center;
  gap: 8px;
}
.hint {
  color: #64748b;
  font-size: 13px;
  margin: 0 0 8px 0;
}
.masked {
  color: #64748b;
  font-size: 12px;
  margin: 0;
}
.chat-panel {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.msg-list {
  max-height: 280px;
  overflow-y: auto;
  padding: 8px 4px;
  background: #f1f5f9;
  border-radius: 10px;
  border: 1px solid #e2e8f0;
}
.msg {
  display: flex;
  margin-bottom: 8px;
  &.msg-user {
    justify-content: flex-end;
    .msg-bubble {
      background: #4f46e5;
      color: #fff;
    }
  }
  &.msg-assistant {
    justify-content: flex-start;
    .msg-bubble {
      background: #fff;
      color: #0f172a;
      border: 1px solid #e2e8f0;
    }
  }
}
.msg-bubble {
  max-width: 85%;
  padding: 10px 12px;
  border-radius: 10px;
  line-height: 1.5;
  font-size: 14px;
  white-space: pre-wrap;
  word-break: break-word;
  &.typing {
    font-style: italic;
    color: #64748b;
  }
}
.chat-input-row {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  .send-btn {
    flex-shrink: 0;
  }
}
</style>
<style>
.gitcc-chat-dialog .el-dialog__body {
  padding: 8px 16px 16px;
}
</style>
