<template>
  <div class="Mall4j page-promote-goods">
    <z-paging
      ref="pagingRef"
      v-model="goodsList"
      :paging-style="{'top': '0','background-color': '#f2f3f7'}"
      empty-view-text="没有找到推广商品喔~"
      loading-more-no-more-text="没有更多了~"
      @query="loadPageData"
    >
      <template #top>
        <view>
          <!-- 搜索框 -->
          <view class="search-top">
            <view class="search-box">
              <view class="icon">
                <image src="/static/images/search.png" />
              </view>
              <input
                type="text"
                placeholder="输入关键字搜索"
                confirm-type="search"
                class="input"
                @input="onProdNameInput"
                @confirm="onProdNameSearch"
              >
            </view>
            <view
              class="list-style"
              @tap="changeListStyle"
            >
              <image
                v-if="isLineProds"
                src="/static/images/list-row.png"
              />
              <image
                v-else
                src="/static/images/list-line.png"
              />
            </view>
          </view>
          <!-- 筛选栏 -->
          <view class="sortbar">
            <view
              :class="'item' + (sort==='' ?' active':' ')"
              @tap="onTabTouch(1)"
            >
              默认
            </view>
            <view
              :class="['item', (sort===2 || sort===3?'active':''), (sort===2?'arrow-up':''),(sort===3?'arrow-down':'')]"
              @tap="onTabTouch(2)"
            >
              销量
            </view>
            <view
              :class="['item', (sort===4 || sort===5?'active':''), (sort===4?'arrow-up':''),(sort===5?'arrow-down':'')]"
              @tap="onTabTouch(3)"
            >
              价格
            </view>
          </view>
        </view>
      </template>
      <view class="Mall4j page-promote-goods">
        <!-- 产品列表 -->
        <view :class="[isLineProds ? 'line-prods' : 'prods']">
          <view
            v-for="(item, index) in goodsList"
            :key="index"
            class="item"
          >
            <view class="img">
              <image
                v-if="item.mainImgUrl"
                :src="util.addDomain(item.mainImgUrl)"
                @error="imgErr(index)"
              />
              <image
                v-else
                mode="aspectFit"
                src="/static/images/def.png"
              />
            </view>
            <view class="text-box">
              <view
                class="name"
              >
                {{ item.spuName }}
              </view>
              <view class="expected">
                {{ $t('distribution.expectedEarn') }} {{ wxs.parsePrice(item.distributionInfo.awardNumbers)[0] }}{{ (item.distributionInfo.awardMode!==0? '.' + wxs.parsePrice(item.distributionInfo.awardNumbers)[1] : '' ) }}{{ item.distributionInfo.awardMode===0?'%':$t('distribution.yuan') }}
              </view>
              <view class="price-box">
                <view class="price">
                  <view class="symbol">
                    ￥
                  </view>
                  <view class="big">
                    {{ wxs.parsePrice(item.priceFee)[0] }}
                  </view>
                  <view class="symbol">
                    .{{ wxs.parsePrice(item.priceFee)[1] }}
                  </view>
                </view>
                <view
                  class="btn"
                  :data-spuid="item.spuId"
                  :data-spuname="item.spuName"
                  :data-pic="item.mainImgUrl"
                  :data-price="item.priceFee"
                  @tap="onShowSharePop"
                >
                  分享
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 分享弹窗 -->
    <view
      v-if="shareShow"
      class="promo-share"
    >
      <image
        v-if="picture&&showCanvasImg"
        class="picture-img"
        :src="picture"
      />
      <l-painter
        ref="painterRef"
        :board="poster"
        path-type="url"
        hidden
        is-canvas-to-temp-file-path
        @success="pictureSuccess"
      />
      <view
        v-if="showShareBtn"
        class="promo-main"
      >
        <!-- #ifndef H5  -->
        <view class="promo-tit">
          <title>分享当前图片到</title>
        </view>
        <!-- #endif -->
        <!-- #ifdef H5  -->
        <view
          v-if="isWechat"
          class="promo-tit"
        >
          <title>分享当前图片到</title>
        </view>
        <!-- #endif -->
        <view class="promo-icons">
          <!-- #ifdef H5  -->
          <view
            v-if="isWechat"
            class="promo-img1"
            @tap="onShareWay"
          >
            <view class="promo-img1-icon">
              <image
                src="/static/images/wetchat.png"
                mode="aspectFit"
              />
            </view>分享
          </view>
          <view
            v-if="!isWechat"
            class="promo-tit1"
          >
            长按图片保存
          </view>
          <!-- #endif -->
          <!-- #ifndef H5  -->
          <view
            class="promo-img1"
            @tap="saveImg"
          >
            <view class="promo-img1-icon">
              <image
                src="/static/images/export.png"
                mode="aspectFit"
              />
            </view>保存图片
          </view>
          <!-- #endif -->
        </view>
        <view
          class="promo-close"
          @tap="closeEarn"
        >
          取消
        </view>
      </view>
    </view>
    <!-- 分享弹窗 end -->

    <!-- 二维码弹窗 -->
    <view
      v-if="wxCodeShow"
      class="code-popup"
    >
      <view class="code-main">
        <view
          class="close-v"
          @tap.stop="closeCodePopup"
        >
          <image
            src="../../../static/images/close-share.png"
            class="close-png"
          />
        </view>
        <view class="code-v">
          <image
            :src="shareWxCode"
            class="wx-code"
          />
        </view>
        <!-- #ifndef H5 -->
        <view
          class="code-txt"
          @tap="downloadImg"
        >
          {{ $t('distribution.saveAlbum') }}
        </view>
        <!-- #endif -->
      </view>
    </view>
    <!-- 二维码弹窗 end -->

    <!-- 引导分享蒙版 -->
    <view
      v-if="guideShare"
      class="guide-share-mask"
    >
      <view class="mask" />
      <view class="guide-content">
        <view
          class="close"
          @tap="guideShare=false"
        >
          <image src="../../../static/images/close-share.png" />
        </view>
        <view class="share-img">
          <image src="../../../static/images/shareIcon.png" />
        </view>
        <view class="share-word">
          <view class="big-word">
            {{ $t('distribution.shareFriendsNow') }}
          </view>
          <view class="small-word">
            {{ $t('distribution.shareFriendsTips2') }}
          </view>
        </view>
      </view>
    </view>
    <!-- 引导分享蒙版 end -->

    <!-- 分享弹窗 -->
    <view
      v-if="sharePopupShow"
      class="activitys"
      @tap="sharePopupShow = false"
    >
      <view
        class="activitys-box share"
        @tap.stop
      >
        <view class="activitys-tit radius">
          <view class="text">
            分享至
          </view>
          <image
            class="img"
            src="/static/images/icon/icon_close.png"
            mode=""
            @tap="sharePopupShow = false"
          />
        </view>
        <view class="share-cnt">
          <view
            class="item left"
            @tap="onShowShare()"
          >
            <image
              class="img"
              src="/static/images/icon_Generate.png"
            />
            <view>
              生成图片
            </view>
          </view>

          <!-- #ifndef MP-WEIXIN -->
          <view
            class="item right"
            @tap="copylink"
          >
            <image
              class="img"
              src="/static/images/icon_copy.png"
            />
            <view class="text">
              复制链接
            </view>
          </view>
          <!-- #endif -->

          <!-- #ifdef MP-WEIXIN -->
          <button
            class="item right"
            open-type="share"
          >
            <image
              class="img"
              src="/static/images/icon_copy.png"
            />
            <view class="text">
              分享链接
            </view>
          </button>
          <!-- #endif -->
        </view>
      </view>
    </view>
    <!-- 分享弹窗 end -->
  </div>
