<template>
  <DesktopLayout v-if="show">
    <template #head>
      <DesignHead :title="t('打印模板设计')">
        <template #steps
          ><a-steps :current="current">
            <a-step v-for="item in steps" :key="item.title" :title="item.title" />
          </a-steps>
        </template>
        <template #buttons>
          <div class="design-button">
            <a-button
              :type="current == 0 ? '' : 'primary'"
              :disabled="current == 0"
              @click="prev"
              class="common-button"
            >
              {{ t('上一步') }} >
            </a-button>
            <a-button
              :type="current == steps.length - 1 ? '' : 'primary'"
              :disabled="current == steps.length - 1"
              class="common-button"
              @click="next"
              >{{ t('下一步') }} ></a-button
            >
            <a-button
              :type="current == 0 ? '' : 'warning'"
              class="common-button"
              :disabled="current == 0"
              @click="save"
              >{{ t('保存') }}</a-button
            >
            <a-button type="error" class="clean-icon" @click="$emit('close')">{{
              t('关闭')
            }}</a-button>
          </div>
        </template>
      </DesignHead>
    </template>
    <Basic
      v-if="current == 0"
      :basicData="data.basicData"
      :apiConfig="data.apiConfig"
      ref="basicRef"
    />
    <iframe v-if="current == 1" ref="iframe" :src="printIframeUrl" class="iframe-box"></iframe>
    <LoadingBox v-if="showLoading" />
  </DesktopLayout>
</template>

