<template>
  <div class="editor-wrapper">
    <div class="top">
      <div class="title">
        Enter Link to Embed in Tweet
      </div>
      <div class="search-wrapper">
        <input class="input" type="text" v-model="siteUrl" placeholder="Enter link">
        <div class="btn" @click="searchHandler()">
          <img :src="require('@/assets/svg/icon-tool-box-search-arrow.svg')" />
        </div>
      </div>
      <div class="desc">
        <img :src="linkInputDescImage" alt="">
      </div>
    </div>
    <div class="bottom">
      <div class="content">
        <div class="cate-item history-wrapper" v-if="historyList.length">
          <div class="cate">
            <img :src="require('@/assets/svg/icon-tool-app-history.svg')" />
          </div>
          <div class="app-list">
            <div class="app" v-for="(app, idx) in historyList" :key="idx" @click="clickHistoryAppHandler(app)">
              <div class="img-wrapper">
                <img class="img" :class="{ 'small-img': !app.appId }" :src="app.iconPath" :onerror="imgOnError" />
              </div>
              <div class="name">
                {{ app.name }}
              </div>
            </div>
          </div>
        </div>
        <div class="cate-item" v-for="(item) in appList" :key="item.cateId">
          <div class="cate">
            <img :src="item.iconPath">
          </div>
          <div class="app-list">
            <div class="app" v-for="(app, idx) in item.apps" :key="idx" @click="clickAppHandler(app)">
              <img class="app-img" :src="app.iconPath" alt="">
              <div class="name">
                {{ app.name }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, onMounted } from "vue";
import axios from 'axios';
import { message } from "ant-design-vue";
import { convertUrl, getAllPostEditorAppData, checkInputUrlInBlacklist } from "@/http/toolBoxApi";
import { setChromeStorage, getChromeStorage } from "@/uilts/chromeExtension"
import { checkURL, debounce } from "@/uilts/help"

const props = defineProps({
  linkInputDescImage: {
    type: String,
    default: '',
  },
});


let siteUrl = ref('');

let selectAppGuideData = {};
let openWindowList = [];

let historyList = ref([])

let appList = ref();

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

const searchHandler = async (_params) => {
  let siteTitle = '', favicon = '';
  let timer = null;


  if (!siteUrl.value) {
    return;
  }

  siteUrl.value = siteUrl.value.trim();

  if (!checkURL(siteUrl.value)) {
    message.info('Incorrect URL entered');
    //提示
    return;
  }
  const loadingHide = message.loading('loading...', 0);
  timer = setTimeout(() => {
    loadingHide();
    message.error('Page loading failed');
  }, 1000 * 15);

  if(!_params) {
    let blackListRes = await checkInputUrlInBlacklist({
      params: {
        url: siteUrl.value
      }
    })

    if(blackListRes.code == 0) {
      if(blackListRes.data) {
        loadingHide();
        clearTimeout(timer);
        message.info('This site is not supported');
        return;
      }
    }
  }

  let siteRes = await axios.get(siteUrl.value);

  let currentApp = {
    appId: '',
    cateId: '',
    createType: '',
    defaultUrl: siteUrl.value,
    guideData: '',
    iconPath: '',
    interactType: '',
    linkImagePath: '',
    name: '',
  }

  if (siteRes) {
    if (siteRes.headers['content-type'].indexOf('text/html') < 0 || siteRes.request.status > 403) {
      loadingHide();
      message.error('Page loading failed');
      return;
    }
    let urlObj = new URL(siteUrl.value);
    if (siteRes.data) {
      siteTitle = getTitleByHtmlStr(siteRes.data);
      if (!siteTitle) {
        siteTitle = urlObj.hostname;
        currentApp.defaultTit = siteTitle;
      }
      currentApp.name = siteTitle;
    }
    favicon = urlObj.origin + '/favicon.ico';
  }
  currentApp.iconPath = favicon;

  if(_params) {
    currentApp = _params;
  }
  
  let convertRes = await convertUrl({ params: { originUrl: siteUrl.value } });
  let params = { convertUrl: siteUrl.value, 
                  originUrl: siteUrl.value, 
                  appId: currentApp.appId, 
                  linkImagePath: currentApp.linkImagePath, 
                  currentApp };

  loadingHide();
  clearTimeout(timer);

  if (convertRes && convertRes.code == 0) {
    let { convertUrl } = convertRes.data || {};
    params.convertUrl = convertUrl;
  }
  emits('changeShowCom', params)
}

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) {
    return '';
  }

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

const clickHistoryAppHandler =  debounce(function(params) {
  if (params.appId) {
    clickAppHandler(params);
  } else {
    siteUrl.value = params.defaultUrl;
    searchHandler(params);
  }
}, 800);

