<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import { addStage, updateStage } from '#/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '新增阶段',
  },
  diaData: {
    type: Object,
    default: () => ({}),
  },
})
const emits = defineEmits(['update:modelValue', 'onRefresh'])

const show = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  },
})

const _formData = {
  id: null,
  name: '',
  sortValue: '',
  status: 0,
}
const formRef = ref<FormInstance | undefined>()
const formData = reactive<Record<string, any>>({
  ..._formData,
})

const rules = reactive<FormRules>({
  name: [{ required: true, message: '阶段名称不能为空', trigger: 'blur' }],
  sortValue: [
    { required: true, message: '排序不能为空', trigger: 'blur' },
    { type: 'number', message: '排序必须为数字' },
  ],
})

function onOpen() {
  onClear()
  if (props.diaData.id) {
    for (const i in formData) {
      formData[i] = props.diaData[i]
    }
  }
}

async function handleSave() {
  await formRef.value?.validate((valid, _) => {
    if (valid) {
      let fn = updateStage
      if (props.title === '新增阶段') {
        fn = addStage
      }

      fn(formData).then(() => {
        show.value = false
        onClear()
        emits('onRefresh')
      })
    }
  })
}

function onClear() {
  Object.assign(formData, _formData)
}
</script>

<template>
  <el-dialog
    v-model="show"
    width="30vw"
    :title="title"
    class="box"
    destroy-on-close
    @open="onOpen"
  >
    <el-form ref="formRef" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="阶段名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="排序" prop="sortValue">
        <el-input v-model.number="formData.sortValue" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleSave"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
