<template>
  <div class="page" id="page">
    <div class="top-title wow fadeInUp" data-wow-duration="2s" data-wow-delay="0s" data-wow-offset="0">
      <div class="top-container">
        <n-icon :component="IosFiling" size="40" style="vertical-align: middle" />
        <span>简报智库</span>
      </div>
    </div>
    <div class="page-nav-container wow fadeInLeft" data-wow-duration="2s" data-wow-delay="0s" data-wow-offset="0">
      <div class="nav-txt">
        <n-breadcrumb separator=">">
          <n-breadcrumb-item> <n-icon :component="MdHome" /><router-link to="/home">首页</router-link> </n-breadcrumb-item>
          <n-breadcrumb-item> <n-icon :component="IosFiling" />简报智库 </n-breadcrumb-item>
        </n-breadcrumb>
      </div>
    </div>
    <div class="bulletin-detail" :class="{ 'mobile-detail': !pcShow }">
      <div class="container">
        <h1 class="wow fadeInLeft">{{ detail?.title }}</h1>
        <p class="wow fadeInLeft">
          <span class="bqfl-iconfont icon-icon color99 mr5"></span>
          <span>发布时间：{{ formatDate(detail?.publishDate) }}</span>
        </p>
        <n-divider />
        <div class="btns wow fadeInRight">
          <n-button type="primary" color="#F0A226" @click="handleTools('subscribe')"> 定制报告 </n-button>
          <n-button type="primary" color="#2683F0" @click="handleTools('pdf')"> PDF下载 </n-button>
          <n-button type="primary" color="#2683F0" @click="handleTools('ppt')"> PPT下载 </n-button>
        </div>
        <div class="iframe-box" v-if="detail?.id">
          <ClientOnly :is-show="isShow">
            <PDFPreview :key="`t_${new Date().getTime()}`" :src="PdfPreviewUrl" :config="pdfConfig"></PDFPreview>
          </ClientOnly>
        </div>
        <div class="reader wow fadeInUp" data-wow-duration="3s" data-wow-delay="0s" data-wow-offset="0" v-if="listData && listData.length > 0">
          <h3>相关阅读</h3>
          <ul>
            <li v-for="item in listData" :key="item.id">
              <div class="img">
                <img :src="BaseUrl + '/fileupload/' + item.filePath + item.imageFileName" alt="" />
              </div>
              <div class="info">
                <a :href="`/bulletin/bulletin-detail/${item.webTitle}-${item.id}`">
                  <h4>{{ item.title }}</h4>
                </a>
                <span class="tags" v-if="item.secondLabelName">
                  <span class="tag">{{ item.secondLabelName.split(',')[0] }}</span>
                </span>
                <span class="time">{{ formatDate(item.publishDate) }}</span>
                <span class="num">{{ item.pdfNum || 0 }}页</span>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <n-modal :show="toolsVisible" preset="dialog" :title="toolsTitle" :showIcon="false" :z-index="9" @close="toolsVisible = false" @esc="toolsVisible = false" @mask-click="toolsVisible = false" :class="{ 'login-dialog': !pcShow }">
      <demand @closeDialog="handleCloseDiag" v-if="toolsType == 'subscribe'" />
      <pay v-if="toolsType == 'pdf' || toolsType == 'ppt'" :detail="detail" @closeToolsDialog="closeToolsDialog" @openWXCode="openWXCode"></pay>
      <template v-if="toolsType == 'wxQRCode'">
        <div class="wxQRCode">
          <h3>微信支付</h3>
          <qrcode-vue :value="wxQRCode" size="200" level="H" render-as="svg" />
          <p>请使用微信扫码支付</p>
          <p v-if="payShow" style="color: red">支付状态请求中,请勿重复支付</p>
        </div>
      </template>
    </n-modal>
    <n-modal v-model:show="payJumpVisible" preset="dialog" title="提示" :showIcon="false" content="" positive-text="确认" negative-text="取消" :close-on-esc="false" :mask-closable="false" @positive-click="submitPayEndCallback" @negative-click="cancelPayEndCallback" :class="{ 'login-dialog': !pcShow }">
      <h2>请确认是否支付完成?</h2>
      <p>支付完成后，请到个人中心—我的订单中进行下载</p>
    </n-modal>
    <n-spin class="load" :description="description" :show="spinShow" :delay="1000">
      <div style="width: 150px"></div>
    </n-spin>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  reactive,
  onMounted,
  computed,
  watch,
  onUnmounted,
  onServerPrefetch,
  inject,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  NIcon,
  NBreadcrumb,
  NBreadcrumbItem,
  NButton,
  NInput,
  createDiscreteApi,
  NDivider,
  NModal,
  NSpin,
} from "naive-ui";
import { IosFiling, MdHome } from "@vicons/ionicons4";
import pay from "./modules/pay.vue";
import { useUserStore } from "@/store/user";
import QrcodeVue from "qrcode.vue";
import ClientOnly from "@duannx/vue-client-only";
import PDFPreview from "@/components/PdfPreview/index.vue";
import { useI18n } from "#imports";
const { t } = useI18n();
const setTitleKeywordsDescription = inject("setTitleKeywordsDescription");
const router = useRouter(); // 传递参数
const route = useRoute();
const userStore = useUserStore();
const toolsVisible = ref<boolean>(false);
const toolsTitle = ref<string>("");
const toolsType = ref<string>();
const pcShow = ref<boolean>(true);
const id = ref();
const detail = ref({});
const listData = ref([]);
const spinShow = ref(false);
const description = ref("数据加载中");
const wxQRCode = ref("");
const count = ref(0);
const timer = ref();
const payShow = ref(false);
const websiteToken = computed(() => userStore.getToken);
const userInfo = computed(() => userStore.getUserInfo);
const isShow = ref(false);
const PdfPreviewUrl = ref("");
const payJumpVisible = ref(false);
const config = useRuntimeConfig();
const BaseUrl = ref(config.public.baseUrl);
const pageSize = 10;
const pdfConfig = {
  toolbar: {
    toolbarViewerLeft: {
      findbar: true,
      previous: true,
      next: true,
      pageNumber: true,
    },
    toolbarViewerRight: {
      presentationMode: true,
      openFile: false,
      print: true,
      download: true,
      viewBookmark: true,
    },
    toolbarViewerMiddle: {
      zoomOut: true,
      zoomIn: true,
      scaleSelectContainer: true,
    },
  },
};