</template>

<script setup>
import Wechat from '@/utils/wechat.js'
import Qr from '@/utils/wxqrcode.js'
import util from '@/utils/util.js'

const wxs = number()

const shareShow = ref(false)
const wxCodeShow = ref(false)
const shareImgUrl = ref('')
const dpObj = {} // 画布参数

const isWechat = ref(false) // 是否为微信环境
onLoad(() => {
  // #ifdef H5
  isWechat.value = Wechat.isWechat()
  // #endif
  // #ifdef APP-PLUS
  isWechat.value = false
  // #endif
  // #ifdef MP-WEIXIN
  isWechat.value = true
  // #endif
  getDisInfo()
  getShareLink()
})

/**
  * 用户点击微信图标转发
  */
onShareAppMessage((res) => {
  if (res.from === 'button') {
    const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
    return {
      title: shareProdName,
      path: '/pages/detail/detail?spuId=' + shareProdId + '&distributionUserId=' + distributionUserId,
      imageUrl: dpObj.sharePic
    }
  } else {
    return {
      title: shareProdName,
      path: '/pages/detail/detail?spuId=' + shareProdId,
      imageUrl: dpObj.sharePic
    }
  }
})

// 分销商品列表
const pagingRef = ref(null)
const goodsList = ref([])
const loadPageData = (pageNum, pageSize) => {
  http.request({
    url: '/tmerclub_search/ua/search/page_distribution_spu',
    method: 'GET',
    data: {
      pageNum,
      pageSize,
      orderBy: 1,
      spuName: spuName.value,
      distributionState: 1,
      sort: sort.value
    }
  }).then(res => {
    // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
    pagingRef.value.complete(res.list[0].spus)
  })
}