<script setup lang="ts">
  import DesignHead from '/@/views/generator/desktop/components//designer/layout/Head.vue';
  import DesktopLayout from '/@/views/generator/desktop/components/designer/layout/Desktop.vue';
  import Basic from './Basic.vue';
  import { computed, nextTick, onMounted, reactive, ref } from 'vue';
  import { PrintBasicData } from '/@/model/generator/print';
  import { getPrintData } from './hooks/usePrintData';
  import { iframeUrl } from './config';
  import { ApiConfig } from '/@/components/ApiConfig/src/interface';
  import { LoadingBox } from '/@/components/ModalPanel/index';
  import { addDesign, editDesign } from '/@/api/system/generator/print';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getAppEnvConfig } from '/@/utils/env';
  let iframe = ref();
  const current = ref<number>(0);
  let basicRef = ref();
  let show = ref(false);
  const { notification } = useMessage();
  const { t } = useI18n();
  const showLoading = ref(false);
  const steps = [
    {
      title: t('基本配置'),
      content: t('基本配置'),
    },
    {
      title: t('打印设计'),
      content: t('打印设计'),
    },
  ];
  const props = withDefaults(
    defineProps<{
      editData: PrintBasicData;
    }>(),
    {
      editData: () => {
        return {
          id: '',
          code: '',
          name: '',
          icon: '',
          category: undefined,
          parentId: '',
          sortCode: 0,
          isMenu: 0,
          remark: '',
          apiConfig: '',
          content: '',
        };
      },
    },
  );
  let emits = defineEmits(['close']);
  const printIframeUrl = computed(() => {
    return iframeUrl + '?type=' + data.urlType;
  });
  const data: {
    basicData: PrintBasicData;
    printData: Object;
    apiConfig: ApiConfig;
    apiFields: Array<{ text: string; field: string }>;
    subTabulation: Array<{
      text: string;
      field: string;
      columns: Array<{ text: string; field: string }>;
    }>;
    isSave: boolean;
    isHoldPrevSave: boolean;
    urlType: number;
  } = reactive({
    basicData: {
      code: '',
      name: '',
      icon: '',
      category: undefined,
      parentId: '',
      apiConfig: '',
      sortCode: 0,
      isMenu: 0,
      remark: '',
      content: '',
    },
    apiConfig: {
      id: '5e6d0b195f9947b683cc526171fdb75c',
      name: '多个子表',
      method: 'GET',
      path: 'PrintTemplate/multi-table',
      requestParamsConfigs: [
        {
          name: 'id',
          dataType: 'Long',
          assignmentType: 'value',
          value: '1632565362742263809',
          config: '',
        },
        {
          name: 'deptId',
          dataType: 'Long',
          assignmentType: 'value',
          value: '1650072894457032705',
          config: '',
        },
      ], //Query Params
      requestHeaderConfigs: [], //Header
      requestBodyConfigs: [], //Body
    },
    apiFields: [],
    subTabulation: [],
    printData: {},
    isSave: false,
    isHoldPrevSave: false,
    urlType: Math.random() * 10,
  });
  onMounted(async () => {
    if (props.editData.id) {
      data.basicData = props.editData;
      data.apiConfig = JSON.parse(props.editData.apiConfig);
    }
    show.value = true;
  });
  const next = async () => {
    if (current.value == 0) {
      let validate = await basicRef.value.validateForm();
      if (validate) {
        data.apiConfig = basicRef.value.getApiData();
        data.basicData = basicRef.value.getBasicData();
        data.basicData.apiConfig = JSON.stringify(data.apiConfig);
        current.value++;
        await nextTick();
        iframe.value.onload = function () {
          sendMessage();
          window.addEventListener('message', function (event) {
            if (
              event.data.urlType == data.urlType &&
              event.origin === getAppEnvConfig().VITE_GLOB_PRINT_BASE_URL
            ) {
              if (!data.isSave) {
                data.isSave = true;
                data.basicData.content = event.data.json;
                showLoading.value = true;
                submit();
              }
            }
          });
        };
      }
    }
  };
  const prev = () => {
    holdSave();
  };
  async function sendMessage() {
    try {
      let printData = await getPrintData(data.apiConfig);
      let json = '';
      // 编辑
      if (data.basicData.content) {
        json = data.basicData.content;
      }
      let info = {
        type: 'api',
        fields: printData.apiFields,
        subTabulation: printData.subTabulation,
        printData: printData.data,
        json,
      };
      var wn = iframe.value.contentWindow;
      wn.postMessage(info, getAppEnvConfig().VITE_GLOB_PRINT_BASE_URL);
    } catch (error) {}
  }
  function save() {
    data.isSave = false; //防止重复发送消息 重复提交
    data.isHoldPrevSave = false;
    var wn = iframe.value.contentWindow;
    wn.postMessage({ type: 'save' }, getAppEnvConfig().VITE_GLOB_PRINT_BASE_URL);
  }
  function holdSave() {
    data.isSave = false; //防止重复发送消息 重复提交
    data.isHoldPrevSave = true;
    var wn = iframe.value.contentWindow;
    wn.postMessage({ type: 'save' }, getAppEnvConfig().VITE_GLOB_PRINT_BASE_URL);
  }
  async function submit() {
    if (data.isHoldPrevSave) {
      current.value--;
      showLoading.value = false;
      return true;
    }
    try {
      if (data.basicData.id) {
        let res = await editDesign(data.basicData);
        if (res) {
          notification.success({
            message: t('提示'),
            description: t('编辑成功'),
          }); //提示消息
          close();
        }
      } else {
        let res = await addDesign(data.basicData);
        if (res) {
          notification.success({
            message: t('提示'),
            description: t('新增成功'),
          }); //提示消息
          close();
        }
      }
    } catch (error) {}
  }
  function close() {
    setTimeout(() => {
      data.isSave = true;
      showLoading.value = false;
      emits('close');
    }, 1);
  }
</script>

<style scoped lang="less">
  .iframe-box {
    width: 100%;
    height: 100%;
  }

  .common-button {
    margin-right: 16px;
    width: 82px;
    border-radius: 4px;
  }

  .ant-btn-warning:not(.ant-btn-link, .is-disabled) {
    background-color: #f70;
    border-color: #f70;
  }

  .clean-icon {
    width: 82px;
    border-radius: 4px;
  }

  .ant-steps {
    width: 464px;
  }
</style>