// onMounted(async () => {
//   pcShow.value = !isMobile();
//   const webTitle = route.params.webTitle;
//   const wts = webTitle.split("-");
//   id.value = wts[wts.length - 1];
//   getDetail();
// });

onUnmounted(() => {
  payEnd();
});

watch(
  () => toolsVisible.value,
  (newVal, oldVal) => {
    if (newVal === false) {
      payEnd();
    }
  }
);

const getDetail = async () => {
  isShow.value = false;
  spinShow.value = true;
  description.value = "数据加载中";
  const {
    code,
    data: { list, vo },
  } = await bulletinDetail_Api({
    id: id.value,
  });
  if (code === 200) {
    if (vo) {
      detail.value = vo;
      listData.value = [...list];
      isShow.value = true;
      PdfPreviewUrl.value = `${BaseUrl.value}/fileupload/${vo.filePath}${
        vo.previewPdfFileName
      }?t=${new Date().getTime()}`;
      useHead({
        title: detail.value.title,
        viewport: "width=device-width,initial-scale=1,maximum-scale=1 ",
        charset: "utf-8",
        meta: [
          {
            hid: "keywords",
            name: "keywords",
            content: t("defaultSettings.keyword"),
          },
          {
            hid: "description",
            name: "description",
            content: detail.value.outline,
          },
        ],
      });
    } else {
      errorMsg("报告查询失败,请查看其它报告");
    }
  }
  spinShow.value = false;
};

const toDetail = (item: object) => {
  router.push({
    name: "bulletinDetail",
    query: {
      id: item.id,
    },
  });
};

const handleTools = (type: string) => {
  switch (type) {
    case "subscribe":
      toolsVisible.value = true;
      toolsTitle.value = "定制报告";
      toolsType.value = type;
      break;
    case "pdf":
      toCreatedPayOrder(type);
      break;
    case "ppt":
      toCreatedPayOrder(type);
      break;
    default:
      break;
  }
};

