<template>
    <div class="page-wrapper">
        <editor v-show="showCom == 'EDITOR'" :linkInputDescImage="pageData.linkInputDescImage" @changeShowCom="changeShowCom" />
        <preview v-show="showCom == 'PREVIEW'"
            :previewData="previewData"
            :screenshotWebsiteData="screenshotWebsiteData"
            :showCom="showCom"
            :defaultLinkTitle="pageData.defaultLinkTitle"
            :certNftProjectId="certNftProjectId"
            :hasNft="hasNft"
            :resourceInfo="resourceInfo"
            :contentTypeConfig="contentTypeConfig"
            @publishFinish="publishFinish">
            <nft-setting ref="nftSettingDom" @change="changeSetting"></nft-setting>
        </preview>
    </div>
</template>

<script setup>
import { ref, reactive, watch, defineProps, defineEmits, onMounted } from "vue";
import axios from 'axios';
import { screenshotWebsite, getContentTypeConfig } from "@/http/toolBoxApi";
import editor from '@/view/iframe/publish/tool-box/child/editor.vue'
import preview from '@/view/iframe/publish/tool-box/child/preview.vue'
import Report from "@/log-center/log"
import nftSetting from '@/view/iframe/publish/components/nft-setting.vue'

const props = defineProps({
    pageData: {
        type: Object,
        default: {
            linkInputDescImage: '',
            defaultLinkTitle: ''
        }
    },
    activePage: {
        type: String,
        default: 'EDITOR', // EDITOR PREVIEW
    },
});

const emits = defineEmits(["onToolBoxPageChange"]);

watch(
    () => props.activePage,
    (newVal) => {
        showCom.value = newVal;
        if(newVal == 'PREVIEW') {
          hasNft.value = nftSettingDom.value && nftSettingDom.value.nftList.length > 0;
          Report.reportLog({
              pageSource: Report.pageSource.previewPage,
              businessType: Report.businessType.pageView,
          }, {
            'type': Report.bizType.ToolBox,
            'post-editor-url': previewData.convertUrl,
            'has-nft': hasNft.value
          })
        }
    },
    {
        deep: true
    }
);

let showCom = ref('EDITOR');
let previewData = reactive({
    convertUrl: '',
    originUrl: '',
    appId: '',
    currentApp: {}
})
let certNftProjectId = ref('')

let screenshotWebsiteData = reactive({
    url: '',
    viewBgImagePath: '',
    viewBgImageFullPath: '',
    status: '',
});

let nftSettingDom = ref(null);
let hasNft = ref(false);

let contentTypeConfig = ref({
  allowContentTypes: [],
  unSupportToast: '',
  contentTypeTitleMap: {}
})

let resourceInfo = ref({
  isSet: false,
  contentType: '',
  statusCode: '',
  title: '',
  hasTitle: false,
  loadSuccess: false
});

const changeShowCom = (params) => {
    showCom.value = 'PREVIEW';
    previewData.convertUrl = params.convertUrl;
    previewData.originUrl = params.originUrl;
    previewData.appId = params.appId
    previewData.linkImagePath = params.linkImagePath || '';
    previewData.currentApp = params.currentApp || {};

    screenshotWebsiteData.url = '';
    screenshotWebsiteData.viewBgImagePath = '';
    screenshotWebsiteData.viewBgImageFullPath = '';
    screenshotWebsiteData.status = '';

    resourceInfo.value = {
      isSet: false,
      contentType: '',
      statusCode: '',
      title: '',
      hasTitle: false,
      loadSuccess: false
    };

    if(!params.appId || params.appId && !params.linkImagePath) {
        screenshotWebsite({
            params: {
                url: params.convertUrl
            }
        }).then(res => {
            if(showCom.value != 'PREVIEW') {
                return;
            }
            if(res.code == 0 && res.data) {
                screenshotWebsiteData.url = res.data.linkImagePath;
                screenshotWebsiteData.viewBgImagePath = res.data.viewBgImagePath;
                screenshotWebsiteData.viewBgImageFullPath = res.data.viewBgImageFullPath;
                screenshotWebsiteData.status = 1;
            } else {
                screenshotWebsiteData.status = 1;
            }
        }).catch(() => {
            if(showCom.value != 'PREVIEW') {
                return;
            }
            screenshotWebsiteData.status = 1;
        })
    }

    if(!params.appId) {
      getResourceInfo({url:params.convertUrl});
    }

    emits("onPageChange", {page: showCom.value});
}

const getResourceInfo = ({url}) => {
  axios.get(url).then(res => {
    if(res) {
      resourceInfo.value.isSet = true;
      resourceInfo.value.contentType = res.headers['content-type'];
      resourceInfo.value.statusCode = res.request.status;
      resourceInfo.value.hasTitle = resourceInfo.value.contentType.indexOf('text/html') > -1 ? true : false;
      resourceInfo.value.loadSuccess = true;

      let siteTitle = '';
      if(resourceInfo.value.hasTitle) {
        siteTitle = getTitleByHtmlStr(res.data);
        if (!siteTitle) {
          let urlObj = new URL(url);
          siteTitle = urlObj.hostname;
        }
      }
      resourceInfo.value.title = siteTitle;
    }

  }).catch(err => {
    resourceInfo.value.isSet = true;
  })
}

const getTitleByHtmlStr = (str = '') => {
  let tag_start = '<title>'
  let tag_end = '</title>'
  let index1 = str.indexOf(tag_start) + tag_start.length;
  let index2 = str.indexOf(tag_end);

  if (index1 < tag_start.length || index2 < 0 || index2 < index1) {
    return '';
  }

  return str.substring(index1, index2) || '';
};


const publishFinish = (params) => {
    emits("toolBoxPublishFinish", params);
}

const changeSetting = (id = '') => {
    certNftProjectId.value = id;
}

onMounted(() => {
  getContentTypeConfig({
    params: {}
  }).then(res => {
    if(res.code == 0) {
      contentTypeConfig.value = res.data;
    }
  })
})
</script>

<style lang="scss" scoped>
    .page-wrapper {
        width: 100%;
        height: 100%;
    }
</style>