/**
 * 点击导航菜单
 */
const sort = ref('') // 排序(0 佣金排序 1时间排序 2销量排序 3价格排序) 默认1
const onTabTouch = (type) => {
  // 1 默认 //2 销量 //3 价格
  // 2 降序 3升序
  // 4 降序 5升序
  if (type === 1) {
    sort.value = ''
  }

  if (type === 2) {
    if (sort.value === 2) {
      sort.value = 3
    } else {
      sort.value = 2
    }
  }

  if (type === 3) {
    if (sort.value === 4) {
      sort.value = 5
    } else {
      sort.value = 4
    }
  }
  pagingRef.value.reload()
}

// 名称输入
const spuName = ref('')
const onProdNameInput = (e) => {
  spuName.value = e.detail.value.trim()
}

/**
 * 搜索
 */
const onProdNameSearch = () => {
  pagingRef.value.reload()
}

// 切换列表格式
const isLineProds = ref(true) // 列表格式，默认横排展示
const changeListStyle = () => {
  isLineProds.value = !isLineProds.value
}

/**
 * 获取分销员信息
 */
const getDisInfo = () => {
  http.request({
    url: '/tmerclub_marketing/distribution_user/distribution_user_info',
    method: 'GET'
  }).then(res => {
    if (res.state === -1) {
      shareShow.value = false
      uni.showModal({
        title: '',
        showCancel: false,
        content: $t('distribution.distributorBanned'),
        confirmText: $t('distribution.confirm'),
        confirmColor: '#eb2444',
        success (res) {
          if (res.confirm) {
            uni.switchTab({
              url: '/pages/my/my'
            })
          }
        }
      })
    }

    if (res.state === 2) {
      shareShow.value = false
      uni.showToast({
        title: $t('distribution.distributorCleared'),
        mask: true,
        icon: 'none'
      })
      uni.showModal({
        title: '',
        content: $t('distribution.distributorCleared'),
        confirmText: $t('distribution.confirm'),
        confirmColor: '#eb2444',
        showCancel: false
      })
    }
  })
}

const sharePopupShow = ref(false)

const onShowSharePop = (e) => {
  shareProdId = e.currentTarget.dataset.spuid
  shareProdName = e.currentTarget.dataset.spuname
  dpObj.sharePic = e.currentTarget.dataset.pic
  dpObj.sharePrice = e.currentTarget.dataset.price

  sharePopupShow.value = true
}

const copylink = () => {
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')

  const code = `${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/pages/detail/detail?spuId=${shareProdId}&distributionUserId=${distributionUserId}`
  uni.setClipboardData({
    data: code,
    showToast: false,
    success: function () {
      uni.showToast({
        title: '复制成功',
        icon: 'none'
      })
      sharePopupShow.value = false
    }
  })
}

onShareAppMessage(() => {
  sharePopupShow.value = false
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')

  return {
    title: shareProdName,
    path: '/pages/detail/detail?spuId=' + shareProdId + '&distributionUserId=' + distributionUserId,
    imageUrl: dpObj.sharePic
  }
})

