<template>
  <a-modal
    v-model:visible="dialogVisible"
    :title="isEdit ? '编辑分类' : '新建分类'"
    :width="520"
    :mask-closable="false"
    unmount-on-close
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-form-item field="name" label="分类名称" required>
        <a-input
          v-model="formData.name"
          placeholder="请输入分类名称"
          :max-length="50"
        />
      </a-form-item>

      <a-form-item field="code" label="分类编码" required>
        <a-input
          v-model="formData.code"
          placeholder="请输入分类编码"
          :max-length="50"
          :disabled="isEdit"
        />
      </a-form-item>

      <a-form-item field="parent_id" label="父级分类">
        <a-tree-select
          v-model="formData.parent_id"
          :data="categoryTreeData"
          placeholder="请选择父级分类（不选则为顶级分类）"
          allow-clear
          :field-names="{
            key: 'id',
            title: 'name',
            children: 'children',
          }"
          :load-more="handleLoadMore"
        />
      </a-form-item>

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

      <a-form-item field="color" label="颜色">
        <a-input
          v-model="formData.color"
          placeholder="请输入颜色值，如 #1890ff"
          :max-length="20"
        >
          <template #prefix>
            <div
              :style="{
                width: '16px',
                height: '16px',
                borderRadius: '2px',
                backgroundColor: formData.color || '#1890ff',
              }"
            />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item field="enabled" label="是否启用">
        <a-switch v-model="formData.enabled" />
      </a-form-item>

      <a-form-item field="description" label="描述">
        <a-textarea
          v-model="formData.description"
          placeholder="请输入分类描述"
          :max-length="200"
          :auto-size="{ minRows: 2, maxRows: 4 }"
          show-word-limit
        />
      </a-form-item>

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

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue/es/form'
import {
  createCategory,
  updateCategory,
  fetchCategoryTree,
  fetchCategoryChildren,
} from '@/api/ops/assetCategory'
import type { AssetCategory, CategoryFormData } from '@/api/ops/assetCategory'

interface Props {
  visible: boolean
  category?: AssetCategory | null
}

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

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  category: null,
})

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const categoryTreeData = ref<any[]>([])
const loading = ref(false)

const isEdit = computed(() => !!props.category?.id)

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val),
})

const defaultFormData = (): CategoryFormData => ({
  name: '',
  code: '',
  description: '',
  color: '#1890ff',
  parent_id: null,
  enabled: true,
  sort: 0,
  remarks: '',
})

const formData = ref<CategoryFormData>(defaultFormData())

const rules = {
  name: [
    { required: true, message: '分类名称不能为空' },
    { max: 50, message: '分类名称不能超过50个字符' },
  ],
  code: [
    { required: true, message: '分类编码不能为空' },
    { max: 50, message: '分类编码不能超过50个字符' },
    {
      match: /^[A-Z0-9_]+$/,
      message: '分类编码只能包含大写字母、数字和下划线',
    },
  ],
  color: [
    {
      match: /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,
      message: '请输入有效的颜色值，如 #1890ff',
    },
  ],
}

// 加载分类树
const loadCategoryTree = async () => {
  try {
    const res = await fetchCategoryTree()
    categoryTreeData.value = res.details || []
  } catch (error) {
    console.error('加载分类树失败:', error)
    categoryTreeData.value = []
  }
}

// 懒加载子节点
const handleLoadMore = async (node: any) => {
  if (node.children && node.children.length > 0) return
  try {
    const res = await fetchCategoryChildren(node.id)
    node.children = res.details || []
  } catch (error) {
    console.error('加载子分类失败:', error)
    node.children = []
  }
}

// 重置表单
const resetForm = () => {
  formData.value = defaultFormData()
  formRef.value?.resetFields()
}

// 监听 visible 变化
watch(
  () => props.visible,
  async (val) => {
    if (val) {
      await loadCategoryTree()
      if (props.category) {
        // 编辑模式，填充数据
        formData.value = {
          id: props.category.id,
          name: props.category.name,
          code: props.category.code,
          description: props.category.description || '',
          color: props.category.color || '#1890ff',
          parent_id: props.category.parent_id || null,
          enabled: props.category.enabled,
          sort: props.category.sort || 0,
          remarks: props.category.remarks || '',
        }
      } else {
        resetForm()
      }
    }
  }
)

const handleCancel = () => {
  emit('update:visible', false)
  resetForm()
}

const handleOk = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (valid) return

    loading.value = true
    const submitData = { ...formData.value }

    if (isEdit.value) {
      // 编辑
      const res = await updateCategory(submitData)
      if (res.code === 0) {
        Message.success('更新成功')
        emit('success')
        emit('update:visible', false)
        resetForm()
      } else {
        Message.error(res.message || '更新失败')
      }
    } else {
      // 新建
      const res = await createCategory(submitData)
      if (res.code === 0) {
        Message.success('创建成功')
        emit('success')
        emit('update:visible', false)
        resetForm()
      } else {
        Message.error(res.message || '创建失败')
      }
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    Message.error(error.message || '操作失败')
  } finally {
    loading.value = false
  }
}
</script>

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