<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="component-share-shop-popup shareShopPopup">
    <uni-popup
      ref="sharePopRef"
      :is-mask-click="false"
      class="share-pop"
    >
      <view class="pop-main">
        <view class="shop-name-logo">
          <view class="shop-logo">
            <image
              :src="util.checkFileUrl(shopInfo.shopLogo)"
              style="width: 100%; height: 100%; min-width: 84rpx"
              mode="aspectFill"
            />
          </view>
          <view class="shop-name">
            {{ shopInfo.shopName }}
          </view>
        </view>
        <view class="qr-code">
          <!-- 商家二维码 -->
          <image
            class="code"
            :src="shareWxCode"
          />
        </view>
        <text class="tip-text">
          {{ $t('fenXiangDianPuGeiHaoYou') }}
        </text>
        <view class="share-item">
          <!-- 暂时只有在公众号才能分享到微信好友与朋友圈 -->
          <!-- #ifdef H5 -->
          <!-- 微信好友 -->
          <view
            v-if="isWechat"
            class="we-chat item"
            @tap="onShareWay(0)"
          >
            <view class="item-image">
              <image
                src="/static/images/we-chat.png"
                style="width: 36rpx; height: 36rpx"
                mode="aspectFit"
              />
            </view>
            <text class="item-text">
              {{ $t('weiXinHaoYou') }}
            </text>
          </view>
          <!-- 朋友圈 -->
          <view
            v-if="isWechat"
            class="circle-friends item"
            @tap="onShareWay(1)"
          >
            <view class="item-image">
              <image
                src="/static/images/circle-friends.png"
                style="width: 36rpx; height: 30rpx"
                mode="aspectFit"
              />
            </view>
            <text class="item-text">
              {{ $t('pengYouQuan') }}
            </text>
          </view>
          <!-- #endif -->
          <!-- 复制链接 -->
          <view
            class="copy-link item"
            @tap="copy"
          >
            <view class="item-image">
              <image
                src="/static/images/link.png"
                style="width: 30rpx; height: 30rpx"
                mode="aspectFit"
              />
            </view>
            <text class="item-text">
              {{ $t('fuZhiLianJie') }}
            </text>
          </view>
          <!-- 保存相册 -->
          <view
            v-if="!isWechat"
            class="save-to-album item"
            @tap="downloadImg"
          >
            <view class="item-image">
              <image
                src="/static/images/download.png"
                style="width: 30rpx; height: 30rpx"
                mode="aspectFit"
              />
            </view>
            <text class="item-text">
              {{ $t('baoCunXiangCe') }}
            </text>
          </view>
        </view>
      </view>
      <view
        class="pop-close"
        @tap="closeSharePop"
      >
        <image
          src="/static/images/close.png"
          style="width: 18rpx; height: 18rpx"
        />
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { onMounted } from 'vue'
import Qr from '../../utils/wxqrcode.js'
import util from '@/utils/util'

const emit = defineEmits(['openGuideShare', 'closeSharePop'])
const props = defineProps({
  shopInfo: {
    type: Object,
    default: () => {
      return {}
    }
  },
  isWechat: {
    type: Boolean,
    default: false
  }
})

let userMobileUrl = ''
// 需要保存的图片路径
const shareWxCode = ref('')

onMounted(() => {
  userMobileUrl = import.meta.env.VITE_APP_H5_DOMAIN
  const code = userMobileUrl + 'package-shop/pages/shop-page/shop-page?shopId=' + props.shopInfo.shopId
  shareWxCode.value = Qr.createQrCodeImg(code, { size: 250 })
})

// 复制链接
const copy = () => {
  util.uniCopy({
    content:
      userMobileUrl +
      'package-shop/pages/shop-page/shop-page?shopId=' +
      props.shopInfo.shopId,
    success: (res) => {
      uni.showToast({
        title: res,
        icon: 'none'
      })
    },
    error: (e) => {
      uni.showToast({
        title: e,
        icon: 'none',
        duration: 3000
      })
    }
  })
}

/**
 * 用户点击分享到微信好友或朋友圈
 * @param {number} scene 分享场景 0:微信好友分享，1:朋友圈分享
 */
const onShareWay = (scene) => {
  // #ifdef H5
  // 微信内置浏览器分享到微信
  if (props.isWechat) {
    const sharedata = {
      title: props.shopInfo.shopName, // 分享标题
      imgUrl: util.checkFileUrl(props.shopInfo.shopLogo), // 分享图标
      link:
        userMobileUrl +
        'package-shop/pages/shop-page/shop-page?shopId=' +
        props.shopInfo.shopId, // 分享链接
      desc: scene ? props.shopInfo.intro : '' // 分享描述(朋友圈分享无需desc参数)
    }
    if (scene === 0) {
      closeSharePop()
      emit('openGuideShare', scene)
      // 分享到微信好友
      wechat.callWexinShare(
        sharedata,
        () => {
          closeSharePop()
          emit('openGuideShare', scene)
        }
        // (failMsg) => {
        //   // console.log('shareFailMsg', failMsg)
        // }
      )
    } else {
      closeSharePop()
      emit('openGuideShare', scene)
      // 分享到朋友圈
      wechat.callonCircleFriendsShare(
        sharedata,
        () => {
          closeSharePop()
          emit('openGuideShare', scene)
        }
        // (failMsg) => {
        //   console.log('shareFailMsg', failMsg)
        // }
      )
    }
  }
  // #endif
}

