<template>
  <BasicModal
    @register="registerModal"
    wrap-class-name="custom-model-height"
    :footer="buttonList && buttonList.length > 0 ? undefined : null"
    @visible-change="handleVisible"
    @ok="handleConfirm"
    @cancel="handleCancel"
  >
    <SimpleForm
      v-if="show"
      ref="formRef"
      :formProps="formDataProps"
      :formModel="{}"
      @model-change="
        (val) => {
          simpformModal = val;
        }
      "
    />
    <template #footer v-if="buttonList && buttonList.length > 0">
      <template v-for="(item, index) in sortBy(buttonList, 'index')" :key="item.key">
        <a-button
          :type="item.style"
          v-if="item.isShow"
          :style="{ marginLeft: index > 0 ? '10px' : 0 }"
          @click="customClick(item)"
        >
          {{ t(item.name) }}
        </a-button>
      </template>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { inject, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  import { getModalManage } from '/@/api/dataconfig/modalmanage';
  import { sortBy } from 'lodash-es';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { buildOption } from '/@/utils/helper/designHelper';
  import { apiConfigFunc, camelCaseString, isValidJSON } from '/@/utils/event/design';
  import { useUserStore } from '/@/store/modules/user';
  import { executeCurFormEvent } from '/@/utils/event/data';

  const userStore = useUserStore();
  const emit = defineEmits(['open', 'close', 'confirm', 'cancel']);
  const { t } = useI18n();
  const mainformModel = ref();
  const modalSetting = ref();
  const show = ref(false);
  const buttonList = ref([]);
  //const isCustomForm = inject<boolean>('isCustomForm', false);
  const isCamelCase = inject<boolean>('isCamelCase', false);
  const formDataProps = ref({});
  const formModel = ref({});
  const formRef = ref();
  const simpformModal = ref();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    modalSetting.value = data.modal;
    mainformModel.value = data.record;
    let res: any = await getModalManage(data.modal.bindModal);

    if (res) {
      const { configJson } = res;

      let json = JSON.parse(configJson);

      let formJson = json.formJson;
      buttonList.value = formJson.buttonList || [];
      formDataProps.value = buildOption(formJson, false);
      await resetData();
    }
    let height = coputedHeight(data.modal.modalHeight, data.modal.modalHeightUnit);
    await setModalProps({
      destroyOnClose: true,
      maskClosable: false,
      showCancelBtn: true,
      showOkBtn: true,
      canFullscreen: true,
      title: data.modal.title,
      height: height,
      width: data.modal.modalWidthUnit
        ? data.modal.modalWidth + data.modal.modalWidthUnit
        : data.modal.modalWidth
        ? data.modal.modalWidth
        : 1000,
    });
    show.value = true;

    setTimeout(() => {
      if (formRef.value) {
        formRef.value.setFieldsValue(formModel.value);
        emit('open', formModel.value);
      }
    }, 100);
  });
  function coputedHeight(modalHeight, modalHeightUnit) {
    return modalHeightUnit && modalHeight !== undefined && modalHeight !== null && modalHeight >= 0
      ? modalHeight + modalHeightUnit
      : modalHeight !== undefined && modalHeight !== null && modalHeight >= 0
      ? modalHeight
      : undefined;
  }
  function resetData() {
    modalSetting.value.innerParams?.forEach(async (o: any) => {
      let data = JSON.parse(o.component);
      if (data.table) {
        if (data.field) formModel.value[data.field] = await getData(o);
      }
    });
  }
  async function handleVisible(v) {
    if (!v) {
      await resetData();
      if (formRef.value) formRef.value.setFieldsValue(formModel.value);
      emit('close', simpformModal.value);
    }
  }
  async function getData(data) {
    if (data.type == 'value') {
      return data.value;
    } else if (data.type == 'api') {
      return await apiConfigFunc(data.apiConfig, isCamelCase, mainformModel.value);
    } else if (data.type == 'info') {
      return getUserInfo(data.value);
    } else if (data.type == 'form') {
      let json = isValidJSON(data.value);
      if (!json) return data.value;
      let newField = isCamelCase && json.field ? camelCaseString(json.field) : json.field;
      if (mainformModel.value) {
        if (newField) {
          return mainformModel.value[newField];
        }
      }
    }
  }
  async function handleConfirm() {
    try {
      const values = await formRef.value?.validate();
      modalSetting.value.outParams?.forEach(async (o: any) => {
        let data = JSON.parse(o.component);
        let maindata = o.mainComponent ? JSON.parse(o.mainComponent) : {};
        if (data.table && mainformModel) {
          if (data.field) {
            setMainData(maindata.table, maindata.field, values[data.field]);
          }
        }
      });
      emit('confirm', mainformModel.value);
      closeModal();
    } catch (error) {}
  }
  function handleCancel() {
    emit('cancel', simpformModal.value);
  }
  function setMainData(table, field, value) {
    let newField = isCamelCase && field ? camelCaseString(field) : field;
    if (table && mainformModel) {
      if (newField) mainformModel.value[newField] = value;
    }
  }

  function getUserInfo(val) {
    switch (val) {
      case '3-name':
        return userStore.getUserInfo.name;
      case '3-id':
        return userStore.getUserInfo.id;
      case '3-code':
        return userStore.getUserInfo.code;
      case '3-mobile':
        return userStore.getUserInfo.mobile;
      case '3-departmentName':
        return userStore.getUserInfo.departmentName;
      case '3-departmentId':
        return userStore.getUserInfo.departmentId;
      case '3-postId':
        return userStore.getUserInfo.postId;
      case '3-roleId':
        return userStore.getUserInfo.roleId;
    }
  }
  const customValidateModal = async () => {
    const values = await formRef.value?.validate();
    return values;
  };
  async function customClick(item) {
    if (item.key == 'confirm') {
      handleConfirm();
    } else if (item.key == 'cancel') {
      handleCancel();
      closeModal();
    } else if (item.key == 'reset') {
      await resetData();
      formRef.value.setFieldsValue(formModel.value);
    } else {
      executeCurFormEvent(item.event, simpformModal.value, isCamelCase, {
        curRow: mainformModel.value,
        formApi: { validateModal: customValidateModal, customModalClose: closeModal },
      });
    }
  }
</script>