const toCreatedPayOrder = async (type: string) => {
  if (detail.value.useDownPay == "0" || detail.value.useShowPay == "0") {
    downFile();
  } else {
    if (userInfo.value?.id && websiteToken.value) {
      toolsVisible.value = true;
      toolsTitle.value = ``;
      toolsType.value = type;
    } else {
      userStore.setShowLoginDialog(true);
      // errorMsg("请先登录");
    }
  }
};

const downFile = async () => {
  const { code, data } = await getDownUrl_Api({
    researchBriefReportId: detail.value.id,
    fileType: detail.value.previewPdfFileName.split(".")[1],
  });
  if (code === 200) {
    const url = `${BaseUrl.value}/fileupload/${data.filePath}${data.fileName}`;
    downloadFile(url);
  }
};

const closeToolsDialog = (type: string) => {
  switch (type) {
    case "success":
      toolsVisible.value = false;
      break;
    case "subscribe":
      break;
    case "pdf":
      break;
    case "ppt":
      break;
    case "zfbPayEnd":
      setTimeout(() => {
        // toolsVisible.value = false;
        payJumpVisible.value = true;
      }, 3000);
      break;
    default:
      break;
  }
};

const handleCloseDiag = () => {
  toolsVisible.value = false;
};

const openWXCode = (val: string) => {
  toolsType.value = "wxQRCode";
  wxQRCode.value = val?.orderPayUrl;
  setTimeout(() => {
    // toolsVisible.value = false;
    payJumpVisible.value = true;
    // payDetail(val?.orderNumber);
  }, 3000);
};

const submitPayEndCallback = () => {
  toolsVisible.value = false;
  payJumpVisible.value = false;
  NMessage.message.success("已确认支付,正在前往支付订单页");
  setTimeout(() => {
    router.push({
      name: "mineCenter",
      params: { active: 1 },
    });
  }, 300);
};

const cancelPayEndCallback = () => {
  if (toolsType.value != "wxQRCode") {
    toolsVisible.value = false;
  }
  payJumpVisible.value = false;
  NMessage.message.success("已取消确认操作");
};

const payDetail = async (orderNumber) => {
  payShow.value = true;
  const { code, data } = await bulletinDetailPay_Api({
    researchBriefReportId: id.value,
    orderNumber: orderNumber,
  });
  if (code === 200) {
    if (data.payStatus == 1) {
      NMessage.message.success("支付成功");
      payEnd();
    } else if (data.payStatus != 1) {
      if (toolsVisible.value) {
        if (count.value >= 5) {
          payEnd();
          NMessage.message.success("请前往个人中心订单列表页查看订单详情");
        } else {
          timer.value = setTimeout(() => {
            count.value++;
            payDetail(orderNumber);
          }, 10 * 1000);
        }
      }
    }
  }
};

const payEnd = () => {
  count.value = 0;
  toolsVisible.value = false;
  clearTimeout(timer.value);
};

const getTitleKeywordsDescription = (data) => {
  let title, description, keywords;
  try {
    title = data.title;
    description = data.outline || "";
    keywords = "";
  } catch (error) {
    console.log("getTitleKeywordsDescription", error);
  }
  return {
    title,
    keywords,
    description,
  };
};

const NMessage = createDiscreteApi(["message"]);
const errorMsg = (msg: any) => {
  NMessage.message.error(msg || "服务端异常");
};

// onServerPrefetch(async () => {
// try {
//   const webTitle = route.params.webTitle;
//   const wts = webTitle.split("-");
//   description.value = "数据加载中";
//   spinShow.value = true;
//   const res = await bulletinDetail_Api({
//     id: wts[wts.length - 1],
//   });
//   detail.value = res.data.vo;
//   listData.value = [...res.data.list];
//   if (res.data.vo) {
//     setTitleKeywordsDescription(getTitleKeywordsDescription(res.data.vo));
//   }
//   spinShow.value = false;
// } catch (error) {
//   console.log(error);
// }
// });
if (process.client) {
  pcShow.value = !isMobile();
}
const webTitle = route.params.webTitle;
const wts = webTitle.split("-");
id.value = wts[wts.length - 1];
getDetail();
</script>

