<template>
  <popup ref="popup" background="transparent" class="pop" @change="change">
    <modal :title="typeInfo[type].title" type="warning" hide-cancel-btn hide-confirm-btn mkclick>
      <view v-if="type !== 'poster'" class="content">
        <view class="content__top">{{ typeInfo[type].top }}</view>
        <image v-if="typeInfo[type].qr" :src="typeInfo[type].qr" class="content__qrcode" />
        <template v-for="item in typeInfo[type].bottom">
          <view :key="item.text" class="content__bottom">
            <text v-if="item.tag" class="content__bottom--tag">{{ item.tag }}</text>
            <tetx class="content__bottom__text">{{ item.text }}</tetx>
          </view>
        </template>
        <template v-for="btn in typeInfo[type].btn">
          <button v-if="!btn.type" :key="btn.text" class="content__btn" @click="action(btn)">
            {{ btn.text }}
          </button>
          <view v-else :key="btn.text" class="content__text" @click="action(btn)">
            {{ btn.text }}
          </view>
        </template>
      </view>
      <view v-if="type === 'poster'" class="content__poster">
        <image v-if="typeInfo[type].url" :src="typeInfo[type].url" class="content__poster" />
      </view>
    </modal>
  </popup>
</template>
<script>
import modal from "./uni-popup/uni-popup-dialog";
import popup from "./uni-popup/uni-popup";
import { downApp } from "../utils/index";
import { saTrackEvent } from "@/utils/sa";
import { getFaceUrl } from "@/api/face.api";
export default {
  options: { styleIsolation: "shared" },
  components: {
    modal,
    popup
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: "gzh"
    },
    scene: {
      // 用于区分ka渠道活体场景，user -> 我的页面  pay -> 收银台
      type: String,
      default: "user"
    }
  },
  data() {
    return {
      vccChannel: "",
      sonVccChannel: "",
      typeInfo: {
        wx: {
          url: "https://img.lkbang.net/xcx/downGzh.png",
          qr: "https://img.lkbang.net/xcx/gzhQrcode.png",
          top: "请关注【羊小咩Plus】公众号，获得更多信息",
          title: "关注微信",
          bottom: [{ text: "下载保存图片" }, { text: "微信扫一扫识别二维码" }],
          btn: [{ text: "保存图片", fn: this.saveEwm }]
        },
        gzh: {
          url: "https://img.lkbang.net/xcx/downGzh.png",
          qr: "https://img.lkbang.net/xcx/gzhQrcode.png",
          top: "请关注【羊小咩Plus】公众号，获得更多信息",
          title: "该功能正在开发中",
          bottom: [{ text: "下载保存图片" }, { text: "微信扫一扫识别二维码" }],
          btn: [{ text: "保存图片", fn: this.saveEwm }]
        },
        app: {
          url: "https://img.lkbang.net/xcx/downApp.png",
          qr: "https://img.lkbang.net/xcx/appQrcode.png",
          top: "请在羊小咩APP中完成后续操作",
          title: "该功能正在开发中",
          bottom: [
            { text: "微信识别图中二维码下载羊小咩APP" },
            { text: "复制链接在浏览器打开前往应用市场下载", tag: "推荐" }
          ],
          btn: [
            { text: "复制链接", fn: this.clipboard },
            { text: "保存图片", fn: this.saveEwm, type: "text" }
          ]
        },
        appToFace: {
          url: "",
          qr: "",
          top: "完成后即可释放享花卡额度",
          title: "请前往浏览器完成活体认证",
          bottom: [
            { text: "复制链接在浏览器打开进行活体认证" }
            // { text: "微信识别图中二维码下载羊小咩APP" },
            // { text: "复制链接在浏览器打开前往应用市场下载", tag: "推荐" }
          ],
          btn: [
            { text: "复制链接", fn: this.clipboard }
            // { text: "保存图片", fn: this.saveEwm, type: "text" }
          ]
        },
        poster: {
          url: "https://appsync.lkbang.net/FntLKua4kHYylJqI1EPXO7rB4yug"
        }
      }
    };
  },
  watch: {
    value: {
      immediate: true,
      handler: function(val) {
        val ? this.$refs.popup.open && this.$refs.popup.open() : null;
      }
    }
  },
  methods: {
    saveEwm() {
      const _self = this;
      uni.getSetting({
        success(res) {
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            uni.authorize({
              scope: "scope.writePhotosAlbum",
              success() {
                //这里是用户同意授权后的回调
                _self.saveImage();
              },
              fail(error) {
                console.log(error);
                uni.showModal({
                  title: "温馨提示",
                  content: "保存图片功能需要您的微信授权才能使用",
                  cancelText: "不授权",
                  confirmText: "授权",
                  confirmColor: "#ec1500",
                  success: function(res) {
                    if (res.confirm) {
                      // 这个 API 是基础库 1.1.0 才有的，所以需要做兼容处理：
                      if (uni.openSetting) {
                        uni.openSetting({
                          //进入授权设置页面手动授权
                          success: function() {}
                        });
                      }
                      //低版本兼容  做提示操作
                      else {
                        uni.showModal({
                          title: "授权提示",
                          confirmColor: "#ec1500",
                          content:
                            "保存图片需要您的微信授权才能使用，错过授权页面的处理方法：1、删除小程序->重新搜索进入->点击授权按钮；2、可在小程序设置打开相应权限"
                        });
                      }
                    }
                    //用户继续拒绝授权。
                    else if (res.cancel) {
                      uni.showModal({
                        title: "温馨提示",
                        content:
                          "相册授权失败，错过授权页面的处理方法：1、删除小程序->重新搜索进入->点击授权按钮；2、可在小程序设置打开相应权限",
                        showCancel: false,
                        confirmColor: "#ec1500",
                        success: function() {
                          _self.refuseSaveImage && _self.refuseSaveImage();
                        }
                      });
                    }
                  }
                });
              } //这里是用户拒绝授权后的回调
            });
          } else {
            //用户已经授权过了
            _self.saveImage();
          }
        }
      });
    },
    saveImage() {
      uni.downloadFile({
        url: this.typeInfo[this.type].url,
        success: function(res) {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function() {
                uni.showToast({
                  title: "保存成功",
                  icon: "none"
                });
              },
              fail: function() {
                uni.showToast({
                  title: "保存失败",
                  icon: "none"
                });
              }
            });
          }
        },
        fail: function(error) {
          console.log(error);
        }
      });
    },
    change(val) {
      if (val?.show === false) {
        saTrackEvent("PD_YXMMACP_UserClickGuidePopupWindowBtn", {
          buttons_name: "遮罩层"
        });
      }
      this.$emit("change", val);
    },
    async clipboard() {
      if (this.type === "appToFace") {
        // 活体认证提示
        const pages = getCurrentPages();
        const page = pages[pages.length - 1];
        const orderNo = Object.keys(page.options).length == 0 ? "" : page.options.orderNo;
        const pagePath = page.route || "";
        const from = pagePath.indexOf("pages/user/user") > -1 ? "user" : "pay";
        const token = uni.getStorageSync("token") || "";
        this.vccChannel = uni.getStorageSync("vccChannel") || "";
        this.sonVccChannel = uni.getStorageSync("sonVccChannel") || "";
        console.log(token, from, orderNo);
        const [result] = await getFaceUrl(token, from, orderNo);
        if (!result) return;
        uni.setClipboardData({
          data: result.faceUrl,
          success: function() {
            console.log("open vcc face ocr");
          }
        });
        return;
      }
      uni.setClipboardData({
        data: downApp,
        success: function() {
          console.log(downApp);
        }
      });
    },
    action(btn) {
      saTrackEvent("PD_YXMMACP_UserClickGuidePopupWindowBtn", {
        buttons_name: btn.text
      });
      if (this.type === "appToFace") {
        const pages = getCurrentPages();
        const page = pages[pages.length - 1];
        const pagePath = page.route || "";
        saTrackEvent("MINI_BodyConfirmationPopupWindowBtnClick", {
          page_name: pagePath.indexOf("pages/user/user") > -1 ? "user" : "pay",
          buttons_name: btn.text
        });
      }
      btn.fn();
    }
  }
};
</script>
<style lang="scss">
.pop {
  text-align: center;
  .uni-dialog-content {
    padding: 0 0 48rpx 0;
  }
  .content {
    &__top {
      font-size: 24rpx;
      color: #999999;
    }
    &__qrcode {
      width: 300rpx;
      height: 300rpx;
      margin-top: 40rpx;
      margin-bottom: 18rpx;
    }
    &__poster {
      width: 300rpx;
      height: 500rpx;
    }
    &__bottom {
      font-size: 28rpx;
      color: #333333;
      margin: 16rpx;
      display: flex;
      align-items: flex-start;
      justify-content: center;
      &--tag {
        min-width: 60rpx;
        font-size: 20rpx;
        color: #ffffff;
        padding: 4rpx 8rpx;
        border-radius: 8rpx;
        margin-right: 8rpx;
        @include primary-bg;
        margin-top: 2rpx;
      }
    }
    &__btn {
      color: $white;
      margin-top: 48rpx;
      font-size: 32rpx;
      border-radius: $uni-border-radius-xl;
      width: 526rpx;
      @include primary-bg;
    }
    &__text {
      font-size: 32rpx;
      margin-top: 36rpx;
      color: #ec1500;
    }
  }
}
</style>
