<!--新增委托-->
<template>
	<view>
		<view id="header"><u-navbar :is-back="false" title="租户选择" :border-bottom="false" :background="{ backgroundColor: 'whitesmoke' }"></u-navbar></view>
		<!-- 列表 确定-->
		<view class="u-p-30 body" :style="{ bottom: footerHeight + 'px', top: headerHeight + 'px' }" v-if="list.length > 0">
			<view v-for="(item, index) in list" :key="item.id" class="u-flex u-m-b-20 s--item" @click="triggerSelectItem(index)">
				<view class="u-m-r-30">
					<u-icon :name="index === selectedIndex ? 'checkmark-circle-fill' : 'checkmark-circle'" color="#000" size="40"  />
				</view>
				<view :class="{ tenant_list: true, border_000: index === selectedIndex }">{{ item.userName }}</view>
			</view>
		</view>
    <view v-if="list.length === 0">
      <u-empty text="没有数据" mode="list"></u-empty>
    </view>
		<!-- 底部按钮 确定-->
		<view class="footer" id="footer">
			<view class="footer-btn">
				<!--        /* 以下形式在微信小程序会无效，APP和H5有效 */-->
				<u-button :disabled="selectedIndex === -1" @click="next" class="custom-style" shape="circle">确定</u-button>
				<!-- <u-button @click="testLogin" class="custom-style" shape="circle">确定</u-button> -->
			</view>
		</view>
	</view>
</template>

