<!-- 编辑弹窗 -->
<template>
  <ele-modal form :width="width" v-model="visible" :title="title">
    <SimpleForm
      :items="items"
      :labelWidth="labelWidth"
      ref="formRef"
      v-bind="formProps"
    ></SimpleForm>
    <template #footer>
      <el-button @click="handleCancel">关闭</el-button>
      <el-button type="primary" @click="handleSumbit">确定</el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, nextTick, getCurrentInstance } from 'vue';
  import { Flag, ChatDotSquare } from '@element-plus/icons-vue';
  import orderTimeline from '@/views/recycleOrder/components/order-timeline.vue';
  import SimpleForm from '@/components/CommonPage/SimpleForm.vue';
  import validators from '@/utils/validators';
  import { EleMessage } from 'ele-admin-plus/es';
  let { proxy } = getCurrentInstance();

  const props = defineProps({
    items: { type: Array, default: () => [] },
    title: { type: String, default: '编辑' },
    width: { type: String, default: '520px' },
    labelWidth: { type: String, default: '90px' },
    formProps: { type: Object, default: () => ({}) },
    baseUrl: { type: Object, default: () => ({}) }
  });
  const emit = defineEmits(['success']);
  /** 弹窗是否打开 */
  const visible = defineModel({ type: Boolean });

  /** 关闭弹窗 */
  const handleCancel = () => {
    visible.value = false;
    nextTick(() => {
      formRef.value?.resetForm();
    });
  };

  const form = ref({});
  /** 弹窗打开事件 */
  const handleOpen = (data) => {
    visible.value = true;
    nextTick(() => {
      form.value = data;
      formRef.value?.assignFields(data);
    });
  };

  const formRef = ref();
  const handleSumbit = () => {
    formRef.value?.submitForm().then((data) => {
      data.id = form.value?.id;
      let url = data.id ? props.baseUrl.update : props.baseUrl.add;
      proxy.$http.post(url, data).then((res) => {
        if (res.data.code !== 200) return;
        visible.value = false;
        emit('success', data);
        EleMessage.success(form.id ? '编辑成功' : '新增成功');
      });
    });
  };

  defineExpose({
    handleOpen,
    handleSumbit
  });
</script>
