<!--新增委托-->
<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: []
      list: [
          // {"id":"1466279033363894272","userNo":"18268270336","userName":"18268270336","phone":"18268270336","tenantId":"1466279033363894272","tenantCode":"18268270336","tenantName":"18268270336","tenantPlat":"saas","globalUserId":"1466279033251729408"},
          // {"id":"1466279033363894274","userNo":"18268270336","userName":"18268270336","phone":"18268270336","tenantId":"1466279033363894274","tenantCode":"18268270336dtd","tenantName":"18268270336的团队","tenantPlat":"paas","globalUserId":"1466279033251729408"}
      ]
		};
	},
	created() {
	  uni.clearStorageSync();
    this.getTenanList();
	},
  mounted() {
  },
  methods: {
    getTenanList(){
      // #ifdef APP-PLUS
      // 向宿主App发送事件
      uni.sendNativeEvent('getTenantList', {}, ret => {
        this.list = JSON.parse(ret).filter((item) =>{
          return item.tenantPlat === 'saas'
        });
        if(this.list.length === 1){
          this.selectedIndex = 0;
          this.encryptToken();
        }
      })
      // #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',"iX8yRPFVwT9LtD7Y4J/1X9OZUVca8RandOim1vTKkt+UGhc9H7rWuNxCbjmAm5Ky2g/xWcC7fNzwpHxX/wG5moHPvT6yqWr5p0EHt63kuc/vAwlPUju5XpFlnY1sfIRwIakXu1pZH4VVPdpB6IHkAtWeoVQjo2cc32Yh16SEWn8=")
      this.login()
    },

    triggerSelectItem(item){
      this.selectedIndex = item;
    },
    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);
          uni.setStorageSync('assignType', data.identityType);
          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,
        }
      })
    },
    // 跳转到首页
    async toIndexPage(){
      await this.$store.dispatch("getCategoryList")
      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){
      let identityType = uni.getStorageSync("assignType");
      let type = identityType ? {identityType: identityType} : {};
      this.$http("auth.createTokenByApp" ,{
        ...data,
        ...type
      }).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>
