<template>
  <BasicModal
    v-if="formType === 'modal'"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :height="formHeight ? formHeight : undefined"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <SimpleForm
      ref="formRef"
      class="pt-4"
      :formProps="formProps"
      :formModel="state.formModel"
      :isCamelCase="false"
    />
    <template #footer v-if="formButtons && formButtons.length > 0 && !state.isView">
      <template v-for="(item, index) in sortBy(formButtons, 'index')" :key="item.key">
        <template v-if="item.isShow">
          <CustomButtonModal v-if="item.type == CustomButtonModalType.Modal" :info="item" />
          <a-button
            :type="item.style"
            v-else
            :style="{ marginLeft: index > 0 ? '10px' : 0 }"
            @click="customClick(item)"
          >
            {{ t(item.name) }}
          </a-button>
        </template>
      </template>
    </template>
  </BasicModal>
  <BasicDrawer
    v-else-if="formType === 'drawer'"
    v-bind="$attrs"
    :showFooter="!state.isView"
    @register="registerDrawer"
    :title="getTitle"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <SimpleForm
      ref="formRef"
      :formProps="formProps"
      :formModel="state.formModel"
      :isCamelCase="false"
    />
    <template #footer v-if="formButtons && formButtons.length > 0 && !state.isView">
      <template v-for="(item, index) in sortBy(formButtons, 'index')" :key="item.key">
        <template v-if="item.isShow">
          <CustomButtonModal v-if="item.type == CustomButtonModalType.Modal" :info="item" />
          <a-button
            :type="item.style"
            v-else
            :style="{ marginLeft: index > 0 ? '10px' : 0 }"
            @click="customClick(item)"
          >
            {{ t(item.name) }}
          </a-button>
        </template>
      </template>
    </template>
  </BasicDrawer>

  <div class="h-full bg-white rounded-2xl pt-4" v-else>
    <div :style="{ height: isShowBtn ? 'calc(100% - 76px)' : '100%' }" class="overflow-y-auto">
      <SimpleForm
        ref="formRef"
        :formProps="formProps"
        :formModel="state.formModel"
        :isCamelCase="false"
      />
    </div>
    <div
      class="flex mx-auto justify-between w-54 mt-6 absolute left-0 right-0 bottom-5"
      v-if="
        (listPageMode == LIST_MODE.VERTICAL && isShowBtn) ||
        (listPageMode == LIST_MODE.HORIZONTAL && !state.isView)
      "
    >
      <template v-if="formButtons && formButtons.length > 0">
        <template v-for="(item, index) in sortBy(formButtons, 'index')" :key="item.key">
          <template v-if="item.isShow">
            <CustomButtonModal v-if="item.type == CustomButtonModalType.Modal" :info="item" />
            <a-button
              :type="item.style"
              :style="{ marginLeft: index > 0 ? '10px' : 0 }"
              @click="customClick(item)"
            >
              {{ t(item.name) }}
            </a-button>
          </template>
        </template>
      </template>
      <template v-else>
        <a-button @click="handleReset" class="!h-10 w-25">重置</a-button>
        <a-button type="primary" @click="handleSubmit" class="!h-10 w-25">确认</a-button>
      </template>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, reactive, provide, Ref, nextTick, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  import { addFormExecute, getFormExecute, updateFormExecute } from '/@/api/form/execute';
  import { cloneDeep, sortBy } from 'lodash-es';
  import {
    createFormEvent,
    getFormDataEvent,
    loadFormEvent,
    submitFormEvent,
  } from '/@/hooks/web/useFormEvent';
  import { apiConfigFunc } from '/@/utils/event/design';
  import { ApiConfig } from '/@/model/generator/listConfig';
  import { LIST_MODE } from '/@/enums/formViewEnum';
  import { buttonListInfo } from '/@/components/Designer';
  import { executeCurFormEvent } from '/@/utils/event/data';
  import { changeSchemaDisabled } from '/@/hooks/web/useWorkFlowForm';
  import { CustomButtonModalType } from '/@/enums/userEnum';
  import CustomButtonModal from '/@/components/Form/src/components/CustomButtonModal.vue';
  const emit = defineEmits(['success', 'register', 'cancel']);
  const { notification } = useMessage();
  const { filterFormSchemaAuth } = usePermission();
  const formRef = ref();

  const formProps = ref<any>({});
  const props = defineProps({
    formType: String,
    formWidth: Number,
    formHeight: [Number, String],
    formButtons: Array<buttonListInfo>,
    formId: String,
    menuId: String,
    onlyShowAddForm: Boolean,
    listPageMode: String,
    isShowBtn: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
  });
  let releaseId = ``;
  const isCopy = ref<boolean>(false);
  const isNotable = ref<boolean>(false);
  const apiConfig = ref([]);
  const rowInfo = ref({});
  const state = reactive({
    formModel: {},
    isUpdate: true,
    isView: false,
    isCopy: false,
    rowId: '',
    pkField: 'id',
    formEventConfig: [],
    menuName: '',
  });
  const cloneFormModal = ref({});
  provide<Ref<boolean>>('isCopy', isCopy);
  provide<Ref<string>>('currentFormId', ref(props.formId || ''));
  const { t } = useI18n();

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    if (props.formType === 'modal') {
      handleInner(data, setModalProps);
    }
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    if (props.formType === 'drawer') {
      handleInner(data, setDrawerProps);
    }
  });

  const getTitle = computed(() =>
    state.isView ? t('查看') : state.isUpdate ? t('编辑') : isCopy.value ? '复制数据' : t('新增'),
  );

  watch(
    () => state.formModel,
    () => {
      if (!state.isUpdate && !state.isView && !isCopy.value && props.formType === 'normal') {
        cloneFormModal.value = cloneDeep(state.formModel);
      }
    },
    {
      deep: true,
    },
  );
  async function handleInner(data, setPropsData?) {
    formProps.value = cloneDeep(data.formProps);
    state.formEventConfig = data.formEventConfig;
    state.isView = !!data?.isView;
    state.isUpdate = !!data?.isUpdate;
    isCopy.value = !!data?.isCopy;
    state.menuName = data.menuName;
    state.pkField = data.pkField;
    isNotable.value = !!data.isNotable;
    if (isNotable.value) {
      apiConfig.value = data.apiConfig;
      rowInfo.value = data.record;
    }

    releaseId = data.releaseId;
    formProps.value.schemas = filterFormSchemaAuth(formProps.value.schemas!);

    const viewformProps = cloneDeep(data.formProps);
    changeSchemaDisabled(viewformProps.schemas);

    formRef.value.setProps(state.isView ? viewformProps : formProps.value);
    if (props.formType === 'normal' && Object.entries(cloneFormModal.value).length > 0) {
      let tempModal = cloneDeep(cloneFormModal.value);
      delete tempModal[state.pkField];
      formRef.value.setFieldsValue(tempModal);
      if (props.listPageMode == LIST_MODE.VERTICAL || props.listPageMode == LIST_MODE.HORIZONTAL) {
        if (!state.isUpdate && !state.isView && !isCopy.value) {
          formRef.value.resetReadonlyFields();
        }
      }
    } else {
      await formRef.value.setDefaultValue();

      if (!state.isUpdate && !state.isView && !isCopy.value) {
        formRef.value.resetFields();
      }
    }

    //初始化表单
    createFormEvent(
      state.formEventConfig,
      state.formModel,
      formRef.value,
      formProps.value.schemas,
      false,
      state.menuName,
      props.formId,
    );

    if (state.isUpdate || state.isView || isCopy.value) {
      let record;
      if (isNotable.value) {
        const viewConfig = (apiConfig.value as ApiConfig[]).find((item) => item.value === 'view');
        const listConfig = (apiConfig.value as ApiConfig[]).find(
          (item) => item.value === 'view',
        )?.outputConfig;
        record = await apiConfigFunc(viewConfig, false, rowInfo.value);
        for (let key in record) {
          listConfig?.forEach((config) => {
            const apiFieldArr = config.apiField.split(',');
            const bindFieldArr = config.bindField.split(',');
            if (config.apiField === key) {
              record[config.bindField!] = record[key];
            } else if (apiFieldArr.length > 1) {
              const bindTable = bindFieldArr[0] + 'List';
              record[apiFieldArr[0]].forEach((info, index) => {
                if (!record[bindTable]) record[bindTable] = [];

                if (record[bindTable][index]) {
                  record[bindTable][index][bindFieldArr[1]] = info[apiFieldArr[1]];
                } else {
                  record[bindTable].push({
                    [bindFieldArr[1]]: info[apiFieldArr[1]],
                  });
                }
              });
            }
          });
        }
      } else {
        state.rowId = data.id;
        record = await getFormExecute({ releaseId, id: state.rowId });
      }

      formRef.value.setFieldsValue(record);
      //获取表单数据
      getFormDataEvent(
        state.formEventConfig,
        state.formModel,
        formRef.value,
        formProps.value.schemas,
        false,
        state.menuName,
        props.formId,
      );
    }

    await nextTick();

    //加载表单
    loadFormEvent(
      state.formEventConfig,
      state.formModel,
      formRef.value,
      formProps.value.schemas,
      false,
      state.menuName,
      props.formId,
    );

    if (setPropsData) {
      console.log('props.formButtons : ', props.formButtons);
      setPropsData({
        destroyOnClose: true,
        maskClosable: false,
        showCancelBtn: props.formButtons && props.formButtons?.length > 0 ? false : !state.isView,
        showOkBtn: props.formButtons && props.formButtons?.length > 0 ? false : !state.isView,
        canFullscreen: true,
        width: props.formWidth,
        footer: state.isView ? null : undefined,
        defaultFullscreen: props.formType === 'modal' ? true : false,
      });
    }
  }

  function handleReset() {
    formRef.value.resetFields();
  }
  async function handleSubmit() {
    try {
      const values = await formRef.value?.validate();
      //添加隐藏组件
      if (formProps.value.hiddenComponent?.length) {
        formProps.value.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
      if (props.formType !== 'normal') {
        props.formType === 'modal'
          ? setModalProps({ confirmLoading: true })
          : setDrawerProps({ confirmLoading: false });
      }
      // TODO custom api
      if (!state.isUpdate) {
        //false 新增
        if (isNotable.value) {
          const addConfig = (apiConfig.value as ApiConfig[]).find((item) => item.value === 'add');
          await apiConfigFunc(addConfig, false, values);
        } else {
          await addFormExecute({ releaseId, formData: values });
        }

        notification.success({
          message: t('提示'),
          description: isCopy.value ? '复制成功' : t('新增成功！'),
        }); //提示消息
      } else {
        if (isNotable.value) {
          const editConfig = (apiConfig.value as ApiConfig[]).find((item) => item.value === 'edit');
          await apiConfigFunc(editConfig, false, values);
        } else {
          values[state.pkField] = state.rowId;
          await updateFormExecute({ releaseId, formData: values });
        }

        notification.success({
          message: t('提示'),
          description: t('修改成功！'),
        }); //提示消息
      }

      //提交表单事件
      submitFormEvent(
        state.formEventConfig,
        state.formModel,
        formRef.value,
        formProps.value.schemas,
        false,
        state.menuName,
        props.formId,
      );
      if (props.formType !== 'normal') {
        props.formType === 'modal' ? closeModal() : closeDrawer();
      }
      formRef.value.resetFields();

      // if (props.onlyShowAddForm) {
      //   formRef.value.resetFields();
      // }
      emit('success');
    } catch (error) {
    } finally {
      if (props.formType !== 'normal') {
        props.formType === 'modal'
          ? setModalProps({ confirmLoading: false })
          : setDrawerProps({ confirmLoading: false });
      }
    }
  }

  function handleClose() {
    formRef.value.resetFields();
    emit('cancel');
  }
  function customClick(item) {
    if (item.key == 'confirm') {
      handleSubmit();
    } else if (item.key == 'cancel' && props.formType !== 'normal') {
      handleClose();
      props.formType === 'modal' ? closeModal() : closeDrawer();
    } else if (item.key == 'reset') {
      formRef.value.resetFields();
    } else {
      executeCurFormEvent(item.event, state.formModel);
    }
  }
  defineExpose({
    handleInner,
  });
</script>