/**
 * 保存图片至相册
 */
const downloadImg = () => {
  // #ifdef H5
  // 非微信内嵌浏览器保存图片
  if (!props.isWechat) {
    const isQuark = navigator.userAgent.toLowerCase().search(/quark/i) > -1 // 是否为夸克浏览器
    const sysInfo = uni.getSystemInfoSync()
    if (isQuark) {
      if (sysInfo.osName !== 'android') {
        uni.showToast({
          title: $t('longPressSaveTips'),
          icon: 'none'
        })
        return
      }
      const a = document.createElement('a') // 生成一个a元素
      const event = new MouseEvent('click', (true, false, window)) // 创建一个单击事件
      a.download = props.shopInfo.shopName + '.jpg' // 设置图片名称
      a.href = shareWxCode.value // 将生成的URL设置为a.href属性
      a.dispatchEvent(event) // 触发a的单击事件
      closeSharePop()
      return
    }
    // 把base64 转换为Blob 对象
    const arr = shareWxCode.value.split(',')
    const bytes = atob(arr[1])
    const ab = new ArrayBuffer(bytes.length)
    const ia = new Uint8Array(ab)
    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i)
    }
    const blob = new Blob([ab], { type: 'application/octet-stream' })
    // Blob 对象的 URL
    const url = URL.createObjectURL(blob)
    // 创建a 标签
    const a = document.createElement('a')
    a.href = url
    a.download = props.shopInfo.shopName + '.jpg'
    // 创建鼠标事件并初始化
    const e = new MouseEvent('click', (true, false, window))
    // 执行保存到本地
    a.dispatchEvent(e)
    URL.revokeObjectURL(url)
    closeSharePop()
  }
  // #endif

  // #ifndef H5 || MP-WEIXIN || APP-PLUS
  // 非H5进行保存
  uni.saveImageToPhotosAlbum({
    filePath: shareWxCode.value,
    success () {
      uni.showToast({
        icon: 'none',
        mask: true,
        title: $t('baoCunChengGong-0')
      })
    },
    fail () {
      uni.showToast({
        icon: 'none',
        mask: true,
        title: $t('baoCunShiBai-0')
      })
    }
  })
  // #endif
  // #ifdef APP-PLUS
  const bitmap = new plus.nativeObj.Bitmap('test')
  bitmap.loadBase64Data(shareWxCode.value, function () {
    const url = '_doc/' + new Date().getTime() + '.png' // url为时间戳命名方式
    bitmap.save(url, {
      overwrite: true // 是否覆盖
      // quality: 'quality'  // 图片清晰度
    }, () => {
      uni.saveImageToPhotosAlbum({
        filePath: url,
        success () {
          uni.showToast({
            title: $t('tuPianBaoCunChengGong'),
            icon: 'none'
          })
          bitmap.clear()
        }
      })
    }, () => {
      uni.showToast({
        title: $t('tuPianBaoCunShiBai'),
        icon: 'none'
      })
      bitmap.clear()
    })
  }, () => {
    uni.showToast({
      title: $t('tuPianBaoCunShiBai-0'),
      icon: 'none'
    })
    bitmap.clear()
  })
  // #endif
  // #ifdef MP-WEIXIN
  getSaveImg(shareWxCode.value)
  // #endif
}
// 获取授权判断是否授权相册
const getSaveImg = (qrcode) => {
  uni.getSetting({
    success: (res) => {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        uni.showModal({
          title: $t('jingGao'),
          content: $t('jianCeDaoNinMeiNinWeiShouQuanXiangCeQuanXianDianJiQueDingHuoQuShouQuan'),
          success (res) {
            if (res.confirm) {
              uni.authorize({
                scope: 'scope.writePhotosAlbum',
                success () {
                  // 用户已经同意
                  saveImgToAlbum(qrcode)
                },
                fail () {
                  // console.log('用户拒绝授权相册')
                }
              })
            }
          }
        })
      } else {
        saveImgToAlbum(qrcode)
      }
    }
    // fail: () => {
    //   console.log('点击了拒绝')
    // }
  })
}
// 保存二维码图片到相册
const saveImgToAlbum = (qrcode) => {
  const base64 = qrcode.replace(/^data:image\/\w+;base64,/, '')// 去掉data:image/png;base64,
  const fileManager = uni.getFileSystemManager()
  fileManager.writeFile({
    filePath: wx.env.USER_DATA_PATH + '/img.jpg', // 指定图片的临时路径
    data: base64, // 要写入的文本或二进制数据
    encoding: 'base64', // 指定写入文件的字符编码
    success: () => {
      // console.log('写入文件成功', res)
      // console.log(wx.env.USER_DATA_PATH + '/img.jpg')
      uni.saveImageToPhotosAlbum({ // 保存图片到相册
        filePath: wx.env.USER_DATA_PATH + '/img.jpg',
        success () {
          uni.showToast({
            title: $t('baoCunChengGong-1')
          })
        }
        // fail (err) {
        //   console.log('保存失败', err)
        // }
      })
    }
    // file: err => {
    //   console.log('写入文件失败', err)
    // }
  })
}

const sharePopRef = ref(null)
// 打开分享弹出框
const openSharePop = () => {
  sharePopRef.value?.open()
}
// 关闭分享弹出框
const closeSharePop = () => {
  emit('closeSharePop', '')
}
defineExpose({
  openSharePop
})

</script>

<style lang="scss" scoped>
@use './share-shop-popup.scss';
</style>
