<template>
  <BasicModal v-bind="$attrs" @register="register" @ok="confirm" :title="getTitle" >
    <BasicForm @register="registerForm" :model="model" />
  </BasicModal>
</template>
<script lang="ts">

  import { computed, defineComponent, reactive, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { adapt } from '/@/utils/adapt'
  import { formSchema,  } from './data'
  import { useMessage } from '/@/hooks/web/useMessage';

  interface Menu {
    id: string|number
  }

  export default defineComponent({
    components: { BasicModal, BasicForm,  },


    setup(_, { emit }) {
      const { notification } = useMessage();
      const menu = reactive<Menu>({
        id: ''
      })

      const modelRef = ref({});
      const adaptWidth = adapt()
      const isUpdate = ref(true);

      const [registerForm, { getFieldsValue, updateSchema, setFieldsValue, resetFields/* validate*/ }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        actionColOptions: { span: 24 },
      });
      const [register, { closeModal } ] = useModalInner(data => {
        console.log('-------------------data---------------')
        console.log(data)
        resetFields()
        isUpdate.value = !!data?.isUpdate;
        // if (unref(isUpdate)) {
        //   setFieldsValue(data);
        // }
        setFieldsValue(data);
        menu.id = data.id
        updateSchema({
          field: 'parent',
          componentProps: { treeData: data.treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

      function confirm() {
        const info = getFieldsValue()
        if (menu.id) {
          info.id = menu.id
          if(info.id === info.parent) {
           notification.error({
              message: '错误!',
              description: "不能选择当前菜单作为上级菜单！",
              duration: 3,
            });
            return
          }
        }

        const data = {}
        for(let key  in info){
          if (info[key]) {
            data[key] = info[key]
          }
          // else {
          //   data[key] = null
          // }
        }
        console.log(data)
        console.log('-------------11--------------')
        emit('saveData', data)
        closeModal()  // 关闭弹窗
      }
      return {
        register,
        registerForm,
        getTitle,
        model: modelRef,
        confirm,
        adaptWidth,
      };
    },
  });
</script>
<style lang='less'>
.ant-form-item-label {
  text-align: center !important;
}

.tree-label {
  width: 20.6%;
  margin-top: 8px;
  margin-bottom: 1em;
  text-align: center;
}

@media (max-width: 639px) {
  .ant-form-item-label {
  line-height: 2.5715 !important;
  text-align: center !important;
 }

  .tree-label {
  width: 33%;
  margin-top: 8px;
  margin-bottom: 1em;
  text-align: center;
}
}
</style>
