<script setup lang="ts">
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { addShop, updateShop, ShopDTO, UpdateShopCommand } from "@/api/shop/shop";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  row: {
    type: Object as () => ShopDTO,
    default: () => ({})
  }
});

const emit = defineEmits(["update:visible", "refresh"]);

const formRef = ref();
const formData = ref<UpdateShopCommand>({
  shopId: 0,
  shopName: ""
});

const rules = {
  shopName: [{ required: true, message: "请输入地址名称", trigger: "blur" }]
};

watch(
  () => props.visible,
  val => {
    if (val) {
      if (props.row?.shopId) {
        formData.value = {
          ...props.row,
          shopId: props.row.shopId
        };
      } else {
        formData.value = {
          shopId: 0,
          shopName: ""
        };
      }
    }
  }
);

const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    if (formData.value.shopId) {
      await updateShop(formData.value.shopId, formData.value);
      ElMessage.success("修改成功");
    } else {
      await addShop(formData.value);
      ElMessage.success("新增成功");
    }

    emit("update:visible", false);
    emit("refresh");
  } catch (error) {
    console.error(error);
  }
};

const handleClose = () => {
  emit("update:visible", false);
};
</script>

<template>
  <el-dialog :title="formData.shopId ? '编辑地址' : '新增地址'" :model-value="visible" @update:model-value="handleClose"
    width="600px">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="地址ID" prop="shopId" v-if="formData.shopId">
        <el-input v-model="formData.shopId" :disabled="true" />
      </el-form-item>
      <el-form-item label="地址名称" prop="shopName">
        <el-input v-model="formData.shopName" placeholder="请输入地址名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>