<template>
  <div class="space-y-4">
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 flex flex-col h-full">
      <!-- Header -->
      <div class="bg-gray-50 px-4 py-3 border-b border-gray-200 flex justify-between items-center">
        <div>
           <h3 class="text-sm font-bold text-gray-800">IP 用户映射</h3>
           <p class="text-xs text-gray-500">维护 IP 与用户标识的对应关系</p>
        </div>
        <button
          @click="loadMappings"
          :disabled="loading"
          class="text-gray-500 hover:text-blue-600 transition-colors p-1.5 rounded hover:bg-gray-200"
          title="刷新列表"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4" :class="{'animate-spin': loading}">
             <path fill-rule="evenodd" d="M15.312 11.424a5.5 5.5 0 01-9.201 2.466l-.312-.311h2.433a.75.75 0 000-1.5H3.989a.75.75 0 00-.75.75v4.242a.75.75 0 001.5 0v-2.43l.31.31a7 7 0 0011.712-3.138.75.75 0 00-1.449-.39zm1.23-3.723a.75.75 0 00.219-.53V2.929a.75.75 0 00-1.5 0v2.433l-.31-.31a7 7 0 00-11.712 3.138.75.75 0 001.449.39 5.5 5.5 0 019.201-2.466l.312.312h-2.433a.75.75 0 000 1.5h4.185a.75.75 0 00.53-.219z" clip-rule="evenodd" />
          </svg>
        </button>
      </div>

      <!-- Messages -->
      <div v-if="message" class="mx-4 mt-4 text-sm text-green-600 bg-green-50 px-3 py-2 rounded border border-green-100">
        {{ message }}
      </div>
      <div v-if="error" class="mx-4 mt-4 text-sm text-red-600 bg-red-50 px-3 py-2 rounded border border-red-100">
        {{ error }}
      </div>

      <!-- Add New Form -->
      <div class="p-4 bg-white border-b border-gray-100">
         <div class="flex flex-col md:flex-row gap-3 items-end md:items-center">
            <div class="flex-1 w-full">
               <label class="block text-xs text-gray-500 mb-1">IP 地址</label>
               <input
                v-model="newMapping.ip_address"
                type="text"
                class="w-full px-3 py-2 text-sm font-mono border border-gray-300 rounded focus:ring-1 focus:ring-blue-500"
                placeholder="192.168.1.100"
              />
            </div>
            <div class="flex-1 w-full">
               <label class="block text-xs text-gray-500 mb-1">用户标识</label>
               <input
                v-model="newMapping.user_name"
                type="text"
                class="w-full px-3 py-2 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500"
                placeholder="zhangsan"
              />
            </div>
            <div class="flex-[1.5] w-full">
               <label class="block text-xs text-gray-500 mb-1">备注</label>
               <input
                v-model="newMapping.remark"
                type="text"
                class="w-full px-3 py-2 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500"
                placeholder="可选备注"
              />
            </div>
             <button
              @click="createMapping"
              :disabled="saving"
              class="w-full md:w-auto px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-1 h-[38px] mt-4 md:mt-0"
            >
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
                <path d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z" />
              </svg>
              新增
            </button>
         </div>
      </div>

       <!-- Unmapped IPs Section -->
      <div v-if="unmappedIps.length" class="px-4 py-3 bg-amber-50 border-b border-amber-100">
        <div class="flex items-center justify-between mb-2">
          <div class="text-sm font-bold text-amber-800 flex items-center gap-1">
             <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
              </svg>
            待匹配 IP ({{ unmappedIps.length }})
          </div>
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 max-h-48 overflow-y-auto pr-1 custom-scrollbar">
          <div
            v-for="item in unmappedIps"
            :key="item.ip_address"
            class="group flex items-center justify-between gap-2 bg-white border border-amber-200 rounded px-3 py-2 text-sm shadow-sm hover:border-amber-400 transition-colors cursor-pointer"
            @click="fillIp(item.ip_address)"
            title="点击填入"
          >
            <div class="flex flex-col min-w-0">
              <span class="font-mono text-gray-800 font-medium truncate">{{ item.ip_address }}</span>
              <span class="text-xs text-gray-500 truncate">
                {{ formatTime(item.last_seen_at) }} ({{ item.logs_count }})
              </span>
            </div>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4 text-amber-300 group-hover:text-amber-600">
               <path d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z" />
            </svg>
          </div>
        </div>
      </div>

      <!-- Table -->
      <div class="overflow-x-auto flex-1">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/4">IP 地址</th>
              <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/4">用户标识</th>
              <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">备注</th>
              <th scope="col" class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider w-24">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="mapping in mappings" :key="mapping.id" class="hover:bg-gray-50 group">
              <td class="px-4 py-2 align-top">
                <input
                  v-model="mapping.ip_address"
                  type="text"
                  class="w-full text-sm font-mono bg-transparent border-none p-0 focus:ring-0 text-gray-900 placeholder-gray-400 group-hover:bg-white focus:bg-white rounded px-1"
                />
              </td>
              <td class="px-4 py-2 align-top">
                <input
                  v-model="mapping.user_name"
                  type="text"
                  class="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-gray-900 group-hover:bg-white focus:bg-white rounded px-1"
                />
              </td>
              <td class="px-4 py-2 align-top">
                <input
                  v-model="mapping.remark"
                  type="text"
                  class="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-gray-600 group-hover:bg-white focus:bg-white rounded px-1"
                />
              </td>
              <td class="px-4 py-2 align-top text-right whitespace-nowrap">
                <div class="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">
                  <button
                    @click="updateMapping(mapping)"
                    :disabled="mapping._saving"
                    class="p-1.5 text-blue-600 hover:bg-blue-50 rounded"
                    title="保存"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
                      <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z" clip-rule="evenodd" />
                    </svg>
                  </button>
                  <button
                    @click="deleteMapping(mapping)"
                    :disabled="mapping._deleting"
                    class="p-1.5 text-red-600 hover:bg-red-50 rounded"
                    title="删除"
                  >
                     <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
                      <path fill-rule="evenodd" d="M8.75 1A2.75 2.75 0 006 3.75v.443c-.795.077-1.584.176-2.365.298a.75.75 0 10.23 1.482l.149-.022.841 10.518A2.75 2.75 0 007.596 19h4.807a2.75 2.75 0 002.742-2.53l.841-10.52.149.023a.75.75 0 00.23-1.482A41.03 41.03 0 0014 4.193V3.75A2.75 2.75 0 0011.25 1h-2.5zM10 4c.84 0 1.673.025 2.5.075V3.75c0-.69-.56-1.25-1.25-1.25h-2.5c-.69 0-1.25.56-1.25 1.25v.325C8.327 4.025 9.16 4 10 4z" clip-rule="evenodd" />
                    </svg>
                  </button>
                </div>
              </td>
            </tr>
            <tr v-if="mappings.length === 0">
              <td colspan="4" class="px-4 py-8 text-center text-sm text-gray-400">
                暂无映射数据
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'IpUserMappings',
  data() {
    return {
      mappings: [],
      unmappedIps: [],
      loading: false,
      saving: false,
      error: '',
      message: '',
      newMapping: {
        ip_address: '',
        user_name: '',
        remark: ''
      }
    };
  },
  mounted() {
    this.loadMappings();
  },
  methods: {
    formatTime(value) {
      if (!value) {
        return '-';
      }
      // Simple date formatter, removing seconds for compactness
      return value.replace('T', ' ').replace('Z', '').substring(5, 16);
    },
    async parseJsonResponse(response) {
      const contentType = response.headers.get('content-type') || '';
      if (!contentType.includes('application/json')) {
        const text = await response.text();
        throw new Error(text || '响应不是JSON');
      }
      return response.json();
    },
    getErrorMessage(data, fallback) {
      if (!data) {
        return fallback;
      }
      if (data.message) {
        return data.message;
      }
      if (data.errors && typeof data.errors === 'object') {
        const firstKey = Object.keys(data.errors)[0];
        const firstError = firstKey ? data.errors[firstKey]?.[0] : '';
        if (firstError) {
          return firstError;
        }
      }
      return fallback;
    },
    fillIp(ip) {
      this.newMapping.ip_address = ip;
    },
    async loadMappings() {
      this.loading = true;
      this.error = '';
      this.message = '';

      try {
        const response = await fetch('/api/admin/ip-user-mappings', {
          headers: {
            Accept: 'application/json'
          }
        });
        const data = await this.parseJsonResponse(response);

        if (!response.ok) {
          this.error = this.getErrorMessage(data, '加载失败');
          return;
        }

        if (!data.success) {
          this.error = data.message || '加载失败';
          return;
        }

        this.mappings = (data.data.mappings || []).map((item) => ({
          ...item,
          _saving: false,
          _deleting: false
        }));
        this.unmappedIps = data.data.unmapped_ips || [];
      } catch (error) {
        this.error = error.message;
      } finally {
        this.loading = false;
      }
    },
    async createMapping() {
      this.saving = true;
      this.error = '';
      this.message = '';

      try {
        const response = await fetch('/api/admin/ip-user-mappings', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json'
          },
          body: JSON.stringify(this.newMapping)
        });

        const data = await this.parseJsonResponse(response);

        if (!response.ok) {
          this.error = this.getErrorMessage(data, '创建失败');
          return;
        }

        if (!data.success) {
          this.error = data.message || '创建失败';
          return;
        }

        this.message = '已新增映射';
        this.newMapping = { ip_address: '', user_name: '', remark: '' };
        await this.loadMappings();
         setTimeout(() => { this.message = ''; }, 3000);
      } catch (error) {
        this.error = error.message;
      } finally {
        this.saving = false;
      }
    },
    async updateMapping(mapping) {
      mapping._saving = true;
      this.error = '';
      this.message = '';

      try {
        const response = await fetch(`/api/admin/ip-user-mappings/${mapping.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json'
          },
          body: JSON.stringify({
            ip_address: mapping.ip_address,
            user_name: mapping.user_name,
            remark: mapping.remark
          })
        });

        const data = await this.parseJsonResponse(response);

        if (!response.ok) {
          this.error = this.getErrorMessage(data, '更新失败');
          return;
        }

        if (!data.success) {
          this.error = data.message || '更新失败';
          return;
        }

        this.message = '已更新映射';
        setTimeout(() => { this.message = ''; }, 3000);
      } catch (error) {
        this.error = error.message;
      } finally {
        mapping._saving = false;
      }
    },
    async deleteMapping(mapping) {
      if (!confirm('确定要删除吗？')) return;
      mapping._deleting = true;
      this.error = '';
      this.message = '';

      try {
        const response = await fetch(`/api/admin/ip-user-mappings/${mapping.id}`, {
          method: 'DELETE',
          headers: {
            Accept: 'application/json'
          }
        });
        const data = await this.parseJsonResponse(response);

        if (!response.ok) {
          this.error = this.getErrorMessage(data, '删除失败');
          return;
        }

        if (!data.success) {
          this.error = data.message || '删除失败';
          return;
        }

        this.message = '已删除映射';
        await this.loadMappings();
        setTimeout(() => { this.message = ''; }, 3000);
      } catch (error) {
        this.error = error.message;
      } finally {
        mapping._deleting = false;
      }
    }
  }
};
</script>
