<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑标签' : '新增标签'"
    width="600px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
    :confirm-loading="submitting"
  >
    <a-form :model="form" layout="vertical" ref="formRef">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="标签名称"
            field="name"
            :rules="[{ required: true, message: '请输入标签名称' }]"
          >
            <a-input
              v-model="form.name"
              placeholder="请输入标签名称"
              :max-length="200"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="标签类型" field="type">
            <a-select
              v-model="form.type"
              placeholder="请选择标签类型"
              allow-clear
            >
              <a-option value="document">文档标签</a-option>
              <a-option value="faq">FAQ标签</a-option>
              <a-option value="general">通用标签</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="标签描述" field="description">
        <a-textarea
          v-model="form.description"
          placeholder="请输入标签描述"
          :auto-size="{ minRows: 2, maxRows: 4 }"
          :max-length="500"
        />
      </a-form-item>

      <a-form-item label="标签颜色" field="color">
        <div class="color-picker-wrapper">
          <a-input
            v-model="form.color"
            placeholder="请选择颜色"
            readonly
            @click="showColorPicker = !showColorPicker"
          >
            <template #prefix>
              <div
                class="color-preview"
                :style="{ backgroundColor: form.color || '#ccc' }"
              ></div>
            </template>
          </a-input>
          <div v-if="showColorPicker" class="color-picker-dropdown">
            <div class="color-picker-header">选择颜色</div>
            <div class="color-picker-grid">
              <div
                v-for="color in presetColors"
                :key="color"
                class="color-item"
                :style="{ backgroundColor: color }"
                @click="selectColor(color)"
              ></div>
            </div>
            <div class="color-picker-custom">
              <span>自定义颜色:</span>
              <input
                type="color"
                v-model="form.color"
                @change="showColorPicker = false"
              />
            </div>
          </div>
        </div>
      </a-form-item>

      <a-form-item label="排序号" field="sort_order">
        <a-input-number
          v-model="form.sort_order"
          placeholder="请输入排序号"
          :min="0"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item label="备注信息" field="remarks">
        <a-textarea
          v-model="form.remarks"
          placeholder="请输入备注信息"
          :auto-size="{ minRows: 2, maxRows: 4 }"
          :max-length="500"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import {
  createCategory,
  updateCategory,
  type Category,
} from '@/api/kb/category'

interface Props {
  visible: boolean
  category: Category | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref()
const submitting = ref(false)
const showColorPicker = ref(false)

// 预设颜色
const presetColors = [
  '#FF0000', '#FF4500', '#FF8C00', '#FFD700', '#FFFF00',
  '#9ACD32', '#32CD32', '#00FF00', '#00FA9A', '#00CED1',
  '#1E90FF', '#0000FF', '#8A2BE2', '#9400D3', '#FF00FF',
  '#FF1493', '#DC143C', '#B22222', '#8B0000', '#800000',
]

// 表单数据
const form = ref({
  name: '',
  description: '',
  type: 'document',
  color: '',
  sort_order: 0,
  remarks: '',
})

// 是否为编辑模式
const isEdit = computed(() => !!props.category?.id)

// 选择颜色
const selectColor = (color: string) => {
  form.value.color = color
  showColorPicker.value = false
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.category && isEdit.value) {
        // 编辑模式：填充表单
        form.value = {
          name: props.category.name || '',
          description: props.category.description || '',
          type: props.category.type || 'document',
          color: props.category.color || '',
          sort_order: props.category.sort_order || 0,
          remarks: props.category.remarks || '',
        }
      } else {
        // 新建模式：重置表单
        form.value = {
          name: '',
          description: '',
          type: 'document',
          color: '',
          sort_order: 0,
          remarks: '',
        }
      }
      showColorPicker.value = false
    }
  }
)

// 确认提交
const handleOk = async () => {
  const valid = await formRef.value?.validate()
  if (valid) return

  submitting.value = true
  try {
    const data: any = {
      name: form.value.name,
      description: form.value.description,
      type: form.value.type,
      color: form.value.color,
      sort_order: form.value.sort_order,
      remarks: form.value.remarks,
    }

    let res: any
    if (isEdit.value && props.category?.id) {
      // 编辑标签
      data.id = props.category.id
      res = await updateCategory(data)
    } else {
      // 新建标签
      res = await createCategory(data)
    }

    if (res.code === 0) {
      Message.success(isEdit.value ? '编辑成功' : '创建成功')
      emit('success')
      emit('update:visible', false)
    } else {
      Message.error(res.message || (isEdit.value ? '编辑失败' : '创建失败'))
    }
  } catch (error) {
    Message.error(isEdit.value ? '编辑失败' : '创建失败')
    console.error(error)
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}

// 处理对话框可见性变化
const handleVisibleChange = (visible: boolean) => {
  emit('update:visible', visible)
}
</script>

<script lang="ts">
export default {
  name: 'KbCategoryFormDialog',
}
</script>

<style scoped lang="less">
.color-picker-wrapper {
  position: relative;

  .color-preview {
    width: 16px;
    height: 16px;
    border-radius: 2px;
    border: 1px solid #d9d9d9;
  }

  .color-picker-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    background: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    padding: 12px;
    margin-top: 4px;
    width: 280px;

    .color-picker-header {
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 8px;
      color: #262626;
    }

    .color-picker-grid {
      display: grid;
      grid-template-columns: repeat(10, 1fr);
      gap: 4px;
      margin-bottom: 12px;

      .color-item {
        width: 20px;
        height: 20px;
        border-radius: 2px;
        cursor: pointer;
        border: 1px solid #d9d9d9;

        &:hover {
          transform: scale(1.1);
          border-color: #1890ff;
        }
      }
    }

    .color-picker-custom {
      display: flex;
      align-items: center;
      gap: 8px;
      padding-top: 8px;
      border-top: 1px solid #f0f0f0;

      span {
        font-size: 12px;
        color: #595959;
      }

      input[type="color"] {
        width: 60px;
        height: 28px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        cursor: pointer;
      }
    }
  }
}
</style>