<template>
  <div>
    <a-button type="primary" @click="showModal">{{ title }}</a-button>
    <BasicDrawer
      @register="registerModal"
      :title="title"
      :push="false"
      :width="modalWidthUnit ? modalWidth + modalWidthUnit : modalWidth ? modalWidth : '50%'"
      :showFooter="true"
      :footerHeight="52"
      @visible-change="handleVisible"
      @ok="handleConfirm"
      @cancel="handleCancel"
    >
      <SimpleForm
        ref="formRef"
        :formProps="formDataProps"
        :formModel="{}"
        @model-change="
          (val) => {
            simpformModal = val;
          }
        "
      />
    </BasicDrawer>
  </div>
</template>

<script lang="ts" setup>
  import { inject, ref } from 'vue';
  import { BasicDrawer, useDrawer } from '/@/components/Drawer';
  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 } from '/@/utils/event/design';
  import { useUserStore } from '/@/store/modules/user';

  const userStore = useUserStore();
  const props = defineProps({
    title: String,
    innerParams: Array,
    outParams: Array,
    bindModal: String,
    modalWidth: Number,
    modalWidthUnit: String,
  });
  const emit = defineEmits(['open', 'close', 'confirm', 'cancel']);
  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 [registerModal, { openDrawer, closeDrawer }] = useDrawer();
  const showModal = async () => {
    if (props.bindModal) {
      let res: any = await getModalManage(props.bindModal);

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

        let json = JSON.parse(configJson);

        let formJson = json.formJson;
        formDataProps.value = buildOption(formJson, false);
        props.innerParams?.forEach(async (o: any) => {
          let data = JSON.parse(o.component);
          if (data.table) {
            if (data.table.includes('child')) {
              if (!formModel.value[data.table + 'List']) {
                formModel.value[data.table + 'List'] = [{}];
              }
              if (data.field)
                formModel.value[data.table + 'List'][0][data.field] = await getData(o);
            } else {
              if (data.field) formModel.value[data.field] = await getData(o);
            }
          }
        });
      }
      openDrawer();
    } else {
      notification.warning({
        message: t('未绑定弹窗'),
      });
    }
  };
  function handleVisible(v) {
    setTimeout(() => {
      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 = JSON.parse(data.value);
      let newField = isCamelCase && json.field ? camelCaseString(json.field) : json.field;
      if (mainformModel) {
        if (json.table?.includes('child')) {
          let newTable = isCamelCase ? camelCaseString(json.table + 'List') : json.table + 'List';
          if (newTable && mainformModel[newTable]) {
            return mainformModel[newTable][0][newField];
          }
        } else {
          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.table.includes('child')) {
            if (values[data.table + 'List']) {
              setMainData(
                maindata.table,
                maindata.field,
                values[data.table + 'List'][0][data.field],
              );
            }
          } else {
            if (data.field) {
              setMainData(maindata.table, maindata.field, values[data.field]);
            }
          }
        }
      });
      emit('confirm', values);
      closeDrawer();
    } catch (error) {}
  }
  function handleCancel() {
    emit('cancel', simpformModal.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;
    }
  }
</script>
