<template>
  <Modal
    centered
    :maskClosable="false"

    width="650px"
    destroyOnClose
    :title="props.data?.id ? '编辑' : '新增'"
    @ok="handleSave"
    @cancel="handleCancel"
    okText="确定"
    cancelText="取消"
    :confirmLoading="loading"
    v-model:open="visible"
  >
    <div style="margin-top: 10px; padding: 0 20px">
      <Form :layout="'vertical'" ref="formRef" :rules="rules" :model="modelRef">
        <FormItem label="名称" name="name">
          <Input v-model:value="modelRef.name" placeholder="请输入名称" />
        </FormItem>
        <FormItem label="说明" name="describe">
          <Textarea v-model:value="modelRef.description" placeholder="请输入说明" showCount :maxlength="200" :rows="4" />
        </FormItem>
      </Form>
    </div>
  </Modal>
</template>

<script lang="ts" setup>
  import { saveRule, modify } from '../../../../api/rule-engine/instance';
  // @ts-ignore
  import { message, Modal, Form, FormItem, Textarea, Input } from 'linker-ui-components';
  import { ref } from 'vue';
  import { getImage } from "@jdlinker/utils";

  const visible = ref<boolean>(false);
  const emit = defineEmits(['success', 'closeSave']);
  const props = defineProps({
    data: {
      type: Object
    }
  });

  const loading = ref<boolean>(false);
  const formRef = ref();
  const modelRef = ref();
  modelRef.value = { ...props.data };
  const rules = {
    name: [
      {
        required: true,
        message: '请输入名称'
      },
      {
        max: 64,
        message: '最多输入64个字符'
      }
    ]
  };
  const handleCancel = () => {
    emit('closeSave');
  };

  const handleSave = () => {
    formRef.value
      .validate()
      .then(async () => {
        loading.value = true;
        if (!modelRef.value?.id) {
          let resp = await saveRule(modelRef.value);
          loading.value = false;
          if (resp) {
            message.success('操作成功！');
            emit('closeSave');
            emit('success');
          } else {
            message.error('操作失败');
          }
        } else {
          let resp = await modify(modelRef.value?.id, modelRef.value);
          loading.value = false;
          if (resp) {
            message.success('操作成功！');
            emit('closeSave');
            emit('success');
          } else {
            message.error('操作失败！');
          }
        }
      })
      .catch((err: any) => {
        console.log('error', err);
      });
  };

  const show = (data: any) => {
    visible.value = true;
  };

  defineExpose({
    show: show
  });
</script>
