<script lang="ts" setup>
/**
 * @Name: CreateDialog.vue
 * @Description: 产品品牌-创建对话框
 * @Author: xinyan
 */

import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';
import { Close, Finished } from '@element-plus/icons-vue';


const loading = ref(false);
const createDialog = <Ref>useTemplateRef('createDialog');
const createOpen = defineModel({ default: false });

const emit = defineEmits([ 'refresh' ]);

interface RuleForm {
  brand: any;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  brand: ''
});

const rules = reactive<FormRules<RuleForm>>({
  brand: [ { required: true, message: '请输入品牌名称', trigger: 'blur' } ]
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const body = {
        brand_name: ruleForm.brand
      };
      const res = await useResponse(api.createBrand, body, loading);
      if (res.code === 2000) {
        ElMessage.success({ message: '创建成功', plain: true, icon: 'CirclePlus' });
        createOpen.value = false;
        emit('refresh');
      }
    } else {
      // createOpen.value = false;
      ElMessage.error('创建失败，请检查表单');
    }
  });
};

function cancelDialog() {
  resetForm(ruleFormRef.value);
  createDialog.value.visible = false;
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<template>
  <el-dialog ref="createDialog" v-model="createOpen" :close-on-click-modal="false" :close-on-press-escape="false"
             :title="`产品品牌 - 创建 `" style="width: 30%">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="mx-2.5 mt-5" label-width="auto" status-icon>
      <el-form-item class="font-medium" label="品牌名称" prop="brand">
        <el-input v-model="ruleForm.brand" placeholder="请输入品牌名称" style="width:328px" />
      </el-form-item>
    </el-form>
    <template #footer>

      <el-button :icon="Close" @click="cancelDialog">取 消</el-button>
      <el-button :icon="Finished" :loading="loading" type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>