/**
 * 生成复制分享链接
 */
const getShareLink = () => {
  // 从缓存获取分销员卡号，如果没有则去接口获取，以备转发时使用
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
  if (!distributionUserId) {
    http.request({
      url: '/tmerclub_marketing/distribution_user/distribution_user_info',
      method: 'GET'
    }).then(res => {
      uni.setStorageSync('cloudDistributionUserId', res.distributionUserId)
    })
  }
}

// 商品图片加载失败
const imgErr = (index) => {
  goodsList.value[index].mainImgUrl = ''
}

/**
 * 显示分享弹窗
 */
const showShareBtn = ref(false) // 分享栏
const showCanvasImg = ref(true) // 海报图片（小程序不显示）
let shareProdId = 0
let shareProdName = ''
const canvasW = ref(0) // 画布宽
const canvasH = ref(0) // 画布高
const marginTopCanvas = ref(0)
const onShowShare = () => {
  picture.value = ''
  getDisInfo()
  shareImgUrl.value = ''
  shareShow.value = true
  // #ifndef MP-WEIXIN
  showShareBtn.value = true
  // #endif
  // #ifdef MP-WEIXIN
  showCanvasImg.value = false
  // #endif

  dpObj.shareProdName = shareProdName
  dpObj.canvasH = canvasH
  dpObj.shareShow = shareShow
  dpObj.shareImgUrl = shareImgUrl
  dpObj.completeDraw = completeDraw
  uni.getSystemInfo({
    success: function (res) {
      canvasW.value = res.windowWidth * 0.8
      marginTopCanvas.value = (res.windowHeight - (400 * res.windowWidth / 750)) * 0.1 * 0.7
      dpObj.systemInfo = res
      dpObj.canvasW = canvasW.value
      dpObj.canvasHMax = (res.windowHeight - (400 * res.windowWidth / 750)) * 0.9
    }
  })
  getShareLink()
  // 从缓存获取分销员卡号，如果没有则去接口获取，以备转发时使用
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
  if (!distributionUserId) {
    http.request({
      url: '/tmerclub_marketing/distribution_user/distribution_user_info',
      method: 'GET'
    }).then(res => {
      uni.setStorageSync('cloudDistributionUserId', res.distributionUserId)
      genWeixinCode()
    })
  } else {
    genWeixinCode()
  }
}

/**
 * 关闭分享弹窗
 */
const closeEarn = () => {
  shareShow.value = false
  shareImgUrl.value = ''
}

/**
 * 用户点击分享到微信小程序
 * @param {Object} sharedata 支付需要的参数
 * @param {Object} cb 成功回调
 * @param {Object} errorCb 失败回调
 */
const guideShare = ref(false) // 引导蒙版
const onShareWay = () => {
  if (isWechat.value) {
    const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
    const sharedata = {
      title: shareProdName, // 分享标题
      imgUrl: dpObj.sharePic, // 分享图标
      link: import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/pages/detail/detail?spuId=' + shareProdId + '&distributionUserId=' + distributionUserId, // 分享链接
      desc: '这个商品不错，快来看看吧！', // 分享描述
      type: '', // 分享类型,music、video或link，不填默认为link
      dataUrl: '' // 如果type是music或video，则要提供数据链接，默认为空
    }
    Wechat.callWexinShare(sharedata, () => {
      shareShow.value = false
      guideShare.value = true
    }, (failMsg) => {
      // eslint-disable-next-line no-console
      console.log('shareFailMsg', failMsg)
    })
  }
}

