<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>
import { mapGetters, mapMutations } from 'vuex';

export default {
  name: 'p-wbs-import',
  props: {
    task: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {};
  },

  computed: {
    ...mapGetters('user', ['userId']),
    ...mapGetters('project', ['projectId']),
  },

  methods: {
    ...mapMutations('project', ['setShowAlert']),

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

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

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

    // 导入失败
    onUploadError(error) {
      this.$refs.uTips.show({
        title: error || '导入失败',
        type: 'error',
        duration: '6000',
      });
    },
  },
};
</script>
