<template>
  <view class="news-detail">
    <view class="title">{{ result?.title || result?.xcmc }}</view>
    <view class="time-box">
      <text>{{ formatTime(result?.createTime) }}</text>
      <text class="author">{{ result?.author }}</text>
    </view>
    <view v-if="result?.glyp" class="about-box">关联药品：{{ result?.glyp }}</view>
    <!--  #ifdef H5 -->
    <div class="content-box" v-html="result?.content || result?.wb"></div>
    <!--  #endif -->
    <!--  #ifdef MP-WEIXIN -->
    <rich-text space="nbsp" :nodes="result?.content || result?.wb"></rich-text>
    <!--  #endif -->

    <!--  #ifdef MP-WEIXIN -->
    <button v-if="loginStore.isLogin" @click="loginShareFn">
      <image class="s-share" src="@/static/images/common/share.png" />
    </button>
    <button
      v-else
      open-type="share"
      :data-title="result?.title || result?.xcmc"
      :data-id="detailId"
    >
      <image class="s-share" src="@/static/images/common/share.png" />
    </button>
    <image
      class="s-share"
      @click="shareFn"
      style="bottom: 98rpx"
      src="@/static/images/common/share2.png"
    />
    <!--  #endif -->
    <!-- 转发朋友圈探窗 -->
    <uv-overlay :show="overlayShow">
      <view class="overlay-content">
        <view class="overlay-info">
          <view class="overlay-title one-row">{{ result?.title || result?.xcmc }} </view>
          <view class="overlay-desc">
            <text class="overlay-time">{{ formatTime(result?.createTime) }}</text>
            <text>{{ result?.author || result?.createUser }}</text>
          </view>
          <view class="overlay-text four-row">{{ formatHtml(result?.content || result?.wb) }}</view>
          <view class="overlay-ercode">
            <image
              class="ercode-bg"
              src="https://api.yaoyi.net/wmkj/miniProgram/min-share-code.png"
            />
            <image class="ercode-url" :src="ercodeUrl" />
          </view>
          <view class="overlay-ercode-text">（长按识别二维码查看更多）</view>
          <view class="overlay-colse-icon" @click="overlayShow = false">
            <uv-icon name="close-circle" color="#A3A3A3" size="32" />
          </view>
        </view>
        <button class="save-btn" @click="saveBtn">保存图片</button>
        <view class="save-text">保存成功后请到手机相册查看</view>
      </view>
    </uv-overlay>
    <canvas class="canvas" canvas-id="myCanvas" :style="{ height: `${picOption.h}PX` }" />
    <!-- 登录状态下分享弹窗 -->
    <sharePopup
      @initInfo="initInfo"
      :sharePopupType="sharePopupType"
      :sharePopupId="sharePopupId"
      :shareTitle="shareTitle"
      ref="sharePopupRef"
    />
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { login } from '@/service/modules/common'
import {
  shareArticleByIdApi,
  getArticleByIdApi,
  shareAlbumByIdApi,
  getAlbumByIdApi,
  getOpenId
} from '@/service/modules/newsDetail'
import { useLoginStore } from '@/store/login'
import { getPackageListByTaskTypeApi, getQrCodeByUrlApi } from '@/service/modules/getTask'
import formatTime from '@/utils/formatTime'
import { formatRichTxt, transformContentToMultiLineText } from '@/utils/index'
import { getSystemInfo, downloadFile, saveImageToPhotosAlbum } from '@/wxUtils/index'
import sharePopup from '@/components/sharePopup/index.vue'

const loginStore = useLoginStore()

// 当前类型
const type = ref()
// 当前id
const detailId = ref()
// toPx
const toPx = ref()
onLoad(async (e: any) => {
  type.value = e?.type
  detailId.value = e?.id

  // 获取详情
  getDetail(e)
  //  #ifdef MP-WEIXIN
  // 判断当前是否是登录状态 是登陆状态下去请求获取执行包列表的接口
  if (loginStore.isLogin) {
    getPackageListByTaskType(e?.type)
  }
  // #endif
  const res = await getSystemInfo()
  toPx.value = res.toPx
})

