<script setup lang="ts">
import { useMemberStore } from '@/stores'
import type { goodsListItem } from '@/types/goods'
import { ref, reactive } from 'vue'
import { fullUrl, checkImage, getUserDefaultAvatar } from '@/utils/common'
import { getShareInfoApi } from '@/api/goods'
import { getShareUrl } from './sharePoster'
import { usePopupStore } from '@/stores'

const props = defineProps<{
  goods: goodsListItem
  currentPrice: string
  currentOriginPrice: string
  goodsImage: string
}>()

const sharePosterRef = ref()
const painter = ref()

const state = reactive({
  posterImgPath: '',
  showPoster: false,
  userAvatarImg: useMemberStore().profile!.avatar,
  qrcodeUrl: '',
})

const userImage = ref('')
const open = async () => {
  userImage.value = fullUrl(state.userAvatarImg)
  await checkImage(userImage.value)
    .then((url) => {
      userImage.value = url
    })
    .catch(() => {
      userImage.value = getUserDefaultAvatar()
    })

  // #ifdef MP-WEIXIN
  const shareInfo = await getShareInfoApi(props.goods.id)
  state.qrcodeUrl = shareInfo.result.qrcode_url
  // #endif

  await sharePosterRef.value?.open()
  state.showPoster = true
  state.posterImgPath = ''
  await uni.showLoading({
    title: '海报生成中…',
    mask: true,
  })
}

const close = () => {
  sharePosterRef.value.close()

  state.showPoster = false
}

const onDone = () => {}

const onSuccess = (imgPath: string) => {
  state.posterImgPath = imgPath
  uni.hideLoading()
}

const onSave = () => {
  // #ifdef MP-WEIXIN
  painter.value.canvasToTempFilePathSync({
    fileType: 'jpg',
    pathType: 'url',
    quality: 1,
    success: (res: any) => {
      console.log(res.tempFilePath)
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: () => {
          uni.showToast({
            title: '保存成功',
            icon: 'none',
          })
        },
        fail: (err) => {
          console.log(err)
          if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
            return uni.showToast({
              title: '取消保存',
              icon: 'none',
            })
          } else {
            uni.showToast({
              title: '保存失败',
              icon: 'none',
            })
          }
        },
        complete: () => {
          close()
        },
      })
    },
  })

  // #endif
}

defineExpose({ sharePosterRef, open, close })
</script>

<template>
  <uni-popup
    ref="sharePosterRef"
    type="center"
    :animation="false"
    :mask-click="false"
    @change="usePopupStore().onChangePopupProps"
  >
    <image :src="state.posterImgPath" mode="widthFix" style="width: 600rpx" />
    <view>
      <view class="poster">
        <l-painter
          ref="painter"
          isCanvasToTempFilePath
          @success="onSuccess"
          css="width: 750rpx; padding-bottom: 40rpx; background: #edca88; object-fit: contain;"
          hidden
          @done="onDone"
          :after-delay="500"
        >
          <l-painter-image
            :src="userImage"
            css="margin-left: 40rpx; margin-top: 40rpx; width: 100rpx;  height: 100rpx; border-radius: 50%;"
          />
          <l-painter-view css="margin-top: 40rpx; padding-left: 20rpx; display: inline-block">
            <l-painter-text
              :text="useMemberStore().profile?.nickname || ''"
              css="display: block; padding-bottom: 20rpx; color: #000; font-size: 32rpx; fontWeight: bold"
            />
            <l-painter-text text="推荐了一个好物给您" css="color: #000; font-size: 24rpx" />
          </l-painter-view>
          <l-painter-view
            css="margin-left: 40rpx; margin-top: 30rpx; padding: 32rpx; box-sizing: border-box; background: #fff; border-radius: 16rpx; width: 670rpx; box-shadow: 0 20rpx 58rpx rgba(0,0,0,.15)"
          >
            <l-painter-image
              :src="fullUrl(props.goodsImage)"
              css="object-fit: fill;  width: 600rpx; max-height: 550rpx; border-radius: 12rpx;"
            />
            <l-painter-view
              css="margin-top: 32rpx; color: #FF0000; font-weight: bold; font-size: 28rpx; line-height: 1em;"
            >
              <l-painter-text text="￥" css="vertical-align: bottom" />
              <l-painter-text
                :text="`${props.currentPrice.split('.')[0]}`"
                css="vertical-align: bottom; font-size: 58rpx"
              />
              <l-painter-text
                :text="`.${props.currentPrice.split('.')[1]}`"
                css="vertical-align: bottom"
              />
              <l-painter-text
                :text="`￥${props.currentOriginPrice}`"
                css="vertical-align: bottom; padding-left: 10rpx; font-weight: normal; text-decoration: line-through; color: #999999"
              />
            </l-painter-view>
            <l-painter-view css="margin-top: 30rpx">
              <l-painter-text
                :text="props.goods.name"
                css="line-clamp: 2; color: #333333; line-height: 1.5em; width: 620rpx; font-size: 30rpx; padding-right:32rpx; box-sizing: border-box"
              ></l-painter-text>
            </l-painter-view>
            <l-painter-view css="margin-top: 30rpx; display: flex; flex-wrap: nowrap;">
              <l-painter-text
                text="长按或扫一扫识别二维码"
                css="float: left; padding-bottom: 10rpx; color: #999999; font-size: 26rpx; margin-top: 60rpx; margin-right: 160rpx"
              />
              <!-- #ifdef MP-WEIXIN -->
              <l-painter-image
                v-if="state.qrcodeUrl"
                :src="state.qrcodeUrl"
                css="float: right; width: 150rpx; height: 150rpx;"
              />
              <!-- #endif -->
              <!-- #ifdef WEB -->
              <l-painter-qrcode
                :text="getShareUrl(props.goods.id)"
                css="float: right; width: 150rpx; height: 150rpx;"
              />
              <!-- #endif -->
            </l-painter-view>
          </l-painter-view>
        </l-painter>
      </view>
      <view class="action" v-if="state.posterImgPath">
        <view class="button cancel" @tap="close()">取消分享</view>
        <!-- #ifdef WEB -->
        <view>长按图片进行保存</view>
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->
        <view class="button" @tap="onSave()">保存图片</view>
        <!-- #endif -->
      </view>
    </view>
  </uni-popup>
</template>

<style lang="scss" scoped>
.action {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #f5f5f5;

  .button {
    padding: 16rpx 32rpx;
    margin: 0 10rpx;

    background: #ff784d;
    color: #ffffff;

    border-radius: 40rpx;

    &:active {
      opacity: 0.8;
    }
  }

  .cancel {
    background: #b3b3b3;
    color: #ffffff;
  }
}
</style>
