<template>
    <JeepayCustomNavbar backCtrl="back" bgDefaultColor="#fff" title="支付宝代运营授权" />
    <view class="ali-wrapper">
    <view class="ali-top">
      <image class="ali-image" :src="calcStyleOrImg()" mode="scaleToFill" />
      <view class="ali-status" :style="{ color: calcStyleOrImg('color') }">{{ calcAliStatus() }}</view>
      <view class="ali-reset" @tap="upDateAliStatus">
        <image src="/static/iconImg/ali-resete.svg" mode="scaleToFill" /> 刷新授权状态
      </view>

      <view class="edit-input flex-center" style="margin-top: 30rpx">
        <view class="input-title">支付宝账号</view>
        <uni-easyinput :inputBorder="false" v-model="vdata.aliAccount" placeholderStyle=" font-size: 30rpx;color:#ADADAD"
          placeholder="请输入支付宝账号以授权" :styles="styles" clearable />
      </view>
    </view>
    <view class="ali-bottom">
      <view>
        <Button @tap="openPopup">{{ vdata.original?.handleStatus == 'SUCCESS' ? '重新' : '发起' }}授权</Button>
      </view>
    </view>
  </view>
  <JSinglePopup :list="list" ref="refSingle" />
  <uni-popup type="center" ref="refPopup">
    <view class="ali-img-wrapper">
      <view class="ali-tips">
        请使用支付宝账号【{{ vdata.aliAccount }}】绑定的支付宝扫码，根据页面指引完成授权
      </view>
      <image class="ali-image" :src="vdata.qrImg" mode="scaleToFill" />
      <view class="save-img">
        <Button @tap="saveImage(vdata.qrImg)">保存图片</Button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { $aliPayQrCodeOrApply, $aliAccountInfo } from "@/http/apiManager"
import infoBox from '@/commons/utils/infoBox.js';
import { ref, reactive, onMounted } from "vue"
const vdata = reactive({
  aliAccount: '',
  original: {},//存储原始数据
})
const styles = {
  backgroundColor: 'transparent',
  color: '#000',
  fontSize: '32rpx',
}
const refSingle = ref(null)
const refPopup = ref(null)
const list = [
  { label: '发送支付宝授权消息', value: 'phone', fun: () => { getAliQrCode('phone') } },
  { label: '使用支付宝扫授权码', value: 'scan', fun: () => { getAliQrCode('scan') } },
]
const getAliQrCode = (v) => {
  if (validate()) return
  $aliPayQrCodeOrApply(vdata.aliAccount, v == 'phone' ? 'apply' : 'queryQrcode').then(({ bizData }) => {
    vdata.qrImg = decodeURIComponent(bizData.qrCodeUrl)
    upDateAliStatus()
    if (v == 'phone') {
      infoBox.showToast('授权消息发送成功 请在支付宝 服务消息点击确认授权')
      return
    }
    refPopup.value.open()
  })
}

