<template>
  <div class="theme-list-page">
    <a-card :bordered="false">
      <template #title>
        <span>主题字典管理</span>
      </template>
      <template #extra>
        <a-button type="primary" @click="handleCreate">
          <template #icon><PlusOutlined /></template>
          新建主题
        </a-button>
      </template>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'color'">
            <span v-if="record.color" class="color-swatch" :style="{ backgroundColor: record.color }" :title="record.color" />
            <span v-else class="color-empty">-</span>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 'ACTIVE' ? 'success' : 'default'">
              {{ record.status === 'ACTIVE' ? '启用' : '归档' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm title="确定要删除吗？" @confirm="handleDelete(record)">
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑主题' : '新建主题'"
      @ok="handleSave"
      @cancel="modalVisible = false"
    >
      <a-form :model="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="主题名称" required>
          <a-input v-model:value="form.name" placeholder="请输入主题名称" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model:value="form.description" placeholder="请输入主题描述" :rows="3" />
        </a-form-item>
        <a-form-item label="颜色">
          <div class="color-input-row">
            <a-input
              v-model:value="form.color"
              placeholder="#0780cf"
              allow-clear
              class="color-hex-input"
            />
            <input
              type="color"
              class="native-color-input"
              :value="nativePickerValue"
              title="取色器"
              @input="onNativeColorInput"
            />
          </div>
          <div class="color-picker">
            <span
              v-for="c in THEME_COLOR_OPTIONS"
              :key="c"
              class="color-option"
              :class="{ selected: form.color === c }"
              :style="{ backgroundColor: c }"
              :title="c"
              @click="form.color = c"
            />
            <span
              v-if="form.color"
              class="color-clear"
              @click="form.color = ''"
            >清除</span>
          </div>
        </a-form-item>
        <a-form-item label="排序">
          <a-input-number v-model:value="form.sortOrder" :min="1" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import {
  getThemeList,
  createTheme,
  updateTheme,
  deleteTheme,
} from '@/api/theme';
import type { Theme } from '@/api/theme';
import { THEME_COLOR_OPTIONS } from '@/constants/themeColors';

const loading = ref(false);
const dataSource = ref<Theme[]>([]);
const modalVisible = ref(false);
const isEdit = ref(false);
const editingId = ref<number | null>(null);

const form = reactive({
  name: '',
  description: '',
  color: '' as string,
  sortOrder: 1,
});

const HEX6 = /^#[0-9A-Fa-f]{6}$/;
/** 原生取色器需要合法 #RRGGBB，否则用中性灰避免控件报错 */
const nativePickerValue = computed(() => {
  const v = (form.color || '').trim();
  return HEX6.test(v) ? v : '#cccccc';
});

function onNativeColorInput(e: Event) {
  form.color = (e.target as HTMLInputElement).value;
}

const columns = [
  { title: '排序', dataIndex: 'sortOrder', key: 'sortOrder', width: 80 },
  { title: '主题名称', dataIndex: 'name', key: 'name' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '颜色', key: 'color', width: 80 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 150 },
];

const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getThemeList() as any;
    dataSource.value = res || [];
  } catch (error) {
    console.error('获取主题列表失败', error);
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  form.name = '';
  form.description = '';
  form.color = '';
  form.sortOrder = 1;
};

const handleCreate = () => {
  isEdit.value = false;
  editingId.value = null;
  resetForm();
  form.sortOrder = dataSource.value.length + 1;
  modalVisible.value = true;
};

const handleEdit = (record: any) => {
  isEdit.value = true;
  editingId.value = record.id;
  form.name = record.name;
  form.description = record.description || '';
  form.color = (record.color || '').toString();
  form.sortOrder = record.sortOrder;
  modalVisible.value = true;
};

const handleSave = async () => {
  if (!form.name) {
    message.warning('请输入主题名称');
    return;
  }

  try {
    if (isEdit.value && editingId.value) {
      await updateTheme(editingId.value, {
        name: form.name,
        description: form.description,
        color: form.color || undefined,
        sortOrder: form.sortOrder,
      });
      message.success('更新成功');
    } else {
      await createTheme({
        name: form.name,
        description: form.description,
        color: form.color || undefined,
        sortOrder: form.sortOrder,
      });
      message.success('创建成功');
    }
    modalVisible.value = false;
    fetchData();
  } catch (error) {
    message.error('保存失败');
  }
};

const handleDelete = async (record: any) => {
  try {
    await deleteTheme(record.id);
    message.success('删除成功');
    fetchData();
  } catch (error: any) {
    message.error(error.response?.data?.message || '删除失败');
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.theme-list-page {
  padding: 24px;
}

.color-input-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
}

.color-hex-input {
  max-width: 180px;
}

.native-color-input {
  width: 36px;
  height: 32px;
  padding: 0;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  vertical-align: middle;
}

.color-picker {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.color-option {
  width: 28px;
  height: 28px;
  border-radius: 6px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s;
}

.color-option:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.color-option.selected {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.color-clear {
  font-size: 12px;
  color: #999;
  cursor: pointer;
  padding: 4px 8px;
}

.color-clear:hover {
  color: #1890ff;
}

.color-swatch {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  vertical-align: middle;
  border: 1px solid #e8e8e8;
}

.color-empty {
  color: #bfbfbf;
}
</style>