// 生成小程序二维码
const shareWxCode = ref('')
const genWeixinCode = () => {
  uni.showToast({
    icon: 'loading',
    mask: true,
    duration: 10000,
    title: '海报绘制中'
  })
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
  const content = JSON.stringify({
    spuId: shareProdId,
    distributionUserId
  })

  // #ifdef H5 || APP-PLUS
  const code = `${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/pages/detail/detail?spuId=${shareProdId}&distributionUserId=${distributionUserId}`
  shareWxCode.value = Qr.createQrCodeImg(code, { size: 250 })
  poster.value = util.getPoster(dpObj.sharePic, dpObj.sharePrice, shareProdName, shareWxCode.value)

  // #endif

  // #ifdef MP-WEIXIN
  http.request({
    url: '/tmerclub_biz/ua/qrcode_ticket/mini_qrcode',
    method: 'GET',
    responseType: 'arraybuffer',
    data: {
      content,
      type: 2
    }
  }).then(res => {
    // 微信小程序
    shareWxCode.value = uni.arrayBufferToBase64(res)
    util.base64src(shareWxCode.value).then(res => {
      shareWxCode.value = res
      poster.value = util.getPoster(dpObj.sharePic, dpObj.sharePrice, shareProdName, shareWxCode.value)
      shareShow.value = true
      showCanvasImg.value = false
    })
  })
  // #endif

  sharePopupShow.value = false
}

/* 保存图片 */
const painterRef = ref(null)
const saveImg = () => {
  // #ifndef H5
  painterRef.value.canvasToTempFilePath().then(res => {
    uni.saveImageToPhotosAlbum({
      filePath: res.tempFilePath,
      success: function () {
        uni.showToast({
          icon: 'none',
          mask: true,
          title: '保存成功'
        })
      },
      fail: () => {
        uni.showToast({
          icon: 'none',
          mask: true,
          title: '保存失败'
        })
      }
    })
  })
  // #endif
}

// 关闭弹窗
const closeCodePopup = () => {
  wxCodeShow.value = false
}

// 保存图片至相册
const downloadImg = () => {
  uni.showLoading({
    mask: true
  })
  // #ifdef APP-PLUS
  const bitmap = new plus.nativeObj.Bitmap('test')
  bitmap.loadBase64Data(
    shareWxCode.value,
    () => {
      const url = '_doc/' + new Date() + '.png' // url建议用时间戳命名方式
      bitmap.save(
        url,
        {
          overwrite: true
        },
        () => {
          uni.saveImageToPhotosAlbum({
            filePath: url,
            success: () => {
              uni.hideLoading()
              wxCodeShow.value = false
              uni.showToast({
                title: $t('distribution.downloadComplete')
              })
              bitmap.clear()
            }
          })
        },
        () => {
          uni.hideLoading()
          bitmap.clear()
        }
      )
    },
    () => {
      uni.hideLoading()
      bitmap.clear()
    }
  )
  // #endif
  // #ifdef MP-WEIXIN
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
  uni.downloadFile({
    header: {
      Authorization: uni.getStorageSync('cloudToken')
    },
    url: import.meta.env.VITE_APP_BASE_API + '/tmerclub_marketing/ua/distribution_qrcode/invitation?page=pages/detail/detail&distributionUserId=' + shareProdId + ',' +
          distributionUserId,
    success: (res) => {
      uni.hideLoading()
      // 图片保存到本地
      uni.getSetting({
        success: settingData => {
          const flag = settingData.authSetting['scope.writePhotosAlbum']
          if (flag === true || flag === undefined) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                wxCodeShow.value = false
                uni.showToast({
                  title: $t('distribution.downloadComplete'),
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: () => {
                uni.showToast({
                  title: $t('distribution.failedSaveTips'),
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          } else {
            uni.openSetting({
              success: settingData => {
                if (settingData.authSetting['scope.writePhotosAlbum']) {
                  uni.showToast({
                    title: $t('distribution.failedSave'),
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  uni.showToast({
                    title: $t('distribution.failedSaveTips'),
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            })
          }
        }
      })
    }
  })
  // #endif
}

const poster = ref('')
const picture = ref(null)

const pictureSuccess = (e) => {
  uni.hideToast()
  picture.value = e
  // #ifdef MP-WEIXIN
  shareShow.value = false
  completeDraw()
  // #endif
}

// 海报绘制完成
const completeDraw = () => {
  // #ifdef MP-WEIXIN
  uni.showShareImageMenu({
    path: picture.value,
    success: () => {
      shareShow.value = false
    },
    fail: () => {
      shareShow.value = false
    }
  })
  // #endif
}

</script>
<style lang="scss" scoped>
@use "./promote-goods.scss";
</style>