const getAliInfo = () => {
  $aliAccountInfo().then(({ bizData }) => {
    if (!bizData) return
    vdata.original = bizData
    vdata.aliAccount = bizData.alipayAccount
  })
}
getAliInfo()
const validate = () => {
  // 正则表达式 判断是否包含中文 和 中文符号
  const REG = /[\u4e00-\u9fa5|\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/
  if (vdata.aliAccount == vdata.original.alipayAccount && vdata.original.handleStatus == 'SUCCESS') return infoBox.showToast('当前支付宝账号已授权通过，无需再次授权。')
  if (REG.test(vdata.aliAccount)) return infoBox.showToast('账号格式错误 不能包含中文和中文标点符号')
  return false
}
const calcAliStatus = () => {
  if (!vdata.original.handleStatus) return '暂未授权'
  if (vdata.original.handleStatus == 'SUCCESS') return '已授权'
  if (vdata.original.handleStatus == 'PROCESS') return '授权中'
  return '暂未授权'
}
const calcStyleOrImg = (v = 'img') => {
  if (v == 'img') return vdata.original.handleStatus == 'SUCCESS' ? '/static/iconImg/ali-success.svg' : '/static/iconImg/ali-none.svg'
  if (v == 'color') return vdata.original.handleStatus == 'SUCCESS' ? '#000000ff' : '#afbbcbff'
}
// 更新授权状态
const upDateAliStatus = () => {
  $aliPayQrCodeOrApply().then(({ bizData }) => {
    infoBox.showToast('授权状态更新成功')
    if (bizData) vdata.original.handleStatus = bizData.handleStatus
  })
}
const saveImage = (key) => {
  // #ifdef  APP-PLUS

  uni.downloadFile({
    url: key,
    success: (res) => {
      if (res.statusCode == 200) {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: (r) => {
            infoBox.showSuccessToast('保存成功')
            uni.vibrateShort()
          },
          fail: (er) => {
            infoBox.showErrorToast('保存失败')
          }
        })
      }
    },
    fail: (err) => {
      infoBox.showErrorToast('保存失败')
    }
  })
  // #endif
  //#ifdef MP-WEIXIN
  downloadQR(key)
  //#endif
}

//#ifdef MP-WEIXIN
function downloadQR (key) {
  console.log('执行');
  wx.getSetting({
    //获取权限
    success (res) {
      if (res.authSetting['scope.writePhotosAlbum']) {
        if (key == 'authQr') return saveWxQrcodeImg(vdata.authQr)
        download(key)
      } else {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success () {
            if (key == 'authQr') return saveWxQrcodeImg(vdata.authQr)
            download(key)
          },
        })
      }
    },
  })
}
function download (data) {
  uni.downloadFile({
    url: data,
    success: (res) => {
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: function () {
          infoBox.showSuccessToast('保存成功')
          uni.vibrateShort()
        },
        fail: function (err) {
          infoBox.showErrorToast('保存失败')
        },
      })
    },
  })
}
//#endif
const openPopup = () =>{
  if(!vdata.aliAccount) return  infoBox.showToast('请输入支付宝账号。')
   refSingle.value.open()
}
</script>
<style lang="scss" scoped>
.ali-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: calc(100vh - 170rpx);
  overflow: hidden;

  .ali-top {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;

    .ali-image {
      margin-top: 50rpx;
      width: 350rpx;
      height: 280rpx;
    }

    .ali-status {
      margin: 20rpx 0 50rpx 0;
      color: #afbbcbff;
      font-size: 36rpx;
      font-weight: 500;
    }

    .ali-reset {
      display: flex;
      align-items: center;
      margin-bottom: 130rpx;
      color: #1f7bfeff;
      font-size: 26rpx;

      image {
        margin-right: 15rpx;
        width: 28rpx;
        height: 28rpx;
      }
    }
  }

  .ali-bottom {
    display: flex;
    justify-content: center;
    height: 180rpx;

    view {
      width: 400rpx;
    }
  }
}

.edit-input {
  padding: 0 20rpx;
  width: calc(100% - 100rpx);
  flex: 1;
  min-height: 120rpx;
  border-radius: 32rpx;
  background-color: #f7f7f7;
}

.input-title {
  margin-left: 40rpx;
  font-size: 30rpx;
  color: #000;
}

:deep .content-clear-icon {
  color: rgb(192, 196, 204) !important;
}

.ali-img-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
  width: calc(100% - 60rpx);
  min-height: 500rpx;
  background-color: #fff;
  border-radius: 22rpx;

  image {
    margin-top: 15rpx;
    width: 350rpx;
    height: 350rpx;
  }
}

.ali-tips {
  margin: 30rpx;
  margin-bottom: 0;
  text-align: center;
  color: #808080ff;
  font-size: 26rpx;
  line-height: 2;
}

.save-img {
  margin: 30rpx 0;
  width: 80%;
}</style>