<script>
import dom from '@/mixins/dom';
export default {
	name: 'listSelectToAdd',
	mixins: [dom],
	data() {
		return {
      selectedIndex: -1,

      list: []
		};
	},
	created() {
    this.getTenanList();
	},
  mounted() {
  },
  methods: {
    getTenanList(){
      // #ifdef APP-PLUS
      // 向宿主App发送事件
      uni.sendNativeEvent('getTenantList', {}, ret => {
        this.list = JSON.parse(ret).filter((item) =>{
          return item.tenantPlat === 'saas'
        });
      })
      // #endif
    },
    encryptToken(){
      // #ifdef APP-PLUS
      const active = this.list[this.selectedIndex];
      uni.sendNativeEvent('encryptToken',JSON.stringify(
          {
            globalId: active.globalUserId,
            tenantId: active.tenantId,
            subId: active.id,
          }
      ), ret => {
        uni.setStorageSync('encryptToken', ret);
        this.login()
      })
      // #endif
    },

	  initEvent() {
      // #ifdef APP-PLUS
      uni.onNativeEventReceive((event, data)=>{
        this.err = JSON.stringify(event);
        this.err1 = true;
        if(event === 'getTenantList'){
          this.list = JSON.parse(data);
        }else if(event === 'encryptToken'){
          // this.token = data;
          uni.setStorageSync('encryptToken', data);
          this.login()
        }
      })
      this.getTenanList();
      // #endif
    },
    testLogin(){
      uni.setStorageSync('encryptToken',"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJ0ZW5hbnRfaWQiOiIwMDAwMDAiLCJyb2xlX25hbWUiOiJST0xFX0FETUlOIiwidXNlcl9pZCI6IjE0NzM1ODI0NDI5MTEwMjMxMDUiLCJyb2xlX2lkIjoiMTEyMzU5ODgxNjczODY3NTIwMSIsInVzZXJfbmFtZSI6IiIsIm9hdXRoX2lkIjoiIiwidG9rZW5fdHlwZSI6ImFjY2Vzc190b2tlbiIsImFjY291bnQiOiIiLCJjbGllbnRfaWQiOiJzd29yZCIsImV4cCI6MTY0MDIwMDQwNywibmJmIjoxNjQwMTY0NDA3fQ.b2lDYtf8huuxRSfp0YKAHXgcsx59AEo2omgrE8V1tJQNwFIOTD7GzS-iAbpCalj6QXqw-OnNP9HKbsBEuloAMA")// uni.setStorageSync("encryptToken","11")
      this.login()
    },

    triggerSelectItem(item){
      this.selectedIndex = item;
    },
    login(){
      // uni.showToast({
      //   title: "login"
      // })
      // 核对
      this.$http(
          "auth.checkSecretKey",
          uni.getStorageSync('encryptToken')
      ).then(res =>{
        let {
          code, data
        } = res;
        if(code === 200){
          let {
            userId,      // 用户id
            enterpriseId // 企业id
          } = data;
          this.userData = data;
          uni.setStorageSync('tenantId', data.tenantId);
          if(userId && enterpriseId){
            this.createToken(data);
          }else{
            this.toRegister();
          }
        }
      })
    },
    // 跳转到注册
    toRegister(){
      let {userId,enterpriseId,subId,tenantId} = this.userData;
      this.$Router.push({
        path: "/pages/user/register/stepSelectType",
        query:{
          pcUserId: userId || "",
          pcBasicsId: enterpriseId || "",
          tenantUserId:subId,
          tenantId,
        }
      })
    },
    // 跳转到首页
    toIndexPage(){
      this.$Router.push({
        path: "/pages/home/index"
      })
    },
    checkStatus(data){
      this.$http(
          "user.checkMagStatus",{
            pcUserId: data.userId,
            pcBasicsId: data.enterpriseId,
          }).then(res =>{
        let { code ,data} = res;
        if(code === 200){
          // 1-面料供应商, 2-品牌商, 3-设计机构, 4-检测机构
          let { identityType} = data.userLastIdentity;
          if(identityType){
            this.assignType = identityType;
            this.filterStatus(data)
          }
        }
      })
    },
    filterStatus(data){
      // 0-未完善 1-已完善
      let{
        isBrandOwner,   // 我要选款
        isDesignAgency, // 完善设计机构信息
        isFabricSupplier, //完善面料供应商信息
        isTestingFacility, // 完善检测机构信息
      } = data;
      let { assignType} = this;
      switch (assignType){
        case "1":
          isFabricSupplier  ? this.toIndexPage() : this.toRegister();
          return ;
        case "2":
          isBrandOwner  ? this.toIndexPage() : this.toRegister();
          return ;
        case "3":
          isDesignAgency   ? this.toIndexPage() : this.toRegister();
          return ;
        case "4":
          isTestingFacility ? this.toIndexPage() : this.toRegister();
          return ;
        default:
          this.toRegister();
          return;
      }
    },
    createToken(data){

      this.$http("auth.createTokenByApp" ,{
        ...data,
        ...{
          identityType: uni.getStorageSync("identityType")
        }
      }).then(res =>{
        let {
          code, data
        } = res;
        if(code === 200){
          uni.setStorageSync('token', data.accessToken);
          uni.setStorageSync('pcUserId', data.userId);
          uni.setStorageSync('pcBasicsId', data.enterpriseId);
          // uni.setStorageSync('tenantId', this.userData.tenantId);

          this.checkStatus(data);
        }
      })
    },
    next(){
      this.encryptToken();
    }
	}
};
</script>

<style scoped lang="scss">
$h-color: #af8d66;
$main-color: #fff;
.body {
	position: absolute;
	width: 100%;
	height: auto;
	left: 0;
	right: 0;
	bottom: 0;
	top: 0;
	overflow-y: auto;
}
.title {
	color: $h-color;
	background-color: whitesmoke;
}
.tenant_list {
	flex: 1;
	height: 160rpx;
	line-height: 160rpx;
	text-align: center;
	background: url(../../static/images/home/tenSelet@2x.png) no-repeat;
	background-size: 100% 100%;
	border-radius: 16rpx;
	border: 1px solid #979797;
}
.bg-fff {
	background: $main-color;
}
.item {
	border-radius: 8rpx;
	border: 1px solid #bd4848;
	height: 160rpx;
	width: 100%;
	overflow: hidden;
	background-size: contain;

	.active {
		border: 1px solid #000;
	}
}
.border_000 {
	border: 1px solid #000;
}
.custom-style {
	color: #fff;
	background: #000;
}
.footer {
	position: fixed;
	width: 100%;
	bottom: 0;

	z-index: 998;
	background: #fff;
	box-shadow: 0px -4rpx 6rpx 0px rgba(178, 182, 214, 0.1);
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
	.footer-btn {
		padding: 20rpx 30rpx;
	}
}
</style>
