<script setup>
import RPC from '@/utils/rpc'
const props = defineProps({
  type: {
    type: String,
    required: true,
  },
  row: [Object],
})

const emit = defineEmits(['closed', 'onSuccess'])

const dialogVisible = ref(false)

const isAdd = computed(() => props.type === 'add')

onMounted(() => {
  dialogVisible.value = true
})

const formRef = ref(null)
const formField = ref({ enabled: true, params: [] })
const formRules = reactive({
  name: [{ required: true, message: '不可为空', trigger: 'change' }],
  code: [{ required: true, message: '不可为空', trigger: 'change' }],
})

const loading = ref(false)

function closed() {
  emit('closed')
}

const submitForm = async () => {
  await formRef.value.validate()
  const api = isAdd.value ? '/membership_plan/create' : '/membership_plan/update'
  const params = {
    ...formField.value,
    id: isAdd.value ? null : props.row.id,
  }
  loading.value = true
  RPC.post(api, params)
    .then((res) => {
      ElMessage.success('操作成功')
      emit('onSuccess')
      emit('closed')
    })
    .finally(() => {
      loading.value = false
    })
}

if (!isAdd.value) {
  formField.value = {
    ...props.row,
  }
}
</script>

<template>
  <el-dialog
    align-center
    :title="isAdd ? '新增' : '修改'"
    width="80%"
    v-model="dialogVisible"
    @closed="closed"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      label-position="right"
      label-suffix=":"
      :model="formField"
      :rules="formRules"
      v-loading="loading"
      label-width="150"
    >
      <el-form-item prop="name" label="名称">
        <el-input placeholder="请输入" v-model="formField.name" />
      </el-form-item>
      <el-form-item prop="code" label="字段">
        <el-input placeholder="请输入" v-model="formField.code" />
      </el-form-item>
      <el-form-item prop="duration_days" label="持续时间（天）">
        <el-input-number placeholder="请输入" v-model="formField.duration_days" />
      </el-form-item>
      <el-form-item prop="price_cents" label="价格">
        <el-input-number placeholder="请输入" v-model="formField.price" />
      </el-form-item>
      <el-form-item prop="tags" label="标签">
        <el-input placeholder="请输入" v-model="formField.tags" />
      </el-form-item>
      <el-form-item prop="sort" label="排序">
        <el-input-number placeholder="请输入" v-model="formField.sort" />
      </el-form-item>
      <el-form-item prop="enabled" label="是否启用">
        <el-switch v-model="formField.enabled" active-text="启用" inactive-text="禁用" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed"> 取 消 </el-button>
        <el-button type="primary" :loading="loading" @click="submitForm"> 确 定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

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