<template>
  <view>
    <view @click="handleUpload" v-if="task.name === '导入WBS新建项目'">{{ task.name }}</view>
    <view @click="handleUpdate" v-if="task.name === '导入WBS更新项目'">{{ task.name }}</view>
    <!-- 全局提示框 -->
    <u-top-tips ref="uTips"></u-top-tips>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useStore } from 'vuex';

defineProps({ task: { type: Object, default: () => {} } });

const store = useStore();
const userId = computed(() => store.state.user.userId);
const projectId = computed(() => store.getters['project/projectId']);
const uTips = ref(null);

// 导入成功
function onUploadSuccess() {
  uTips.show({
    title: '导入成功，即将打开新项目',
    type: 'success',
    duration: '3000',
  });
}

// 导入失败
function onUploadError(error) {
  uTips.show({
    title: error || '导入失败',
    type: 'error',
    duration: '6000',
  });
}

// 更新项目
// TODO: 更新接口没写完
async function handleUpdate() {
  try {
    await uni.$u.api.import({ projectId: projectId.value });
    // 导入WBS成功后
    // 直接打开导入的项目
    onUploadSuccess();
  } catch (error) {
    onUploadError(error);
  }
}

// 导入wbs
async function handleUpload() {
  try {
    const res = await uni.$u.api.import();
    // 导入WBS成功后
    // 直接打开导入的项目
    onUploadSuccess();
    setTimeout(() => {
      uni.$u.route('/pages/project/project', {
        u: userId.value,
        p: res.id,
        pname: res.pname,
        url: res.url,
      });
    }, 2000);
  } catch (error) {
    onUploadError(error);
  }
}
</script>
