<template>
  <div class="page" v-loading.body.fullscreen="fullscreenLoading" element-loading-background="rgba(255, 255, 255, 0)">
    <backBar1 :title="title[id]" />
    <iframe ref="iframe" @load="onIframeLoad" v-if="iframeUrl" class="iframe" :class="{protocol:sign && !protocol}" :src="`${iframeUrl}?${random}`" frameborder="0"></iframe>
    <template v-if="sign && !protocol">
      <div class="fixed" v-if="id == 'legal' || id == 'risk'">
        <div class="btn flex" :class="{loaded: loaded}" @click="updateUserTradeProtocol">
          <div>
            <!-- 阅读完毕 -->
            {{ $t('statement.l13') }}
          </div>
        </div>
      </div>
      <div class="fixed" v-if="id == 'user' || id == 'tradeconfirm'">
        <div class="btn flex" :class="{loaded: loaded}" @click="signaturePopShow">
          <div>
            <!-- 点击签名同意 -->
            {{ $t('statement.l14') }}
          </div>
        </div>
      </div>
    </template>
    <van-popup overlay-class="overlay1" v-model="signaturePop" round position="bottom">
      <signature @cancel="signaturePop = false" @submit="updateUserTradeProtocol" v-if="signaturePop"/>
    </van-popup>
  </div>
</template>
<script>
import signature from "./components/signature.vue";
import backBar1 from "@/components/backBar1";
import { mapGetters } from 'vuex'
import { updateUserTradeProtocol } from "@/api/user";
export default {
  components: {
    backBar1,
    signature
  },
  data () {
    return {
      content: '',
      random: (Math.random() * 100000).toFixed(0),
      id: '',
      sign: '',
      protocol: 0,
      loaded: false,
      signaturePop: false,
      timerOut: null,
      trade_protocol: [],
      title: {
        // 'user': '用户协议',
        // 'riskwarning': '风险提示',
        // 'privacy': '隐私条款',
        // 'coupon': '声明',
        // '1': 'AML/KYC 政策',
        // 'followUser': '极度跟单协议',
        // 'followExpert': '交易专家协议',
        // 'followLevel': '等级细则',
        'followUser': this.$t('follow.l142'),
        'followExpert': this.$t('follow.l88'),
        'followLevel': this.$t('follow.l89'),
        // 'legal': '法律声明',
        // 'risk': '风险披露',
        // 'tradeconfirm': '交易确认书',
        'user': this.$t('auth.l28'),
        'riskwarning': this.$t('product.l131'),
        'privacy': this.$t('common.l56'),
        'coupon': this.$t('share.l11'),
        '1': this.$t('auth.l35'),
        'legal': this.$t('auth.l25'),
        'risk': this.$t('auth.l26'),
        'tradeconfirm': this.$t('statement.l12'),
      }
    }
  },
  computed: {
    ...mapGetters(['iframeUrlObj']),
    iframeUrl() {
      var url = {
        'user': 'user',
        'riskwarning': 'riskwarning',
        'privacy': 'privacy',
        'coupon': 'coupon',
        '1': 'kyc',
        'followUser': 'followUser',
        'followExpert': 'followExpert',
        'followLevel': 'followLevel',
        'legal': 'legal',
        'risk': 'risk',
        'tradeconfirm': 'tradeconfirm'
      }
      return (this.iframeUrlObj && (this.iframeUrlObj[url[this.id]][this.language] || this.iframeUrlObj[url[this.id]]['en'] ))
    }
  },
  beforeDestroy() {
    (this.timerOut && clearTimeout(this.timerOut))
  },
  created () {
    if (this.$route.params.id) {
      this.id = this.$route.params.id
      if (!this.iframeUrlObj) {
        this.$store.dispatch('getIframeUrl')
      }
    }
    if (this.$route.params.sign && this.isLogin) {
      this.sign = this.$route.params.sign
      sessionStorage.setItem('serviceTipsPop', JSON.stringify(true))
      this.$store.dispatch('getUserInfo').then(() => {
      }).finally(() => {
        var trade_protocol = this.userInfo.trade_protocol ? JSON.parse(this.userInfo.trade_protocol) : [];
        this.trade_protocol = trade_protocol
        trade_protocol.forEach(item => {
          if (item.code == this.id && item.status == 1) {
            this.protocol = 1
          }
        })
      })
    }
  },
  methods: {
    updateUserTradeProtocol() {
      if (!this.loaded) {
        return
      }
      var obj = {
        user: {
          code: 'user',
          client: 'H5',
          status: 0
        },
        tradeconfirm: {
          code: 'tradeconfirm',
          client: 'H5',
          status: 0
        },
        risk: {
          code: 'risk',
          client: 'H5',
          status: 0
        },
        legal: {
          code: 'legal',
          client: 'H5',
          status: 0
        }
      }
      this.trade_protocol.forEach(item => {
        obj[item.code] = item
      })
      obj[this.id].status = 1
      var data = [];
      Object.keys(obj).forEach(item => {
        data.push(obj[item])
      })
      this.fullscreenLoading = true
      updateUserTradeProtocol({
        protocol: JSON.stringify(data)
      }).then(() => {
        this.signaturePop = false
        this.$router.back()        
      }).catch(() => {}).finally(() => {
        this.fullscreenLoading = false
      })
    },
    signaturePopShow() {
      if (!this.loaded) {
        return
      }
      this.signaturePop = true
    },
    onIframeLoad() {
      if (!this.sign || !this.isLogin) {
        return
      }
      var time = {
        user: 12,
        tradeconfirm: 9,
        risk: 6,
        legal: 3,
      }
      this.timerOut = setTimeout(() => {
        this.loaded = true
      }, time[this.id] * 1000)
      return
      var iframe = this.$refs.iframe;
      var iframeWindow = iframe.contentWindow || iframe.contentDocument.parentWindow;
      if (iframeWindow.document.readyState === 'complete') {
        var iframeBody = iframeWindow.document.body;
        var height = iframeBody.scrollHeight;
        console.log('Iframe height:', height);
      }
    },
  }
}
</script>
<style lang="less" scoped>
.iframe {
  position: fixed;
  top: 50px;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100%;
  height: calc(100% - 50px);
  &.protocol {
    height: calc(100% - 125px);
  }
}
.fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 2;
  background-color: #fff;
  padding: 10px 14px;
  .btn {
    justify-content: center;
    height: 50px;
    padding: 0 10px;
    font-weight: 600;
    font-size: 16px;
    cursor: not-allowed;
    background-color: #F6F6F6;
    color: #B6B6B6;
    &.loaded {
      background-color: #000000;
      cursor: pointer;
      color: #FFFFFF;
    }
  }
}
::v-deep {
  .overlay1 {
    background-color: transparent;
  }
}
::v-deep .content {
  word-break: break-all;
  P {
    font-size: 14px;
    color: #3D3C3C;
    line-height: 24px;
    margin-bottom: 10px;
    border-radius: 8px;
    border: 1px solid #F1F1F1;
    padding: 17px 14px;
  }
  img {
    max-width: 100%;
    height: auto !important;
  }
  h1 {
    padding: 10px 0;
    line-height: 1.2em;
  }
}
</style>