<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="600px"
    destroy-on-close
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="分类名称" prop="title">
        <el-input v-model="formData.title" placeholder="请输入分类名称" />
      </el-form-item>

      <el-form-item label="父级分类" prop="pid">
        <el-select
          v-model="formData.pid"
          placeholder="请选择父级分类"
          clearable
          style="width: 100%"
        >
          <el-option label="顶级分类" :value="0" />
          <el-option
            v-for="item in typeOptions"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="分类描述" prop="desc">
        <el-input
          v-model="formData.desc"
          type="textarea"
          :rows="4"
          placeholder="请输入分类描述（可选）"
        />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" :max="999" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  addProductsTypes,
  updateProductsTypes,
  getProductsTypesList
} from '@/api/products'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '添加分类'
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)

const typeOptions = ref([])

const formData = reactive({
  title: '',
  pid: 0,
  desc: '',
  sort: 0
})

const formRules = {
  title: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { max: 100, message: '长度不超过100个字符', trigger: 'blur' }
  ]
}

const resetForm = () => {
  formData.title = ''
  formData.pid = 0
  formData.desc = ''
  formData.sort = 0
}

const loadTypeOptions = async () => {
  try {
    const res = await getProductsTypesList({ page: 1, limit: 1000, keyword: '' })
    if (res.code === 200 && Array.isArray(res.data?.list)) {
      const curId = props.isEdit ? Number(props.rowData?.id ?? 0) : 0
      typeOptions.value = curId
        ? res.data.list.filter((item) => Number(item.id) !== curId)
        : res.data.list
    } else {
      typeOptions.value = []
    }
  } catch (e) {
    // 下拉选项失败不影响弹窗可用性
    console.error('加载父级分类失败:', e)
    typeOptions.value = []
  }
}

// 打开/关闭
watch(
  () => props.modelValue,
  async (val) => {
    visible.value = val
    if (val) {
      resetForm()
      if (props.isEdit && props.rowData) {
        Object.assign(formData, props.rowData)
        formData.pid = Number(props.rowData?.pid ?? 0)
        formData.sort = Number(props.rowData?.sort ?? 0)
      }
      await loadTypeOptions()
    }
  }
)

watch(visible, (val) => {
  emit('update:modelValue', val)
})

const handleClose = () => {
  visible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    submitLoading.value = true
    try {
      let res
      const payload = {
        title: formData.title,
        pid: Number(formData.pid ?? 0),
        desc: formData.desc ?? '',
        sort: Number(formData.sort ?? 0)
      }

      if (props.isEdit) {
        res = await updateProductsTypes(Number(props.rowData?.id), payload)
      } else {
        res = await addProductsTypes(payload)
      }

      if (res.code === 200) {
        ElMessage.success(props.isEdit ? '更新分类成功' : '添加分类成功')
        handleClose()
        emit('success')
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (e) {
      console.error('提交分类失败:', e)
      ElMessage.error('操作失败')
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

