<template>
    <div class="invite-friends">
      <div class="invite-friends-content">
        <div class="invite-friends-content-head">
          <div class="title">Invite Friends to Open the Chest!</div>
          <div class="info">Invitees Need to be Real New follower of {{followUserStr}} to receive rewards</div>
        </div>
        <div class="invite-friends-content-body">
          <img class="tips" v-if="state.active_share_channel" :src="require('@/assets/svg/icon-channel-tips.svg')" />

          <div class="share-list" :class="{'share-list-active': state.active_share_channel}">
            <div v-for="(item, index) in state.share_list" :key="index" :data-clipboard-text="item.inviteContent"
                @click="clickShare(item)" class="share-item">
              <img :src="item.iconPath"  />
              <div class="name">
                {{item.name}}
              </div>
            </div>
            <div class="share-item copy-btn" @click="clickCopy" v-click-log="state.log_invite_copy_btn_click"
                :data-clipboard-text="state.detail.inviteCopyUrl">
              <img :src="require('@/assets/svg/icon-copy-url-teasure.svg')" alt="">
              <div class="name">
                Copy URL
              </div>
            </div>
        </div>
        </div>
      </div>
      <v-btn :txt="state.open_btn.txt" :font-size="'17px'" class="btn" :icon="false"
            :disabled="state.open_btn.disabled" v-show-log="state.log_invite_btn_show" :loading="state.btn_loading"
            v-click-log="state.log_invite_btn_click" @onClick="clickBtn" font-weight="600"></v-btn>
      <div class="mask" v-show="showShareTips">
        <div class="content">
          <img class="icon-loading" :src="require('@/assets/svg/icon-tweet-loading.svg')" />
          <div class="text">
            Link copied to clipboard
             <br/>
            Opening {{selectShareApp.name }}
          </div>
        </div>
      </div>
    </div>
</template>
<script setup>
import VBtn from '@/view/iframe/treasure-hunt/components/btn.vue'
import { inviteChannel } from '@/http/treasure'
import { inject, onMounted, ref } from 'vue'
import Report from "@/log-center/log"
import { getFrontConfig } from "@/http/account";
import { faceShareRedirectUrl } from '@/http/configAPI'
import { setChromeStorage } from '@/uilts/chromeExtension.js'

let ClipboardJS = require('clipboard');

let state = inject('state')

state.log_invite_btn_show = {
    businessType: Report.businessType.buttonView,
    pageSource: Report.pageSource.inviteFriendsPage,
    objectType: Report.objectType.openChestButton,
    redPacketType: Report.redPacketType.treasure,
    shareLinkId: state.invite_code,
    myShareLinkId: state.detail.inviteCopyUrl,
    currentInvitedNum: state.inviteCount,
    postId: state.postId
}

state.log_invite_btn_click = {
    businessType: Report.businessType.buttonClick,
    pageSource: Report.pageSource.inviteFriendsPage,
    objectType: Report.objectType.openChestButton,
    redPacketType: Report.redPacketType.treasure,
    shareLinkId: state.invite_code,
    myShareLinkId: state.detail.inviteCopyUrl,
    currentInvitedNum: state.inviteCount,
    postId: state.postId
}
state.log_invite_copy_btn_click = {
    businessType: Report.businessType.buttonClick,
    pageSource: Report.pageSource.inviteFriendsPage,
    objectType: Report.objectType.copyButton,
    redPacketType: Report.redPacketType.treasure,
    shareLinkId: state.invite_code,
    myShareLinkId: state.detail.inviteCopyUrl,
    currentInvitedNum: state.inviteCount,
    postId: state.postId
}

let facebookAppConfig = {
    facebookAppId: "",
    faceShareRedirectUrl
};

let selectShareApp = ref({});
let showShareTips = ref(false);
let followUserStr = ref('');

onMounted(() => {
    state.btn_loading = false
    setFrontConfig();
    initInviteChannel();
    getFollowUserStr();
})

const getFollowUserStr = () => {
  let arr = [];
  if(state.follows && state.follows.length) {
    for(let i = 0; i < state.follows.length; i++) {
      let item = state.follows[i];
      arr.push('@'+item.name);
    }
  }
  followUserStr.value = arr.join(" or ");
}

chrome.management.onDisabled.addListener(() => {
    initInviteChannel()
})
chrome.management.onEnabled.addListener(() => {
    initInviteChannel()
})

chrome.management.onInstalled.addListener(() => {
    initInviteChannel()
})
chrome.management.onUninstalled.addListener(() => {
    initInviteChannel()
})

let linePluginInstalled
const initInviteChannel = () => {
    try {
        chrome.management.get('ophjlpahpchlmihnnnihgmmeilfjmjjc', (res) => {
            if ((res && linePluginInstalled == 1) || (!res && linePluginInstalled == 0)) {
                return
            }
            if (res) {
                linePluginInstalled = 1
            } else {
                linePluginInstalled = 0
            }

            inviteChannel({
                params: {
                    linePluginInstalled,
                    postId: state.postId
                }
            }).then((res) => {
                if (res.code == 0) {
                    state.share_list = res.data
                }
            })
        })
    } catch (error) {
        console.error(error)
    }
}

