<template>
  <BasicModal v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="40%" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './config.data';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { updateLayer2d, saveOneLayer2d } from '/@/api/twoAndThree/menu';
import { metaModel } from '/@/api/system/model/menuModel';

export default defineComponent({
  name: 'MenuDrawer',
  components: { BasicForm, BasicModal },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);
    var _id = null;

    const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
      labelWidth: 100,
      schemas: formSchema,
      showActionButtonGroup: false,
      baseColProps: { lg: 24, md: 24 },
    });

    //默认传递页面数据
    const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
      resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;

      //如果是编辑操作，设置页面数据
      if (unref(isUpdate)) {
        console.log("编辑:", data)
        //为表单赋值
        if (data.record.view) data.record.view = JSON.stringify(data.record.view)
        if (data.record.subdomains) data.record.subdomains = JSON.stringify(data.record.subdomains)
        _id = data.record._id;
        setFieldsValue({
          ...data.record,
        });
      }
    });

    //得到页面标题
    const getTitle = computed(() => !unref(isUpdate) ? '创建图层' : '编辑图层');

    //提交按钮
    async function handleSubmit() {
      try {
        const values = await validate();
        setModalProps({ confirmLoading: true });
        console.log("values:", values)

        if (values.view) values.view = JSON.parse(values.view);
        if (values.subdomains) values.subdomains = JSON.parse(values.subdomains);
        if (values.title) values.name = values.title;


        if (unref(isUpdate)) {
          // updateMenu
          await updateLayer2d(values, unref(isUpdate) ? _id : null);
        } else {
          // saveMenu
          await saveOneLayer2d(values);
        }
        closeModal(); //关闭侧框
        emit('success');
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    return { registerDrawer, registerForm, getTitle, handleSubmit };
  },
});
</script>