<style lang="scss" scoped>
.bulletin-detail {
  background-color: #fff;
  border-bottom: 1px solid #f2f2f2;

  .container {
    padding-top: 60px;
  }

  h1,
  h3,
  p {
    padding: 0;
    margin: 0;
  }

  h1 {
    margin-bottom: 12px;
    text-align: center;
    font-size: 32px;
    font-weight: bold;
    color: #2d4393;
  }

  p {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666666;
  }

  .btns {
    margin-bottom: 20px;
    text-align: center;

    .n-button {
      width: 140px;
      height: 50px;
      margin-right: 20px;
      font-size: 18px;
      border-radius: 8px;
    }
  }

  .iframe-box {
    width: 100%;
    height: 900px;
    margin-bottom: 40px;

    iframe {
      width: 100%;
      height: 100%;
    }

    #vuePdfApp {
      :deep(.toolbar) {
        z-index: 3;
      }

      :deep(#sidebarContainer) {
        z-index: 3;
      }

      :deep(#errorWrapper) {
        z-index: 3;
      }

      :deep(#thumbnailView) {
        width: 100%;
      }
    }
  }

  ul {
    padding: 0;

    li {
      margin: 0;
      list-style: none;
      padding: 0;

      p {
        padding: 0;
        margin: 0;
      }
    }
  }

  .reader {
    h3 {
      text-align: left;
      font-size: 24px;
      color: #1a1a1a;
    }

    ul {
      display: flex;

      li {
        // width: 240px;
        width: 15rem;
        margin-right: 85px;

        &:last-child {
          margin-right: 0;
        }
      }
    }

    .img {
      width: 100%;
      height: 320px;
      margin-bottom: 25px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        vertical-align: middle;
        object-fit: contain;
        transition: all 0.4s ease;
      }
    }

    h4 {
      margin: 0;
      padding: 0;
      display: block;
      text-align: left;
      margin-bottom: 10px;
      font-size: 14px;
      font-weight: normal;
      color: #1a1a1a;
      line-height: 23px;
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .tags {
      margin-right: 10px;

      .tag {
        display: inline-block;
        padding: 5px 13px 3px;
        text-align: center;
        background: #cbffe3;
        font-size: 12px;
        color: #18a058;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }

    .num {
      margin-left: 10px;
      // display: block;
      // margin-top: 10px;
    }
  }

  .n-dialog {
    padding-top: 48px;
    border-radius: 20px;

    .n-dialog__title {
      display: block;
      font-size: 24px;
      color: #1a1a1a;
      font-weight: bold;
      text-align: center;
    }
  }
}

.mobile-detail.bulletin-detail {
  .container {
    padding: 30px 0;

    h1,
    h3 {
      font-size: 20px;
    }

    .btns {
      // position: fixed;
      // left: 0;
      // bottom: 0;
      width: 100%;
      // padding: 20px 0;
      // margin-bottom: 0;
      display: flex;
      justify-content: space-around;
      background-color: #fff;
      z-index: 5;

      .n-button {
        width: 30%;
        margin-right: 0;
        font-size: 14px;
        border-radius: 4px;
      }
    }

    .iframe-box {
      margin-bottom: 20px;
    }

    .reader {
      h4 {
        font-size: 18px;
      }

      ul {
        display: block;

        li {
          display: flex;
          width: 100%;
          margin-right: 0;
          margin-bottom: 20px;
          padding-bottom: 15px;
          border-bottom: 1px solid #cccccc;
        }
      }

      .img {
        max-width: 100px;
        // height: 135px;
        max-height: 135px;
        margin-bottom: 0;
        margin-right: 10px;
        flex-shrink: 0;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          vertical-align: middle;
          object-fit: cover;
        }
      }
    }
  }
}

.login-dialog.n-dialog {
  min-width: auto;

  padding-top: 20px;
  border-radius: 10px;

  .n-dialog__title {
    font-size: 18px;
  }

  .n-dialog__content {
    .container {
      padding: 20px 10px;

      .login-btn {
        height: 45px;
      }
    }

    .n-form {
      .n-form-item {
        .n-form-item-label {
          width: 85px !important;
          font-size: 12px;
        }

        .n-form-item-feedback-wrapper {
          min-height: 10px;
        }
      }
    }

    .pay-container {
      padding: 10px;

      :deep(.pay-box) {
        width: 50%;
        margin-right: 10px;

        .img {
          height: 150px;
        }
      }
    }
  }
}

.wxQRCode {
  width: 100%;
  text-align: center;
}

.load {
  z-index: 10;

  :deep(.n-spin-body) {
    left: auto;
  }
}
</style>
