<template>
  <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-8">
    <div class="mb-6">
      <h3 class="text-lg font-medium text-gray-900">系统设置</h3>
      <p class="text-gray-500 mt-1">仅对当前浏览器生效的本地配置。</p>
    </div>

    <div class="space-y-6">
      <div class="border border-gray-200 rounded-lg p-6">
        <div class="flex items-start justify-between gap-4">
          <div>
            <h4 class="text-base font-semibold text-gray-900">JIRA</h4>
            <p class="text-sm text-gray-500 mt-1">
              设置“JIRA 默认查询用户”（仅本地浏览器生效）。填写后将优先用于周报/工时等页面的默认用户名。
            </p>
          </div>
          <div v-if="jira.loading" class="text-sm text-gray-400">加载中...</div>
        </div>

        <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">默认查询用户（本地）</label>
            <input
              type="text"
              v-model="jira.localDefaultQueryUserDraft"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="例如: your.name"
            />
            <p class="text-xs text-gray-500 mt-2">留空并保存（或点击清除）将使用服务端默认值。</p>
          </div>

          <div class="space-y-3">
            <div class="bg-gray-50 border border-gray-200 rounded-md p-4">
              <div class="text-sm text-gray-700">
                <div class="flex items-center justify-between gap-2">
                  <span class="text-gray-500">服务端默认查询用户</span>
                  <span class="font-mono text-gray-900">{{ jira.serverDefaultUser || '-' }}</span>
                </div>
                <div class="flex items-center justify-between gap-2 mt-2">
                  <span class="text-gray-500">当前生效</span>
                  <span class="font-mono text-gray-900">{{ effectiveDefaultQueryUser || '-' }}</span>
                </div>
                <div class="flex items-center justify-between gap-2 mt-2">
                  <span class="text-gray-500">JIRA Host</span>
                  <span class="font-mono text-gray-900">{{ jira.host || '-' }}</span>
                </div>
              </div>
            </div>

            <div class="flex gap-2">
              <button
                @click="save"
                class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                :disabled="jira.saving"
              >
                {{ jira.saving ? '保存中...' : '保存' }}
              </button>
              <button
                @click="clear"
                class="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed"
                :disabled="jira.saving"
              >
                清除
              </button>
            </div>

            <div v-if="jira.message" class="text-sm text-green-700 bg-green-50 border border-green-200 rounded-md px-3 py-2">
              {{ jira.message }}
            </div>
            <div v-if="jira.error" class="text-sm text-red-700 bg-red-50 border border-red-200 rounded-md px-3 py-2">
              {{ jira.error }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  clearJiraDefaultQueryUserOverride,
  getJiraDefaultQueryUserOverride,
  resolveJiraDefaultQueryUser,
  setJiraDefaultQueryUserOverride
} from '../../utils/jiraQueryUser';

export default {
  name: 'SystemSettings',
  data() {
    return {
      jira: {
        loading: false,
        saving: false,
        localDefaultQueryUserDraft: '',
        localDefaultQueryUserSaved: '',
        serverDefaultUser: '',
        host: '',
        message: '',
        error: ''
      }
    };
  },
  computed: {
    effectiveDefaultQueryUser() {
      return (this.jira.localDefaultQueryUserSaved || '').trim() || resolveJiraDefaultQueryUser(this.jira.serverDefaultUser);
    }
  },
  async mounted() {
    const savedOverride = getJiraDefaultQueryUserOverride();
    this.jira.localDefaultQueryUserDraft = savedOverride;
    this.jira.localDefaultQueryUserSaved = savedOverride;
    await this.loadServerConfig();
  },
  methods: {
    async loadServerConfig() {
      this.jira.loading = true;
      this.jira.error = '';

      try {
        const response = await fetch('/api/jira/config');
        const data = await response.json();

        if (!data.success) {
          this.jira.error = data.message || '获取配置失败';
          return;
        }

        this.jira.serverDefaultUser = (data.data.default_user || '').trim();
        this.jira.host = (data.data.host || '').trim();
      } catch (error) {
        this.jira.error = error.message;
      } finally {
        this.jira.loading = false;
      }
    },

    async save() {
      this.jira.saving = true;
      this.jira.message = '';
      this.jira.error = '';

      try {
        setJiraDefaultQueryUserOverride(this.jira.localDefaultQueryUserDraft);
        const savedOverride = getJiraDefaultQueryUserOverride();
        this.jira.localDefaultQueryUserSaved = savedOverride;
        this.jira.localDefaultQueryUserDraft = savedOverride;
        this.jira.message = '已保存（仅本地浏览器生效）';
      } catch (error) {
        this.jira.error = error.message;
      } finally {
        this.jira.saving = false;
      }
    },

    async clear() {
      this.jira.saving = true;
      this.jira.message = '';
      this.jira.error = '';

      try {
        clearJiraDefaultQueryUserOverride();
        this.jira.localDefaultQueryUserDraft = '';
        this.jira.localDefaultQueryUserSaved = '';
        this.jira.message = '已清除，将使用服务端默认值';
      } catch (error) {
        this.jira.error = error.message;
      } finally {
        this.jira.saving = false;
      }
    }
  }
};
</script>
