<template>
  <view class="container">
      <image class="banner" src="https://ttmini.oss-cn-shenzhen.aliyuncs.com/static_npm/bind-bg.jpg" mode="widthFix" />
      <view class="line-item">
        <label>代理商名称 :</label>
        <text>{{globalOptions.agent_name}}</text>
      </view>
      <view class="line-item">
       <label>代理商ID :</label>
        <text>{{globalOptions.agent_id}}</text>
      </view>
      <view class="line-item" v-if="nickName">
        <label>用户昵称 :</label>
        <text>{{nickName}}</text>
      </view>
      <view class="line-item" v-if="avatarUrl">
        <label>用户头像 :</label>
        <image :src="avatarUrl" mode="widthFix" />
      </view>
      <view class="setting-tips" v-if="!nickName">对不起,无法获取您的用户信息,无法进行绑定</view>

      <button class="btn setting" open-type="getUserInfo" @getuserinfo="openSetting" v-if="!nickName">用户信息授权</button>
      <button class="btn setting" @click="bindAgentBefore" v-else>确认绑定代理商</button>

      <!-- 抖音号列表 -->
      <view class="mask" v-if="dyVisible">
        <view class="dialog-warpper">
          <view class="title">请选择您当前账号</view>
          <view class="tips">如没有当前账号，需要您去易推系统绑定即可显示，选错账号数据记录将会混乱。</view>
          <scroll-view scroll-y class="tiktok-acconnt-list">
            <block v-for="item in dyList" :key="item.id">
              <view class="tiktok-acconnt" @click="selectTiktok(item)">
                <image class="account-heads" :src="item.info.avatar" mode="aspectFill" />
                <view class="acconnt-info">
                  <view class="text-ellipsis">{{item.info.nickname}}</view>
                  <!-- <view class="fans-number">粉丝：100</view> -->
                </view>
                <view class="acconnt-checkbox" :class="[{active:dy_id === item.id }]">
                  <image class="check" src="https://ttmini.oss-cn-shenzhen.aliyuncs.com/static_npm/check.svg" mode="aspectFill" />
                  <image class="checked" src="https://ttmini.oss-cn-shenzhen.aliyuncs.com/static_npm/checked.svg" mode="aspectFill" />
                </view>
              </view>
            </block>
          </scroll-view>
          <button :class="['tiktok-acconnt-btn',{disabled:!dy_id}]" @click="dyVisible = false">确认当前账号</button>
        </view>
      </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import { bindAgent,getMyTikTok } from '../../common/api'
