<template>
  <u-popup v-model="show" mode="center" :maskCloseAble="false" :closeable="true"
    :maskCustomStyle="{ background: 'rgba(0, 0, 0, 0.5)' }" border-radius="18" :z-index="12" @close="onClose()">

    <view class="pop-poster pop-example__container">
      <view class="image__container" @click="handlePreviewImage()">
        <image v-if="imageUrl" class="image" mode="scaleToFill" :src="imageUrl"></image>
      </view>
      <view class="save-btn__container">
        <view class="save-btn" @click="handleDownload()">保存海报图</view>
      </view>
    </view>

  </u-popup>
</template>

<script>
  export default {
    name: 'goods-poster-popup',
    props: {
      // true 组件显示 false 组件隐藏
      value: {
        type: Boolean,
        default: false
      },
      // 获取海报图的api方法
      apiCall: {
        type: Function,
        default: () => {}
      },
      // 获取海报图的api参数
      apiParam: {
        type: Object,
        default: () => {}
      },
    },
    watch: {
      // 监听海报图弹层显示隐藏
      value: {
        immediate: true,
        handler(val) {
          val && this.onShowPopup()
        }
      },
    },
    data() {
      return {
        // 是否显示弹窗
        show: false,
        // 图片url地址
        imageUrl: ''
      }
    },
    methods: {

      // 显示海报弹窗
      onShowPopup() {
        const app = this
        console.log('GoodsPosterPopup onShowPopup 被调用');
        console.log('apiCall 类型:', typeof app.apiCall);
        console.log('apiCall 函数:', app.apiCall);
        console.log('apiParam:', app.apiParam);
        console.log('platform:', app.platform);

        if (typeof app.apiCall !== 'function') {
          console.error('apiCall 不是一个函数!');
          uni.showToast({
            title: '海报生成功能异常',
            icon: 'none'
          });
          app.onClose();
          return;
        }

        const params = { ...app.apiParam, channel: app.platform };
        console.log('调用 apiCall，参数:', params);

        app.apiCall(params)
          .then(result => {
            console.log('apiCall 调用成功，结果:', result);
            if (result && result.data && result.data.imageUrl) {
              app.imageUrl = result.data.imageUrl;
              app.show = true;
              console.log('海报图片URL设置成功:', app.imageUrl);
            } else {
              console.error('apiCall 返回的数据格式不正确:', result);
              uni.showToast({
                title: '海报生成失败',
                icon: 'none'
              });
              app.onClose();
            }
          })
          .catch(err => {
            console.error('apiCall 调用失败:', err);
            uni.showToast({
              title: '海报生成失败',
              icon: 'none'
            });
            app.onClose();
          });
      },

      // 关闭弹窗
      onClose() {
        this.$emit('input', false)
      },

      // 预览图片
      handlePreviewImage() {
        uni.previewImage({ urls: [this.imageUrl] })
      },

      // 保存海报图片
      handleDownload() {
        const app = this
        uni.showLoading({ title: '加载中' })
        // 下载海报图片
        uni.downloadFile({
          url: app.imageUrl,
          success(res) {
            console.log(res)
            uni.hideLoading()
            // 图片保存到相册
            app.onSaveImage(res.tempFilePath)
          },
          fail(res) {
            console.log('fail', res)
            uni.hideLoading()
            app.$toast('很抱歉，自动保存失败 请点击图片后长按手动保存', 3000)
          }
        })
      },

      // 图片保存到相册
      onSaveImage(filePath) {
        const app = this
        uni.saveImageToPhotosAlbum({
          filePath,
          success(data) {
            app.$success('保存成功')
            // 关闭弹窗
            app.onClose()
          },
          fail(err) {
            console.log(err.errMsg)
            if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
              app.$toast('请允许访问相册后重试 (右上角菜单 - 设置 - 相册)', 3000)
            }
          }
        })
      }

    }
  }
</script>

<style lang="scss" scoped>
  .pop-poster {
    width: 560rpx;
    position: relative;
    background: #fff;
    padding: 76rpx 76rpx 40rpx 76rpx;
    border-radius: 10rpx;
  }

  // 图片容器
  .image__container {
    .image {
      display: block;
      width: 420rpx;
      height: 636rpx;
      box-shadow: 0 0 25rpx rgba(0, 0, 0, 0.15);
    }
  }

  // 保存按钮
  .save-btn__container {
    margin-top: 30rpx;

    .save-btn {
      color: rgb(255, 255, 255);
      color: $main-text;
      background: linear-gradient(to right, $main-bg, $main-bg2);
      font-weight: 500;
      font-size: 28rpx;
      border-radius: 38rpx;
      height: 76rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
</style>
