<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="code"
            :rules="[{ required: true, message: '请输入分类编码' }]"
          >
            <a-input
              v-model="form.code"
              placeholder="请输入分类编码"
              :max-length="100"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item
        v-if="showParentSelector !== false"
        label="父级分类"
        field="parent_id"
      >
        <a-select
          v-model="form.parent_id"
          placeholder="请选择父级分类（不选则为一级分类）"
          allow-clear
          allow-search
          :disabled="fixedParentId !== undefined"
          :filter-option="filterParentOption"
        >
          <a-option
            v-for="item in parentCategories"
            :key="item.id"
            :value="item.id"
          >
            {{ item.name }}
          </a-option>
        </a-select>
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="排序" field="sort">
            <a-input-number
              v-model="form.sort"
              placeholder="请输入排序"
              :min="0"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否启用" field="enabled">
            <a-switch v-model="form.enabled" />
          </a-form-item>
        </a-col>
      </a-row>

      <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="description">
        <a-textarea
          v-model="form.description"
          placeholder="请输入描述"
          :auto-size="{ minRows: 3, maxRows: 6 }"
          :max-length="500"
        />
      </a-form-item>

      <a-form-item label="备注" field="remarks">
        <a-textarea
          v-model="form.remarks"
          placeholder="请输入备注"
          :auto-size="{ minRows: 3, maxRows: 6 }"
          :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 } from '@/api/ops/assetCategory'

interface Category {
  id?: number
  name?: string
  code?: string
  description?: string
  icon?: string
  color?: string
  parent_id?: number
  sort?: number
  enabled?: boolean
  remarks?: string
}

interface Props {
  visible: boolean
  category: Category | null
  parentCategories: any[]
  fixedParentId?: number
  showParentSelector?: boolean
}

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: '',
  code: '',
  description: '',
  icon: '',
  color: '',
  parent_id: undefined as number | undefined,
  sort: 0,
  enabled: true,
  remarks: '',
})

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

// 父级分类下拉搜索过滤
const filterParentOption = (input: string, option: any) => {
  return option.label.toLowerCase().includes(input.toLowerCase())
}

// 选择颜色
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 || '',
          code: props.category.code || '',
          description: props.category.description || '',
          icon: props.category.icon || '',
          color: props.category.color || '',
          parent_id: props.category.parent_id,
          sort: props.category.sort || 0,
          enabled: props.category.enabled !== undefined ? props.category.enabled : true,
          remarks: props.category.remarks || '',
        }
      } else {
        // 新建模式：重置表单
        form.value = {
          name: '',
          code: '',
          description: '',
          icon: '',
          color: '',
          parent_id: props.fixedParentId,
          sort: 0,
          enabled: true,
          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,
      code: form.value.code,
      description: form.value.description,
      icon: form.value.icon,
      color: form.value.color,
      parent_id: form.value.parent_id,
      sort: form.value.sort,
      enabled: form.value.enabled,
      remarks: form.value.remarks,
    }

    let res
    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: 'CategoryFormDialog',
}
</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>
