<template>
  <div>
    <a-button type="primary" @click="showModal" :disabled="disabled">{{ title }}</a-button>
    <BasicModal
      @register="registerModal"
      :title="title"
      :width="modalWidthUnit ? modalWidth + modalWidthUnit : modalWidth ? modalWidth : 1000"
      :height="height"
      :footer="buttonList && buttonList.length > 0 ? undefined : null"
      wrap-class-name="custom-model-height"
      @visible-change="handleVisible"
      @ok="handleConfirm"
      @cancel="handleCancel"
    >
      <SimpleForm
        :key="renderKey"
        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)"
          >
            {{ item.name }}
          </a-button>
        </template>
      </template>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { inject, ref, computed } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  import { getModalManage } from '/@/api/dataconfig/modalmanage';
  import { notification } from 'ant-design-vue';
  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 { sortBy } from 'lodash-es';
  import { executeCurFormEvent } from '/@/utils/event/data';

  const userStore = useUserStore();
  const props = defineProps({
    title: String,
    innerParams: Array,
    outParams: Array,
    bindModal: String,
    modalWidth: Number,
    modalWidthUnit: String,
    modalHeight: Number,
    modalHeightUnit: String,
    disabled: Boolean,
    events: Object,
  });
  const renderKey = ref(0);
  const emit = defineEmits(['open', 'close', 'confirm', 'cancel', 'click']);
  const { t } = useI18n();
  const mainformModel = inject<Recordable>('formModel');
  //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 buttonList = ref([]);
  const [registerModal, { openModal, closeModal }] = useModal();
  const height = computed(() => {
    return props.modalHeightUnit &&
      props.modalHeight !== undefined &&
      props.modalHeight !== null &&
      props.modalHeight >= 0
      ? props.modalHeight + props.modalHeightUnit
      : props.modalHeight !== undefined && props.modalHeight !== null && props.modalHeight >= 0
      ? props.modalHeight
      : undefined;
  });

  const showModal = async () => {
    renderKey.value++;
    if (props.bindModal) {
      let res: any = await getModalManage(props.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();
      }
      if (props.events && props.events.click) {
        if (props.events.click.includes('formActionType.customOpenModal')) {
          emit('click');
        } else {
          openModal();
          emit('click');
        }
      } else {
        openModal();
      }
    } else {
      notification.warning({
        message: t('未绑定弹窗'),
      });
    }
  };
  function resetData() {
    props.innerParams?.forEach(async (o: any) => {
      let data = JSON.parse(o.component);
      if (data.table) {
        if (data.field) formModel.value[data.field] = await getData(o);
      }
    });
  }
  function handleVisible(v) {
    setTimeout(async () => {
      if (v && formRef.value) {
        formRef.value.setFieldsValue(formModel.value);
        emit('open', formModel.value);
      } else if (!v) {
        emit('close', simpformModal.value);
      }
    }, 300);
  }
  async function getData(data) {
    if (data.type == 'value') {
      return data.value;
    } else if (data.type == 'api') {
      return await apiConfigFunc(data.apiConfig, isCamelCase, mainformModel);
    } 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) {
        if (newField) {
          return mainformModel[newField];
        }
      }
    }
  }
  async function handleConfirm() {
    try {
      const values = await formRef.value?.validate();
      props.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', values);
      closeModal();
      renderKey.value++;
    } catch (error) {}
  }
  async function handleCancel() {
    await resetData();
    formRef.value.setFieldsValue(formModel.value);
    emit('cancel', simpformModal.value);
    renderKey.value++;
  }
  function setMainData(table, field, value) {
    let newField = isCamelCase && field ? camelCaseString(field) : field;
    if (table && mainformModel) {
      if (table.includes('child')) {
        let newTable = isCamelCase ? camelCaseString(table + 'List') : table + 'List';
        if (newTable && !mainformModel[newTable]) {
          mainformModel[newTable] = [{}];
        }
        if (newField && newTable) mainformModel[newTable][0][newField] = value;
      } else {
        if (newField) mainformModel[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 customOpenModal = () => {
    openModal();
  };
  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();
      renderKey.value++;
    } else if (item.key == 'reset') {
      await resetData();
      formRef.value.setFieldsValue(formModel.value);
      formRef.value.clearValidate();
    } else {
      executeCurFormEvent(item.event, simpformModal.value, isCamelCase, {
        formApi: {
          validateModal: customValidateModal,
          customModalClose: closeModal,
        },
      });
    }
  }
  defineExpose({
    customOpenModal,
  });
</script>