const loginInfoCode = ref()
const openId = ref()
// 获取详情
const getDetail = async (e: any) => {
  if (e?.shareUserId && e?.packageId) {
    try {
      const loginInfo: any = await login()
      loginInfoCode.value = loginInfo?.code
      const res = await getOpenId(loginInfoCode.value)
      openId.value = res.openid
    } catch (err) {
      console.log('err', err)
    }
  }
  // 获取文章的详情
  if (e?.type === 'article') {
    getArticleDetail(e)
  } else {
    getAlbumDetail(e)
  }
}
const result = ref()
// 文章详情
const getArticleDetail = async (e: any) => {
  uni.showLoading()
  let res
  if (e.shareUserId && e.packageId) {
    res = await shareArticleByIdApi(
      e.id,
      e.shareUserId,
      openId.value,
      'open',
      e.packageId,
      '',
      e.remark
    )
  } else {
    res = await getArticleByIdApi(e.id)
  }
  if (res.data.content) {
    res.data.content = res.data.content.replace(
      /\\<img/gi,
      '<img style="width:100%;height:auto;display:block;" '
    )
    res.data.content = res.data.content.replace(/https/gi, 'http')

    res.data.content = res.data.content.replace(
      /https:\/\/mic.cnbg.com.cn/g,
      // eslint-disable-next-line no-useless-escape
      'https:\/\/cnbg.yaoyi.net'
    )
  } else {
    if (res.data.web) {
      res.data.wb = res.data.wb.replace(
        /\\<img/gi,
        '<img style="width:100%;height:auto;display:block" '
      )
      res.data.wb = res.data.wb.replace(/https/gi, 'http')
      // eslint-disable-next-line no-useless-escape
      res.data.wb = res.data.wb.replace(/https:\/\/mic.cnbg.com.cn/g, 'https:\/\/cnbg.yaoyi.net')
    }
  }
  result.value = res.data
  uni.hideLoading()
}

// 获取相册详情
const getAlbumDetail = async (e: any) => {
  let res
  uni.showLoading()
  if (e.shareUserId && e.packageId) {
    res = await shareAlbumByIdApi(
      e.id,
      e.shareUserId,
      openId.value,
      'open',
      e.packageId,
      '',
      e.remark
    )
  } else {
    res = await getAlbumByIdApi(e.id)
  }
  if (res.data?.wb) {
    res.data.wb = res.data.wb.replace(
      /\\<img/gi,
      '<img style="width:100%;height:auto;display:block" '
    )
    // eslint-disable-next-line no-useless-escape
    res.data.wb = res.data.wb.replace(/https:\/\/mic.cnbg.com.cn/g, 'https:\/\/cnbg.yaoyi.net')
  }

  result.value = res.data
  uni.hideLoading()
}

// 获取执行包
const getPackageListByTaskType = async (currType: string) => {
  const type = currType === 'article' ? '9' : '8'
  const res = await getPackageListByTaskTypeApi(type)
}
const overlayShow = ref(false)
// 登录分享
const shareFn = async () => {
  await getErrCode()
  overlayShow.value = true
}

const ercodeUrl = ref()
const getErrCode = async () => {
  let url = ''
  if (loginStore.isLogin) {
    let userId = loginStore.currentUserInfo.userId
    url = `/pages/news-detail/index?type=${type.value}&id=${detailId.value}&shareUserId=${userId}`
  } else {
    url = `/pages/news-detail/index?type=${type.value}&id=${detailId.value}`
  }
  const res = await getQrCodeByUrlApi(url)
  if (res.code === 0) {
    ercodeUrl.value = import.meta.env.VITE_APP_URL + res.data.data.url
  }
}

const shareId = ref('')
const packageIdVal = ref('')
const remarkVal = ref('')
// 分享
onShareAppMessage((res: any) => {
  if (res.from === 'button') {
    const { id, title, remark, packageid } = res.target.dataset
    let path = ''
    if (loginStore.isLogin) {
      const shareUserId = loginStore.currentUserInfo.userId
      shareSuccess()
      path = `/pages/news-detail/index?type=${type.value}&id=${id}&shareUserId=${shareUserId}&packageId=${packageid}&remark=${remark}`
    } else {
      path = `/pages/news-detail/index?type=${type.value}&id=${id}`
    }
    return {
      title: title,
      path: path
    }
  } else {
    const pages = getCurrentPages()
    const prevPage: any = pages[pages.length - 1]
    return {
      title: '营销行为管理小助手',
      path: prevPage.$page.fullPath
    }
  }
})
const shareSuccess = async () => {
  let res
  if (type.value === 'article') {
    res = await shareArticleByIdApi(
      shareId.value,
      loginStore.currentUserInfo.userId || '',
      loginStore.currentUserInfo.userId || '',
      'share',
      packageIdVal.value,
      '',
      remarkVal.value
    )
  } else {
    res = await shareAlbumByIdApi(
      shareId.value,
      loginStore.currentUserInfo.userId || '',
      loginStore.currentUserInfo.userId || '',
      'share',
      packageIdVal.value,
      '',
      remarkVal.value
    )
  }
  console.log('res', res)

  uni.showToast({
    title: res.msg,
    icon: 'none'
  })

  sharePopupRef.value.close()
}

