<template>
  <view class="wallet_app" v-if="show">
    <view class="wallet_footer" :style="{ 'height': footerHeight + 48 + 'px' }">
      <view class="close">
        <view class="close_icon" @click.stop="close">
          <uni-icons type="closeempty" size="28" color="var(--text-01)"></uni-icons>
        </view>
      </view>
    </view>
		
		<!-- <GlobalLoading :msg="loadingStatus"></GlobalLoading> -->
  </view>
</template>

<script>
import GlobalLoading from '@/components/GlobalLoading.vue'
import { systemInfo, Toast } from "@/utils"
import { SHOP_SUBMIT_PAY } from '@/api'
import { getLan } from "@/locale"


export default {
	comments: {
		GlobalLoading
	},
	
  props: {
    paramsObj: { type: Object }
  },
	emits: ['on-confirm', 'on-open', 'on-close', 'on-success', 'on-error'],
  data() {
    return {
      webview: null,
      show: false,
      footerHeight: 0,
			loadingStatus: { show: false }
    }
  },
  methods: {
    open(data) {
      this.show = true;
      this.fetchPaymentInfo(data);
      // this.initWebViewBelowElement();
    },
    close() {
      this.webview.close();
      this.webview = null;
      this.show = false;
			uni.hideKeyboard();
			this.$emit('on-close');
    },
		
    getRequest(url) {
      let theRequest = new Object();
      let index = url.indexOf("?");
      if (index != -1) {
        let str = url.substring(index + 1);
        let strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
      }
      return theRequest;
    },
    
		async initWebViewBelowElement(eventData) {
      const res = await systemInfo();
      try {
        let wvPath = '/static/hybrid/html/card.html';
        let wv = plus.webview.create("", wvPath, {
          'uni-app': 'none',
          position: 'fixed',
          background: 'transparent',
          left: '24px',
          right: '24px',
          top: this.footerHeight - 24 + 28 + 'px',
          overflowY: 'auto',
        });
        wv.loadURL(wvPath);
        wv.overrideUrlLoading({ mode: 'reject' }, (e) => {
          let { str } = this.getRequest(e.url);
          str = unescape(str)
          return this.handleBack(str)
        });
				/* wv.evalJS(`
				window.dispatchEvent(new CustomEvent('appMessage', 
				{ detail: ${JSON.stringify({ type: 'lan', lan:getLan() })} }))`); */
        wv.evalJS(`
        window.dispatchEvent(new CustomEvent('appMessage', 
        { detail: ${JSON.stringify({ ...eventData, lan: getLan() })} }))`);
        this.$root.$scope.$getAppWebview().append(wv);
        this.webview = wv;
      } catch (error) {
        console.error(error);
      }
    },
		
    async fetchPaymentInfo(data) {
			this.loadingStatus.show = true
      let obj = data
      try {
        const res = await SHOP_SUBMIT_PAY({
          payType: 'airwallex',
          ...obj
        })
        const { id, client_secret } = res.data;
        let params = {}
        params.intent_id = id;
        params.client_secret = client_secret;
        this.initWebViewBelowElement({ type: 'pay', ...params })
      } catch (error) {
        console.error(error);
      } finally {
				this.loadingStatus.show = false
			}
    },
    
		handleBack(str) {
			const { status, res } = JSON.parse(str);
      switch (status) {
        case 'success':
          console.log('成功参数', JSON.stringify(res));
					if (res.status == "SUCCEEDED" || res.status == "succeeded") {
						this.$emit('on-success', res)
					}
					else {
						Toast(res.status)
					}
          break;
				case 'error':
					console.log('----- 提交失败 ----- ', JSON.stringify(res))
					Toast(res.message)
					break;
				case 'loading':
					let s = res.state == true || res.state == 'true' ? true : false
					this.loadingStatus.show = s
					if (s) {
						uni.showLoading({
							title: '',
							mask: true
						})
					}
					else {
						uni.hideLoading();
					}
					break;
        default:
          break;
      }
    }
  },
	
  async mounted() {
    const res = await systemInfo();
    this.footerHeight = res.windowHeight / 2;
    const _this = this;
    uni.onKeyboardHeightChange(res => {
      _this.webview.setStyle({
        top: _this.footerHeight - 24 + 28 - res.height + 'px'
      })
    })
  }
}
</script>
<style lang="less" scoped>
.wallet_app {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999999;
  background-color: rgba(0, 0, 0, .5);
  display: flex;
  align-items: flex-end;

  .wallet_footer {
    width: 100%;
    background-color: #fff;
    padding: 24px;
    border-radius: 10px 10px 0 0;

    .close {
      height: 28px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>