<template>
  <div class="course-label-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="search-section">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索标签名称"
              clearable
              style="width: 240px"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch">
              搜索
            </el-button>
          </div>
          <el-button type="primary" @click="handleAdd">
            新增标签
          </el-button>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="dataSource"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="labelName" label="标签名称" min-width="140">
          <template #default="{ row }">
            <el-tag
              :color="row.color"
              effect="dark"
              style="font-weight: 500; font-size: 14px; border-color: transparent;"
            >
              {{ row.labelName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="100">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; gap: 6px;">
              <span
                :style="{
                  display: 'inline-block',
                  width: '16px',
                  height: '16px',
                  borderRadius: '4px',
                  backgroundColor: row.color,
                  border: '1px solid #ddd',
                }"
              />
              <span>{{ row.color }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        style="margin-top: 16px; justify-content: flex-end"
        @size-change="onSizeChange"
        @current-change="onPageChange"
      />
    </el-card>

    <el-dialog
      v-model="modalVisible"
      :title="modalTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="labelName">
          <el-input v-model="formState.labelName" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签颜色" prop="color">
          <el-color-picker v-model="formState.color" show-alpha />
          <span style="margin-left: 8px; color: #909399;">{{ formState.color }}</span>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="formState.description"
            type="textarea"
            :rows="3"
            placeholder="请输入标签描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modalVisible = false">取消</el-button>
        <el-button type="primary" @click="handleModalOk">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { courseLabelApi, type CourseLabel, type CourseLabelPageRequest } from '@/api/groupCourse.api'

const loading = ref(false)
const dataSource = ref<CourseLabel[]>([])
const searchKeyword = ref('')

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const modalVisible = ref(false)
const modalTitle = ref('')
const formRef = ref()
const formState = reactive<CourseLabel>({
  labelName: '',
  color: '#1890ff',
  description: '',
})

const formRules = {
  labelName: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 2, max: 50, message: '标签名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  color: [{ required: true, message: '请选择标签颜色', trigger: 'change' }],
}

const fetchData = async () => {
  loading.value = true
  try {
    const params: CourseLabelPageRequest = {
      page: currentPage.value - 1,
      size: pageSize.value,
      sort: 'id',
      order: 'asc',
    }
    if (searchKeyword.value) params.keyword = searchKeyword.value

    const res = await courseLabelApi.getPage(params)
    dataSource.value = res.content
    total.value = Number(res.totalElements)
  } catch {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const onPageChange = () => fetchData()
const onSizeChange = () => {
  currentPage.value = 1
  fetchData()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

const handleAdd = () => {
  modalTitle.value = '新增标签'
  Object.assign(formState, {
    id: undefined,
    labelName: '',
    color: '#1890ff',
    description: '',
  })
  modalVisible.value = true
}

const handleEdit = (row: CourseLabel) => {
  modalTitle.value = '编辑标签'
  Object.assign(formState, { ...row })
  modalVisible.value = true
}

const handleDelete = async (row: CourseLabel) => {
  try {
    await ElMessageBox.confirm('确定要删除该标签吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await courseLabelApi.delete(row.id!)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleModalOk = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    // Convert RGBA to hex before submitting
    const data = { ...formState }
    if (data.color?.startsWith('rgba')) {
      data.color = rgbaToHex(data.color)
    }
    if (formState.id) {
      await courseLabelApi.update(formState.id, data)
    } else {
      await courseLabelApi.create(data)
    }
    ElMessage.success('操作成功')
    modalVisible.value = false
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

/** Convert rgba(r, g, b, a) to #rrggbb or #rrggbbaa hex */
const rgbaToHex = (rgba: string): string => {
  const match = rgba.match(/[\d.]+/g)
  if (!match || match.length < 3) return rgba
  const r = parseInt(match[0])
  const g = parseInt(match[1])
  const b = parseInt(match[2])
  const a = match.length >= 4 ? Math.round(parseFloat(match[3]) * 255) : 255
  const toHex = (n: number) => n.toString(16).padStart(2, '0')
  const hex = `#${toHex(r)}${toHex(g)}${toHex(b)}`
  return a < 255 ? `${hex}${toHex(a)}` : hex
}

onMounted(() => fetchData())
</script>

<style scoped lang="css">
.course-label-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;

    .search-section {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }
}
</style>