const clickAppHandler =  debounce(function(params) {
  let { createType, defaultUrl, appId, linkImagePath } = params;
  switch (createType) {
    case 1:
      emits('changeShowCom', { convertUrl: defaultUrl, originUrl: defaultUrl, appId, linkImagePath, currentApp: params })
      break;
    case 2:
      openWindow(params);
      break;
  }
}, 800);

const openWindow = (params) => {
  chrome.windows.getCurrent({},
    function (window) {
      if (window && window.state == "fullscreen") {
        chrome.windows.update(window.id, {
          state: 'normal'
        }, function () {
          setTimeout(() => {
            createGuideWindow(params, true);
          }, 1000)
        })
      } else {
        createGuideWindow(params);
      }
    })
};

const createGuideWindow = (params, isUpdate = false) => {
  openWindowList = [];
  selectAppGuideData = {};

  let windowWith = window.screen.width - 500;
  let guideUrl = chrome.runtime.getURL('/iframe/tool-box-guide.html');

  setChromeStorage({ selectGuideApp : JSON.stringify(params)}, async () => {
    let window1 = await chrome.windows.create({
      width: windowWith,
      type: 'normal',
      url: params.defaultUrl,
      state: 'normal'
    })
    openWindowList.push(window1);

    let window2 = await chrome.windows.create({
      width: 500,
      type: 'popup',
      url: guideUrl,
      left: windowWith,
      state: 'normal'
    })
    openWindowList.push(window2);

    setChromeStorage({ guideAppWindowList: JSON.stringify({list: openWindowList})});
  })  
}

const getAppList = () => {
  getAllPostEditorAppData({ params: {} }).then(res => {
    if (res.code == 0) {
      appList.value = res.data || [];
    }
  })
}


const onRuntimeMsg = () => {
  chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {

    switch (req.actionType) {
      case 'CONTENT_GUIDE_APPLY_APP':
        siteUrl.value = req.data.siteUrl;
        searchHandler(req.data.selectGuideApp);
        break;
    }
  })
}

const getHistoryList = async () => {
  let { list = [] } = await getChromeStorage('toolBoxAppHistoryData') || {};
  historyList.value = list;
};

const imgOnError = (e) => {
  let img = e.srcElement;
  img.src = require('@/assets/img/icon-default-app-logo.png');
  img.onerror = null;
}

onMounted(() => {
  getHistoryList();
  getAppList();
  onRuntimeMsg();
})
</script>

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

  .top {
    padding: 25px 40px 30px 40px;
    border-bottom: 0.5px solid #D1D9DD;
    box-sizing: border-box;

    .title {
      font-weight: 500;
      font-size: 20px;
    }

    .search-wrapper {
      margin: 20px 0;
      border-radius: 8px;
      width: 100%;
      height: 49px;
      display: flex;
      align-items: center;

      .input {
        background: #F1F3F4;
        border: none;
        outline: none;
        font-weight: 400;
        font-size: 16px;
        color: #636363;
        height: 100%;
        width: calc(100% - 49px);
        padding-left: 20px;
        border-bottom-left-radius: 8px;
        border-top-left-radius: 8px;
      }

      .btn {
        width: 49px;
        height: 49px;
        background: #1D9BF0;
        border-bottom-right-radius: 8px;
        border-top-right-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }
    }

    .desc {
      img {
        width: 315px;
        height: 14px;
        object-fit: cover;
      }
    }
  }

  .bottom {
    width: 100%;
    height: calc(100% - 185px);
    overflow-y: auto;

    .content {
      width: 100%;
      padding: 36px 30px 20px 50px;
      box-sizing: border-box;

      .history-wrapper {

        .app-list {
          .img-wrapper {
            width: 60px;
            height: 60px;
            border-radius: 10px;
            margin-bottom: 10px;
            border: 1px solid #E5E5E5;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;

            .img {
              width: 100%;
              height: 100%;
              border-radius: 10px;
            }

            .small-img {
              width: 25px;
              height: 25px;
            }
          }
        }
      }

      .cate-item {
        min-height: 110px;
        display: flex;
        margin-bottom: 12px;

        .cate {
          width: 20px;
          height: 110px;
          margin-right: 26px;
          display: flex;
          align-items: center;
          margin-top: -10px;

          img {
            width: 20px;
            height: 20px;
          }
        }

        .app-list {
          display: flex;
          align-content: center;
          flex-wrap: wrap;

          .app {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 110px;
            height: 110px;
            cursor: pointer;

            .app-img {
              width: 60px;
              height: 60px;
              border-radius: 10px;
              margin-bottom: 10px;
              border: 1px solid #E5E5E5;
              box-sizing: border-box;
            }

            .name {
              font-weight: 500;
              font-size: 12px;
              color: #636363;
              width: 100%;
              height: 15px;
              text-overflow: ellipsis;
              white-space: nowrap;
              overflow: hidden;
              text-align: center;
              box-sizing: border-box;
              padding: 0 5px;
            }
          }
        }
      }
    }
  }
}
</style>
