<template>
  <Modal
    centered
    :title="title"
    :width="750"
    :confirm-loading="loading"
    :maskClosable="false"
    @cancel="emit('close')"
    @ok="handleOk"
    v-model:open="visible"
  >
    <div style="margin-top: 20px; padding: 0 20px">
      <Form layout="vertical" name="scene-save" ref="formRef" :model="formModel">
        <FormItem
          name="name"
          label="名称"
          :rules="[
            { required: true, message: '请输入名称' },
            { max: 64, message: '最多输入64个字符' }
          ]"
        >
          <Input v-model:value="formModel.name" placeholder="请输入名称" />
        </FormItem>
        <FormItem :name="['trigger', 'type']" label="触发方式" :rules="[{ required: true, message: '请选择触发方式' }]">
          <TriggerWay v-model:modelValue="formModel.trigger.type" :disabled="disabled" />
        </FormItem>
      </Form>
    </div>
  </Modal>
</template>

<script setup lang="ts">
  import { SceneItem } from '../typings';
  import TriggerWay from './components/TriggerWay.vue';
  import type { PropType } from 'vue';
  import type { FormInstance } from 'ant-design-vue';
  import { save, modify } from '../../../../api/rule-engine/scene';
  import { ref, reactive, watchEffect, computed } from 'vue';
  // @ts-ignore
  import { Modal, Form, FormItem, Input } from 'linker-ui-components';

  type Emit = {
    (e: 'close'): void;
  };
  const visible = ref<boolean>(false);
  const loading = ref(false);
  const formModel = reactive({
    name: '',
    trigger: {
      type: 'device'
    }
  });

  const formRef = ref<FormInstance>();

  const props = defineProps({
    data: {
      type: Object as PropType<Partial<SceneItem>>,
      default: () => ({})
    }
  });

  watchEffect(() => {
    Object.assign(formModel, props.data);
  });

  const emit = defineEmits<Emit>();

  const title = computed(() => {
    return props.data?.id ? '编辑' : '新增';
  });

  const disabled = computed(() => {
    return !!props.data?.id;
  });

  const handleOk = async () => {
    if (formRef.value) {
      const values = await formRef.value.validateFields();
      let modelObj = { ...values };
      if (props.data.id) {
        modelObj = {
          ...props.data,
          name: values.name
        };
      }
      loading.value = true;
      const resp = props.data.id ? await modify(props.data.id, modelObj) : await save(modelObj);
      loading.value = false;
      if (resp.success) {
        const _id = props.data?.id || (resp.result as any).id;
        // @ts-ignore
        emit('close', _id);
        // const _id = props.data?.id || (resp.result as any).id
        // menuStory.jumpPage('rule-engine/Scene/Save', {}, { triggerType: values.trigger.type, id: _id })
      }
    }
  };

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

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