// 格式化富文本
const formatHtml = (str: string) => {
  if (!str) return ''
  return formatRichTxt(str)
}
// 保存图片
const saveBtn = () => {
  initImage()
}

const picOption = ref({
  x: 0,
  y: 0,
  w: 0,
  h: 0
})
const initImage = async () => {
  const item = result.value
  const ctx = uni.createCanvasContext('myCanvas')
  const miniShareBg = 'https://api.yaoyi.net/wmkj/miniProgram/artileBg.png'
  const miniShareBgInfo: any = await downloadFile(miniShareBg)
  picOption.value = {
    w: 668 * toPx.value,
    h: 718 * toPx.value,
    x: 0, // 居中
    y: 0
  }
  console.log('picOption.value', picOption.value)
  let { w, h, x, y } = picOption.value
  let topBgH = 718 * toPx.value
  let topBgW = 588 * toPx.value

  let topTitle = item.title || item.temp1 || item?.xcmc
  let topTitleX = 36 * toPx.value
  let topTitleY = 76 * toPx.value
  let topTitleFont = 44 * toPx.value

  ctx.setFontSize(topTitleFont) // 文字字
  let topTitleArr = transformContentToMultiLineText(ctx, topTitle, topBgW - 48 * toPx.value, 1)
  let topDescY = topTitleY + topTitleFont + 50 * toPx.value
  let topDescDateTxt = item.createTime.slice(0, item.createTime.length - 3) // 日期
  let topDescCreate = item.createUser || '' // 作者

  // 开始绘制
  ctx.setFillStyle('#ffffff')
  ctx.fillRect(x, y, w, h)
  ctx.drawImage(miniShareBgInfo.tempFilePath, x, y, w, topBgH) // 背景图
  ctx.restore()
  ctx.save()
  // 顶部标题
  ctx.setFillStyle('black') // 文字颜色
  ctx.fillText(topTitleArr[0], topTitleX, topTitleY + topTitleFont)
  // 日期 作者
  ctx.setFontSize(26 * toPx.value)
  ctx.setFillStyle('#898989') // 文字颜色
  ctx.fillText(topDescDateTxt, topTitleX, topDescY)
  ctx.fillText(
    topDescCreate,
    topTitleX + ctx.measureText(topDescDateTxt).width + 38 * toPx.value,
    topDescY
  )
  // 正文
  let txt = formatRichTxt(item?.content || item?.wb)
  ctx.setFontSize(28 * toPx.value)
  ctx.setFillStyle('#333333') // 文字颜色
  let txtArr = transformContentToMultiLineText(ctx, txt, topBgW - 48 * toPx.value, 4)

  let txtLineHeight = 46 * toPx.value

  txtArr.forEach((tItem, index) => {
    ctx.fillText(tItem, topTitleX, topDescY + 80 * toPx.value + txtLineHeight * index)
  })

  // 分享二维码背景
  const miniShareCode = `https://api.yaoyi.net/wmkj/miniProgram/min-share-code.png`
  const miniShareCodeInfo: any = await downloadFile(miniShareCode)
  ctx.restore()
  ctx.save()
  let ercodeY = topDescY + 100 * toPx.value + txtLineHeight * txtArr.length
  let ercodeW = 182 * toPx.value
  ctx.drawImage(miniShareCodeInfo.tempFilePath, w / 2 - ercodeW / 2, ercodeY, ercodeW, ercodeW)
  // 二维码
  const ercodePath = ercodeUrl.value
  const ercodeUrlInfo: any = await downloadFile(ercodePath)
  ctx.restore()
  ctx.save()
  let ercodeUrlY = ercodeY + 18 * toPx.value
  let ercodeUrlW = 150 * toPx.value

  ctx.drawImage(
    ercodeUrlInfo.tempFilePath,
    w / 2 - ercodeUrlW / 2,
    ercodeUrlY,
    ercodeUrlW,
    ercodeUrlW
  )

  // （长按识别二维码查看更多）
  ctx.setFontSize(20 * toPx.value)
  ctx.setFillStyle('#222222') // 文字颜色
  let bottomTxt = '（长按识别二维码查看更多）'
  let bottomTxtW = ctx.measureText(bottomTxt).width
  ctx.fillText(bottomTxt, w / 2 - bottomTxtW / 2, ercodeY + ercodeW + 40 * toPx.value)
  ctx.draw(false, () => {
    onSave()
  })
}