async function clickBtn() {
    let _userInfo = await state.checkIsLogin()
    if (!_userInfo) {
        return
    }
    state.btn_loading = true
    state.treasureOpen()
}

const clickShare = (item) => {
    var clipboard = new ClipboardJS('.share-item');
    clipboard.on('success', function (e) {
        // state.toast.txt = 'Copy Successfully'
        // state.toast.has_icon = true
        // state.toast.show = true
        // setTimeout(() => {
        //     state.toast.show = false
        // }, 2000)
        e.clearSelection();
    })
    showShareTips.value = true;
    selectShareApp.value = item;

    if (item.name == 'facebook') {
        setChromeStorage({
            shareFacebookData: JSON.stringify({
                contentStr: item.inviteContent
            })
        })
        let cbParams = {
            bizType: 'TEASURE_INVITE'
        }
        let url = `https://www.facebook.com/dialog/share?app_id=${facebookAppConfig.facebookAppId}&display=popup&href=${item.treasureInviteUrl}&redirect_uri=${facebookAppConfig.faceShareRedirectUrl}?params=${JSON.stringify(cbParams)}`;

        setTimeout(() => {
          showShareTips.value = false;
          chrome.windows.create({
            width: 800,
              type: 'normal',
              url
          }, function (window) {
          })
        }, 1000)

    } else {
        setTimeout(() => {
          showShareTips.value = false;
          chrome.tabs.create({
              url: item.redirectPath
          });
        }, 1000)
    }
    Report.reportLog({
        businessType: Report.businessType.buttonClick,
        pageSource: Report.pageSource.inviteFriendsPage,
        objectType: Report.objectType.channelButton,
        shareLinkId: state.invite_code,
        myShareLinkId: state.detail.inviteCopyUrl,
        currentInvitedNum: state.inviteCount,
        postId: state.postId
    }, {
        'channel-name': item.name
    });
}

const setFrontConfig = () => {
    getFrontConfig({
        params: {},
    }).then((res) => {
        if (res.code == 0) {
            facebookAppConfig.facebookAppId = res.data.fbClientId;
        }
    });
};



const clickCopy = () => {
    var clipboard = new ClipboardJS('.copy-btn');
    clipboard.on('success', function (e) {
        state.toast.txt = 'Copy Successfully'
        state.toast.has_icon = true
        state.toast.show = true
        setTimeout(() => {
            state.toast.show = false
        }, 2000)
        e.clearSelection();
    })

    clipboard.on('error', function (e) {
        state.toast.txt = 'Copy Error'
        state.toast.has_icon = false
        state.toast.show = true
        setTimeout(() => {
            state.toast.show = false
        }, 2000)
    })
}
</script>
<style lang="scss" scoped>
.invite-friends {
    padding: 9px 14px 14px 14px;
    background: #fff;
    box-sizing: border-box;

    .invite-friends-content {
      max-height: 242px;
      overflow-y: auto;
      margin-bottom: 10px;
      box-sizing: border-box;

      .invite-friends-content-head {
        margin-bottom: 18px;
        padding: 0 6px;
        box-sizing: border-box;

        .title {
          font-weight: 900;
          font-size: 18px;
          margin-bottom: 7px;
        }
        .info {
          font-weight: 400;
          font-size: 12px;
          color: #7A7A7A;
          line-height: 15px;
        }

      }

      .invite-friends-content-body {
        position: relative;

        .tips {
          position: absolute;
          top: -42px;
          left: 0;
          width: 146px;
        }

        .share-list-active {
          background: rgba(29, 155, 240, 0.1);
          border: 1.5px solid #1D9BF0 !important;
          border-radius: 10px;
        }
        .share-list {
          display: flex;
          flex-wrap: wrap;
          width: 100%;
          box-sizing: border-box;
          border: 1.5px solid #fff;

          .share-item {
            user-select: none;
            width: 20%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 8px 2px;
            box-sizing: border-box;
            border-radius: 12px;


            cursor: pointer;
            img {
                width: 40px;
                height: 40px;
                border-radius: 100px;
                margin-bottom: 8px;
            }
            .name {
              font-weight: 400;
              font-size: 12px;
              color: #898989;
              width: 100%;
              overflow: hidden;
              text-overflow: ellipsis; //文本溢出显示省略号
              white-space: nowrap;
              text-align: center;
            }
          }

          .share-item:hover {
            background: #E3E3E4;
          }

        }
      }
    }
    .mask {
      position: fixed;
      top: 0;
      left: 0;
      width: 375px;
      height: 100%;
      background: rgba($color: #000000, $alpha: 0.9);
      z-index: 1000;
      display: flex;
      align-items: center;
      justify-content: center;

      .content {
        text-align: center;
      }

      .icon-loading {
        width: 60px;
        height: 60px;
        animation: loading 1.5 1s linear;
        margin-bottom: 30px;
      }

      .text {
        font-weight: 600;
        font-size: 17px;
        color: #FFFFFF;
      }
    }


  @keyframes loading {
      0% {
          transform: rotate(0);
      }

      100% {
          transform: rotate(360deg);
      }
  }
}
</style>
