<template>
  <!-- iframe组件 -->
  <div :class="prefixCls" :style="getWrapStyle">
    <Spin :spinning="loading" size="large" :style="getWrapStyle">
      <iframe
        :src="iframeUrl"
        :class="`${prefixCls}__main`"
        ref="frameRef"
        @load="hideLoading"
      ></iframe>
    </Spin>
  </div>
</template>
<script lang="ts" setup>
  import type { CSSProperties } from 'vue';
  import { ref, reactive, unref, computed, watch, inject } from 'vue';
  import { Spin } from 'ant-design-vue';
  import { useWindowSizeFn } from '/@/hooks/event/useWindowSizeFn';
  import { propTypes } from '/@/utils/propTypes';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useLayoutHeight } from '/@/layouts/default/content/useContentViewHeight';
  import { apiConfigFunc, camelCaseString } from '/@/utils/event/design';

  const props = defineProps({
    url: propTypes.string.def(''),
    id: {
      //组件key值
      type: String,
      default: () => {
        return '';
      },
    },
    list: {
      type: Array,
      default: () => {
        return [];
      },
    },
    width: String,
    height: String,
  });

  const loading = ref(true);
  const topRef = ref(50);
  const heightRef = ref(window.innerHeight);
  let frameRef = ref();
  const { headerHeightRef } = useLayoutHeight();
  const iframeUrl = ref('');
  const { prefixCls } = useDesign('iframe-page');
  useWindowSizeFn(calcHeight, 150, { immediate: true });
  const formAssignmentData = inject('formAssignmentData');
  const formModel = inject<any>('formModel', null);
  const isCamelCase = inject<boolean>('isCamelCase', false);

  const state = reactive({
    iframeList: [] as any[],
  });

  watch(
    () => props.url,
    (val) => {
      state.iframeList = props.list;
      changeListValue(val);
    },
    {
      immediate: true,
    },
  );
  const getWrapStyle = computed((): CSSProperties => {
    return {
      width: props.width,
      height: props.height || `${unref(heightRef)}px`,
    };
  });

  function calcHeight() {
    const iframe = unref(frameRef);
    if (!iframe) {
      return;
    }
    const top = headerHeightRef.value;
    topRef.value = top;
    heightRef.value = window.innerHeight - top;
    const clientHeight = document.documentElement.clientHeight - top;
    iframe.style.height = `${clientHeight}px`;
  }

  function hideLoading() {
    loading.value = false;
    calcHeight();
  }
  async function getFormAssignmentIframeUrl(url) {
    let tempMap = new Map();
    if (props.id) {
      if (formAssignmentData) {
        for (const key in formAssignmentData) {
          if (Object.prototype.hasOwnProperty.call(formAssignmentData, key)) {
            const element = formAssignmentData[key];
            if (props.id && element) {
              for (const key2 in element) {
                if (Object.prototype.hasOwnProperty.call(element, key2)) {
                  if (key2.includes(props.id)) {
                    const element2 = element[key2];
                    if (key2.includes('---iframe---')) {
                      let keyArr = key2.split('---iframe---');
                      if (keyArr.length > 1) {
                        let key3 = keyArr[1];
                        tempMap.set(key3, element2);
                      }
                    }
                  }
                }
              }
            }
          }
        }
        state.iframeList.forEach((element: { name: string; value: string }) => {
          if (url.includes(element.name)) {
            let value = element.value;
            if (tempMap.has(element.name)) {
              value = tempMap.get(element.name);
            }
            url = url.replace(element.name, value);
          }
        });
      } else {
        for (const item of state.iframeList) {
          let value = '';
          if (item.type === 'form') {
            watch(
              () => formModel,
              () => {
                changeListValue(props.url);
              },
              {
                deep: true,
              },
            );
            const bindField = !isCamelCase ? item.config : camelCaseString(item.config);
            value = formModel[bindField];
          } else if (item.type === 'api') {
            value = await apiConfigFunc(item.config, isCamelCase, formModel);
          }
          if (url.includes(item.name)) {
            url = url.replace(item.name, value);
          }
        }
      }
    }
    return url;
  }
  async function changeListValue(val) {
    let url = await getFormAssignmentIframeUrl(val);
    iframeUrl.value = url;
  }
  async function sendMessage(otherParams = {}, type = 'submit') {
    try {
      let info = {
        type,
        url: iframeUrl.value,
        ...otherParams,
      };
      var wn = frameRef.value.contentWindow;
      wn.postMessage(info, iframeUrl.value);
    } catch (error) {}
  }
  defineExpose({
    sendMessage,
  });
  /* 
  iframe组件添加参数，流程设计中，通过流程参数赋值给iframe参数，并在流程发起，审批时，
  iframe组件根据流程表单赋值显示变化url，在点击发起按钮或者审批按钮的时候
   可向iframe网站发送消息，iframe网站能接收消息进行处理

    iframe 项目中如何接收传参处理事件，只要在对应页面加上一个监听即可。
    window.addEventListener("message", function (event) {
      if (event.data.type == "submit") {
        //  TODO 你的代码  处理消息
        // console.log('event: ', event);
        // alert('处理代码');
      }
    });

  */
</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-iframe-page';

  .@{prefix-cls} {
    .ant-spin-nested-loading {
      position: relative;
      height: 100%;

      .ant-spin-container {
        width: 100%;
        height: 100%;
        padding: 10px;
      }
    }

    &__mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

    &__main {
      width: 100%;
      height: 100%;
      overflow: hidden;
      background-color: @component-background;
      border: 0;
      box-sizing: border-box;
    }
  }
</style>
