<template>
  <view class="upload">
    <u-icon
      name="plus"
      size="24px"
      class="flex justify-center w-12 h-12 bg-blue-100 rounded-full shadow-md"
      @click="handleUpload"
    ></u-icon>
  </view>
</template>

<script setup>
  import { computed, ref } from 'vue';
  import { useStore } from 'vuex';
  import Config from '@/common/js/config.js';

  const store = useStore();
  const list = ref([]);
  const emit = defineEmits(['success', 'error']);
  const user = computed(() => store.state.user.user);
  const userJson = uni.$storage.getStorageSync('user');

  if (userJson) {
    const user = JSON.parse(userJson);
    store.commit('user/setUser', user);
  }

  getList();

  // 导入wbs
  const handleUpload = async cur => {
    // #ifdef APP-PLUS
    uni.$ui.showToast('APP暂不支持导入');
    // #endif

    // #ifndef APP-PLUS
    if (list.value.length === 1) {
      store.commit('setDomain', list.value[0].url);

      uni.showModal({
        content: '是否上传到' + list.value[0].name,
        showCancel: true,
        success: async ({ confirm }) => {
          if (confirm) {
            try {
              const res = await uni.$u.api.import();
              // 导入WBS成功后
              // 直接打开导入的项目
              emit('success');
              const { apiUrl } = Config;
              const defaultwbs = `${apiUrl}/defaultwbs`;
              res.url && (defaultwbs = res.url);
              setTimeout(() => {
                uni.navigateTo({ url: `/pages/project/project?u=${user.value.id}&p=${res.id}&pname=${res.name}&url=${encodeURIComponent(res.url)}` });
              }, 2000);
            } catch (error) {
              console.error('error: ', error);
              emit('error', error);
            }
          }
        },
      });
    } else {
      uni.navigateTo({
        url: '/pages/business/business'
      })
    }
    // #endif
  };

  async function getList() {
    try {
      const res = await uni.$u.api.getBusinessList();
      list.value = res;
    } catch (error) {
      console.error('error: ', error);
    }
  }
</script>

<style lang="scss" scoped>
  .upload {
    position: absolute;
    right: 10px;
    bottom: 0;
    transform: translate3d(0, 50%, 0);
    color: $uni-color-primary !important;
  }
</style>
