<template>
  <div class="changeChain">
    <van-nav-bar class="navBar" title="切换经销商" left-arrow @click-left="onClickLeft" />
    <div class="content">
      <div class="module">
        <div
          class="box"
          v-if="userInfo && userInfo.userMultipleChains && userInfo.userMultipleChains.length > 0">
          <van-radio-group v-model="selectedChainIndex" @change="chainChange">
            <van-radio
              v-for="(value, index) in userInfo.userMultipleChains"
              :key="`${value.chainCode}-${index}`"
              :name="index">
              {{ value.chainName }}
            </van-radio>
          </van-radio-group>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import { switchChainIdentity } from '@/api/week';
import store from '@/store';
export default {
  name: 'changeChain',
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  data() {
    return {
      selectedChainIndex: null,
    };
  },
  watch: {
    'userInfo.userMultipleChains'(val) {
      this.initSelectedChain(val);
    },
  },
  created() {
    this.initSelectedChain(this.userInfo && this.userInfo.userMultipleChains);
  },
  methods: {
    initSelectedChain(val) {
      if (val && val.length > 0) {
        const currentIndex = val.findIndex((item) => item.check);
        this.selectedChainIndex = currentIndex >= 0 ? currentIndex : 0;
      }
    },
    chainChange(index) {
      const chain = this.userInfo.userMultipleChains[index];
      if (!chain) {
        return;
      }
      this.toastLoading(0, '切换中，请稍候...', true);
      switchChainIdentity({ userMultipleChainId: chain.multipleChainId }).then((res) => {
        this.toastLoading().clear();
        if (res.code === 200) {
          store.dispatch('getUserInfo').then(() => {
            this.$toast('切换成功');
          });
        } else {
          this.$toast(res.message || '切换失败');
        }
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>
<style lang="scss" scoped>
.changeChain {
  width: 100%;
  height: 100%;
  .content {
    margin: 10px 16px;
    .module {
      margin-bottom: 10px;
      .title {
        font-size: 16px;
        padding: 10px 0;
      }
      .box {
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px;
        font-size: 16px;
        .van-radio {
          padding: 8px 0;
        }
      }
    }
  }
}
</style>
