<template>
  <a-modal
    :title="modalTitle"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :width="800"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="花卉名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入花卉名称" />
      </a-form-item>

      <a-form-item label="花卉类型" name="type">
        <a-select v-model:value="formState.type" placeholder="请选择花卉类型">
          <a-select-option value="鲜花">鲜花</a-select-option>
          <a-select-option value="盆栽">盆栽</a-select-option>
          <a-select-option value="绿植">绿植</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="品种" name="variety">
        <a-input v-model:value="formState.variety" placeholder="请输入品种" />
      </a-form-item>

      <a-form-item label="价格" name="price">
        <a-input-number
          v-model:value="formState.price"
          :min="0"
          :precision="2"
          placeholder="请输入价格"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item label="库存" name="stock">
        <a-input-number
          v-model:value="formState.stock"
          :min="0"
          placeholder="请输入库存"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item label="商家" name="merchantId">
        <a-select
          v-model:value="formState.merchantId"
          placeholder="请选择商家"
          :loading="merchantsLoading"
        >
          <a-select-option
            v-for="merchant in merchants"
            :key="merchant.id"
            :value="merchant.id"
          >
            {{ merchant.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="状态" name="status">
        <a-select v-model:value="formState.status" placeholder="请选择状态">
          <a-select-option value="active">上架</a-select-option>
          <a-select-option value="inactive">下架</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="图片" name="image">
        <a-upload
          v-model:file-list="fileList"
          list-type="picture-card"
          :before-upload="beforeUpload"
          @preview="handlePreview"
          @remove="handleRemove"
        >
          <div v-if="fileList.length < 1">
            <plus-outlined />
            <div style="margin-top: 8px">上传图片</div>
          </div>
        </a-upload>
      </a-form-item>

      <a-form-item label="描述" name="description">
        <a-textarea
          v-model:value="formState.description"
          placeholder="请输入花卉描述"
          :rows="4"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { message, type UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import type { FormInstance } from 'ant-design-vue'
import { getMerchants } from '@/api/flower'
import type { Flower, Merchant } from '@/api/flower'

interface Props {
  visible: boolean
  currentRecord: Flower | null
  mode: 'create' | 'edit' | 'view'
}

interface Emits {
  (e: 'cancel'): void
  (e: 'ok', data: any): void
}

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

const formRef = ref<FormInstance>()
const confirmLoading = ref(false)
const merchants = ref<Merchant[]>([])
const merchantsLoading = ref(false)
const fileList = ref<any[]>([])

const formState = reactive({
  name: '',
  type: '',
  variety: '',
  price: 0,
  stock: 0,
  merchantId: undefined as number | undefined,
  status: 'active',
  image: '',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入花卉名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择花卉类型', trigger: 'change' }],
  variety: [{ required: true, message: '请输入品种', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
  merchantId: [{ required: true, message: '请选择商家', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const modalTitle = computed(() => {
  switch (props.mode) {
    case 'create':
      return '新增花卉'
    case 'edit':
      return '编辑花卉'
    case 'view':
      return '查看花卉'
    default:
      return '花卉信息'
  }
})

// 加载商家列表
const loadMerchants = async () => {
  try {
    merchantsLoading.value = true
    const response = await getMerchants()
    if (response.data.success) {
      merchants.value = response.data.data.merchants
    }
  } catch (error) {
    console.error('加载商家列表失败:', error)
    message.error('加载商家列表失败')
  } finally {
    merchantsLoading.value = false
  }
}

// 处理图片上传
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return false // 返回 false 阻止自动上传
}

const handlePreview: UploadProps['onPreview'] = (file) => {
  // 处理图片预览
  console.log('Preview file:', file)
}

const handleRemove: UploadProps['onRemove'] = (file) => {
  // 处理图片删除
  console.log('Remove file:', file)
}

// 处理模态框取消
const handleCancel = () => {
  formRef.value?.resetFields()
  fileList.value = []
  emit('cancel')
}

// 处理模态框确认
const handleOk = async () => {
  try {
    await formRef.value?.validate()
    confirmLoading.value = true
    
    const formData = { ...formState }
    if (fileList.value.length > 0) {
      formData.image = fileList.value[0].thumbUrl || fileList.value[0].url
    }
    
    emit('ok', formData)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    confirmLoading.value = false
  }
}

// 监听 visible 变化
watch(() => props.visible, (visible) => {
  if (visible) {
    loadMerchants()
    if (props.currentRecord) {
      Object.assign(formState, props.currentRecord)
      if (props.currentRecord.image) {
        fileList.value = [{
          uid: '-1',
          name: 'image',
          status: 'done',
          url: props.currentRecord.image
        }]
      }
    } else {
      formRef.value?.resetFields()
      fileList.value = []
    }
  }
})

// 监听 mode 变化
watch(() => props.mode, (mode) => {
  if (mode === 'view') {
    // 查看模式下禁用表单
    Object.keys(rules).forEach(key => {
      rules[key as keyof typeof rules] = []
    })
  } else {
    // 恢复验证规则
    Object.assign(rules, {
      name: [{ required: true, message: '请输入花卉名称', trigger: 'blur' }],
      type: [{ required: true, message: '请选择花卉类型', trigger: 'change' }],
      variety: [{ required: true, message: '请输入品种', trigger: 'blur' }],
      price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
      stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
      merchantId: [{ required: true, message: '请选择商家', trigger: 'change' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    })
  }
})
</script>