<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <SimpleForm ref="formRef" class="pt-4" :formProps="formProps" :formModel="state.formModel" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { add, getInfo, edit } from '/@/api/system/oa';

  import { formProps } from './noticesConfig';
  import { cloneDeep } from 'lodash-es';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  import { OaType } from '/@/enums/oa';

  const emit = defineEmits(['success', 'register']);

  const { notification } = useMessage();
  const { filterFormSchemaAuth } = usePermission();
  const formRef = ref();
  formProps.schemas = filterFormSchemaAuth(formProps.schemas!);
  const state = reactive({
    formModel: {},
    isUpdate: true,
    isView: false,
    isCopy: false,
    rowId: '',
  });

  const { t } = useI18n();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    state.isUpdate = !!data?.isUpdate;
    state.isView = !!data?.isView;
    state.isCopy = !!data?.isCopy;

    setModalProps({
      destroyOnClose: true,
      maskClosable: false,
      showCancelBtn: !state.isView,
      showOkBtn: !state.isView,
      canFullscreen: true,
      width: 600,
    });
    const viewformProps = cloneDeep(formProps);
    setDisabled(viewformProps.schemas);
    formRef.value.setProps(state.isView ? viewformProps : formProps);

    if (state.isUpdate || state.isView || state.isCopy) {
      state.rowId = data.id;
      const record = await getInfo(data.id);
      formRef.value.setFieldsValue(record);
    } else {
      formRef.value.resetFields();
    }
  });

  const getTitle = computed(() => (state.isView ? '查看' : !state.isUpdate ? '新增' : '编辑'));

  function setDisabled(schemas) {
    const layoutComponents = ['tab', 'grid', 'card'];
    schemas?.map((info) => {
      if (layoutComponents.includes(info.type!)) {
        info.children?.map((childInfo) => {
          childInfo.list.map((com) => {
            if (layoutComponents.includes(com.type)) {
              setDisabled(childInfo.list);
            } else {
              com.dynamicDisabled = true;
            }
          });
        });
      } else if (info.type == 'table-layout') {
        info.children?.map((childInfo) => {
          childInfo.list.map((com) => {
            com.children.map((el) => {
              if (layoutComponents.includes(el.type) || el.type == 'table-layout') {
                setDisabled(com.children);
              } else {
                el.dynamicDisabled = true;
              }
            });
          });
        });
      } else if (info.type == 'one-for-one') {
        setDisabled(info.componentProps.childSchemas);
      } else {
        info.dynamicDisabled = true;
      }
    });
  }

  async function handleSubmit() {
    try {
      let values = await formRef.value?.validate();
      //添加隐藏组件
      if (formProps.hiddenComponent?.length) {
        formProps.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
      setModalProps({ confirmLoading: true });
      values = { ...values, typeId: OaType.NOTICE };
      // TODO custom api
      if (!state.isUpdate || state.isCopy) {
        //false 新增
        await add(values);
        notification.success({
          message: 'Tip',
          description: t('新增成功！'),
        }); //提示消息
      } else {
        values.id = state.rowId;
        await edit(values);
        notification.success({
          message: 'Tip',
          description: t('修改成功！'),
        }); //提示消息
      }

      closeModal();
      formRef.value.resetFields();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleClose() {
    formRef.value.resetFields();
  }
</script>
<style lang="less" scoped>
  .custom-modal-padding-box {
    height: 100%;
    padding: 16px;
  }
</style>