const onSave = () => {
  uni.showLoading({
    title: '生成图片中..'
  })
  // let self = this
  const { w, h, x, y } = picOption.value

  uni.canvasToTempFilePath({
    x,
    y,
    width: w,
    height: h,
    destWidth: w * 2,
    destHeight: h * 2,
    canvasId: 'myCanvas',
    success: async (res) => {
      const tempFilePath = res.tempFilePath
      try {
        let res = await saveImageToPhotosAlbum(tempFilePath)
        uni.hideLoading()
        if (res) {
          setTimeout(() => {
            uni.showToast({
              title: '保存成功，请到相册查看',
              icon: 'none'
            })
          }, 300)
        }
        overlayShow.value = false
        uni.hideLoading()
      } catch (e) {
        uni.hideLoading()
        console.log(e)
      }
    },
    fail: function (res) {
      uni.hideLoading()
    }
  })
}

const sharePopupRef = ref()
const sharePopupType = ref('')
const sharePopupId = ref('')
const shareTitle = ref('')
const loginShareFn = () => {
  sharePopupType.value = type.value === 'article' ? '9' : '8'
  sharePopupId.value = detailId.value
  shareTitle.value = result.value?.title || result.value?.xcmc
}
const initInfo = () => {
  sharePopupType.value = ''
  sharePopupId.value = ''
  shareTitle.value = ''
}
</script>

<style lang="scss" scoped>
.news-detail {
  padding: 30rpx;
  .title {
    font-size: 44rpx;
    color: #333333;
  }
  .time-box {
    margin-top: 8rpx;
    color: #898989;
    font-size: 26rpx;
    .author {
      margin-left: 38rpx;
    }
  }
}

.s-share {
  position: fixed;
  bottom: 184rpx;
  right: -6rpx;
  width: 250rpx;
  height: 88rpx;
}

.overlay-content {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  height: 100vh;

  .overlay-info {
    box-sizing: border-box;
    width: 668rpx;
    position: relative;
    border-radius: 16rpx;
    overflow: hidden;
    height: 718rpx;
    background: url('https://api.yaoyi.net/wmkj/miniProgram/artileBg.png') no-repeat;
    background-size: 100% 100%;
    padding: 0 36rpx;

    .overlay-title {
      margin-top: 98rpx;
      font-size: 44rpx;
      color: #333333;
    }
    .overlay-desc {
      margin-top: 14rpx;
      font-size: 26rpx;
      color: #898989;
      .overlay-time {
        margin-right: 36rpx;
      }
    }
    .overlay-text {
      margin-top: 28rpx;
      font-size: 28rpx;
      color: #333333;
      line-height: 50rpx;
    }
    .overlay-ercode {
      margin-top: 80rpx;
      position: relative;
      height: 164rpx;
      .ercode-bg {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        width: 164rpx;
        height: 164rpx;
        margin: 0 auto;
        z-index: 1;
      }
      .ercode-url {
        position: absolute;
        left: 0;
        right: 0;
        top: 18rpx;
        width: 129rpx;
        height: 129rpx;
        margin: 0 auto;
        z-index: 5;
      }
    }
    .overlay-ercode-text {
      margin-top: 20rpx;
      font-size: 20rpx;
      text-align: center;
    }
    .overlay-colse-icon {
      position: absolute;
      right: 10rpx;
      top: 10rpx;
      z-index: 100;
      line-height: 80rpx;
    }
  }
  .save-btn {
    width: 690rpx;
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    border-radius: 12rpx;
    background: #6eb657;
    color: #ffffff;
    font-size: 30rpx;
    margin-top: 30rpx;
  }
  .save-text {
    margin-top: 16rpx;
    width: 690rpx;
    text-align: center;
    font-size: 26rpx;
    color: #ffffff;
  }
}
.canvas {
  width: 100%;
  position: fixed;
  top: 500000px;
}
</style>