export default {
  name: 'yt-bind-agent',
  props: {
    indexPath: {
      type: String,
      default: '/pages/index/index'
    },
  },
  data() { 
    return {
      avatarUrl:'',
      nickName:'',
      gender:'',
      dy_id:0,
      dyList:[],
      dyVisible:false,
      globalOptions:{}
    }
  },
  computed: {
    ...mapState('index',[
      'tid','openid','unionid', 'agent_id','spread_id','agent_name','dy_user_id','mid','systemInfo'
    ]),
    watchObj(){
      // 由于QQ小程序的watch和computed 比onLoad执行慢,所以通过监听此属性触发页面初始化,并将页面query参数传入
      const { globalOptions,openid } = this
      return { agent_id:globalOptions.agent_id,openid }
    },
    dyListLength(){
      return this.dyList.length
    }
  },
  watch: {
    watchObj:{
      handler(val){
        if(val.agent_id && val.openid){
          this.loginHandler();
        }
      },
      immediate:true
    }
  },
  mounted(){
    const routers = getCurrentPages()
    const query = routers[routers.length - 1].options
    this.globalOptions = query
  },
  methods: { 
    getMyTikTok(){
      // 获取我的抖音号
      // #ifdef MP-TOUTIAO
      if(this.systemInfo?.appName==='Toutiao'){
        return Promise.resolve()
      }else{
        return getMyTikTok({ agent_id:this.globalOptions.agent_id }).then(res => {
          if(res.data.length){
            this.dyList = res.data
            if(!this.dy_id){
              this.dyVisible = true
            }
          }
        })
      }
      // #endif
      // #ifndef MP-TOUTIAO
      return Promise.resolve()
      // #endif
    },
    loginHandler(){
    
      // 用户已绑定过抖音号,不进行重复绑定
      if(/\d+/.test(this.dy_user_id)) { 
        this.dy_id = this.dy_user_id 
      }
      // 如果小程序启动参数上带有dy_user_id,享有更高的优先级
      if(/\d+/.test(this.globalOptions.dy_user_id)){
        this.dy_id = this.globalOptions.dy_user_id
      }

      if(!this.agent_name){
        //  情况一：用户第一次来绑定代理商
        this.authorize().then(this.getMyTikTok)
      // eslint-disable-next-line
      }else if(this.agent_name && (this.globalOptions.agent_id == this.agent_id)){
        // 情况二: 用户二次扫描推广码,判断已经绑定过,更新代理商抖音号信息
        if(parseInt(this.globalOptions.agent_id) === this.agent_id){
          this.authorize().then(() => {
            this.getMyTikTok().then(() => {
              // eslint-disable-next-line
              const hasTiktok = this.dyList.findIndex(v => v.id == this.dy_id)
              if(hasTiktok !== -1 || !this.dyList.length){
                const params = {
                  tid: this.tid,
                  agent_id:this.globalOptions.agent_id,
                  openid: this.openid,
                  avatar_url: this.avatarUrl,
                  nickname: this.nickName,
                  type: 2,
                  // #ifdef MP-TOUTIAO
                  dy_user_id:this.systemInfo?.appName==='Toutiao'?-1:this.dy_id,
                  // #endif
                  mid:this.mid
                };
                if(this.unionid){params.unionid = this.unionid}
                bindAgent(params)
                this.reload(this.spread_id)
              }else{
                // #ifdef MP-TOUTIAO
                this.dy_id = 0
                this.dyVisible = true
                // #endif
              }
            })
          })
        }
      } else {
        // 情况三: 用户二次扫描推广码,但是推广码agent_id 与用户原来的agent_id 不相等
        uni.showModal({
          title: '提示',
          content: '此抖音号已绑定其他代理商，如有疑问请联系客服咨询！',
          showCancel:false
        })
      }
        
    },
    authorize() {
      const that = this;
      return new Promise(function(resolve,reject){
        const getUserInfo = function(){
          uni.getUserInfo({
            success(res) {
              if (res.errMsg === 'getUserInfo:ok') {
                that.avatarUrl = res.userInfo.avatarUrl;
                that.nickName = res.userInfo.nickName;
                that.gender = res.userInfo.gender;
                resolve(res.userInfo)
              }else{
                reject()
              }
            },
            fail(){
              reject()
            }
          });
        }
        uni.getSetting({
          success: (auth) => {
            if (!auth.authSetting['scope.userInfo']){
              uni.authorize({
                scope: 'scope.userInfo',
                success(auth) {
                  if (auth.data['scope.userInfo'] === 'ok') {
                    getUserInfo()
                  }
                },
                fail(){
                  reject()
                }
              });
            }else{
              getUserInfo()
            }
          },
          fail(){
            reject()
          } 
        })
      })
    },
    openSetting(e){
      const that = this;
      // #ifdef MP-TOUTIAO
      uni.openSetting().then(() => {
         uni.getUserInfo({
          success(res) {
            if (res.errMsg === 'getUserInfo:ok') {
              that.avatarUrl = res.userInfo.avatarUrl;
              that.nickName = res.userInfo.nickName;
              that.gender = res.userInfo.gender;
              that.loginHandler()
            }
          }
        });
      })
      // #endif
      // #ifndef MP-TOUTIAO
      const {userInfo} = e.detail
      if(userInfo){
        that.avatarUrl = userInfo.avatarUrl;
        that.nickName = userInfo.nickName;
        that.gender = userInfo.gender;
        that.loginHandler()
      }
      // #endif
    },
    reload(id){
      const router = getCurrentPages()
      const route = router[router.length - 1]
      uni.$yt.route({
        type:'reLaunch',
        url: route.options.callback || this.indexPath,
        params:{
          product_id:route.options.product_id,
          agent_id:this.globalOptions.agent_id,
          spread_id:id || this.spread_id
        }
      })
    },
    bindAgentBefore(){
      uni.showModal({
          title: '注意',
          content: '即将绑定此代理商，是否继续?',
          success: (res) => {
            if (res.confirm) {
              this.bindAgent();
            }
          }
        });
    },
    bindAgent(){
      const that = this;
      uni.showLoading({
        title: '处理中'
      });
      const params = {
        tid: this.tid,
        agent_id: this.globalOptions.agent_id,
        openid: this.openid,
        avatar_url: this.avatarUrl,
        nickname: this.nickName,
        // #ifdef MP-TOUTIAO
        dy_user_id:this.systemInfo?.appName==='Toutiao'?-1:this.dy_id,
        // #endif
        mid:this.mid
      };
      if(this.unionid){params.unionid = this.unionid}
      bindAgent(params)
        .then(res => {
          const { id } = res;
          if (id) {
            const obj = {
              agent_id: this.globalOptions.agent_id,
              spread_id: id,
              agent_name: this.globalOptions.agent_name,
              login_agent_id:this.globalOptions.agent_id
            }
            this.$store.commit('index/set_agent',obj);
            this.$emit('success',obj)
          }
          uni.showModal({
            title: '提示',
            content: '绑定代理商成功!',
            confirmText: '开始推广',
            showCancel: false,
            success(){
              that.reload(id)
            }
          });
        })
        .catch(e => {
          uni.hideLoading();
          uni.showModal({
            title: '提示',
            content: e.msg || '绑定失败!!!',
            showCancel: false
          });
        });
    },
    selectTiktok({ id }){
      this.dy_id = id
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  background-color: #ffffff;
  min-height: 100vh;
}

.banner{
  height: 200rpx;
  margin-bottom: 68rpx;
}
.line-item{
  display: flex;
  align-items: center;
  font-size: 32rpx;
  height: 80rpx;
  label{
    flex: 0 0 360rpx;
    padding-right: 40rpx;
    text-align: right;
    color: #444444;
    font-weight: bolder;
  }
  text{
    color: #444444;
  }
  image{
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
  }
}
.setting-tips{
  font-size: 28rpx;
  text-align: center;
  color: #666;
  padding: 20rpx 70rpx 30rpx;
}
.btn{
  color: #fff;
  background-color: #00CB6D;
  font-size: 36rpx;
  width:450rpx;
  height: 90rpx;
  line-height:90rpx;
  border-radius: 50rpx;
  display: block;
  margin: 40rpx auto 0;
}
.mask{
  background-color: rgba($color: #000000, $alpha:.7);
  position: fixed;
  left: 0;right: 0;
  top: 0;bottom: 0;
  z-index: 100;
  animation: fadein linear 300ms;
}
@keyframes fadein {
  from{
    opacity: 0;
  }
  to{
    opacity: 1;
  }
}
.dialog-warpper{
  background-color: #ffffff;
  border-radius:20rpx;
  width: 600rpx;
  height: 78vh;
  padding: 0 30rpx;
  margin: 11vh auto 0;
  .title{
    text-align: center;
    padding:40rpx 0 30rpx;
    font-size: 36rpx;
    line-height: 36rpx;
  }
  .tips{
    color: #F92359;
    font-size: 26rpx;
    text-align: justify;
    line-height: 36rpx;
  }
  
}
.tiktok-acconnt-list{
  height: calc( 78vh - 350rpx );
  padding: 24rpx 0;
}
.tiktok-acconnt{
    width: 100%;
    height:116rpx;
    display: flex;
    align-items: center;
    border-top:1px solid #EEEEEE;
    // border-bottom:1px solid #EEEEEE;

    .account-heads{
      flex: 0 0 68rpx;
      height: 68rpx;
      width: 68rpx;
      border-radius: 50%;
    }
    .acconnt-info{
      flex: 1 1 auto;
      min-width: 0;
      padding:0 20rpx 0 30rpx;
      .text-ellipsis{
        font-size: 30rpx;
        color: #2A2A2A;
      }
      .fans-number{
        color: #4D4C4D;
        font-size: 24rpx;
      }
    }
    .acconnt-checkbox{
      flex: 0 0 36rpx;
      height: 36rpx;
      width: 36rpx;
      image{
        display: block;
        height: 36rpx;
        width: 36rpx;
      }
      .checked{
        display: none;
      }
      &.active{
        .check{
          display: none;
        }
        .checked{
          display: block;
        }
      }
    }
  }
  .tiktok-acconnt-btn{
    background-color:#F92359;
    display: block;
    color: #ffffff;
    font-size: 30rpx;
    line-height: 78rpx;
    height: 78rpx;
    &.disabled{
      background-color:#CACDD4;
      pointer-events: none;
    }
  }
  .text-ellipsis {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
</style>
