<template>
  <el-dialog title="提示" :visible.sync="dialogVisible" width="480px" :close-on-click-modal="false" append-to-body>
    <p>原拓扑图已存在新图,是否覆盖?</p>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { recoveryGraph, queryDraftsGraph } from "@/api/home"
import { mapState } from "vuex"
function changeArr(list, map) {
  for (let i = 0; i < list.length; i++) {
    const ele = list[i];
    if (ele.categoryList) {
      changeArr(ele.categoryList, map);
    }
    map[ele.code] = ele;
    delete map[ele.code].categoryList
  }
}
export default {
  data() {
    return {
      dialogVisible: false,
      data: {},
      codeToName: {}
    };
  },
  computed: {
    ...mapState(["categoryGraph"])
  },
  watch: {
    categoryGraph: {
      handler: function(v) {
        const temp = JSON.parse(JSON.stringify(v))
        changeArr(temp, this.codeToName)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    showDialog(data) {
      this.data = data;
      this.getDraftsGraph()
    },
    // 查询草稿箱当前拓扑图是否存在新图
    getDraftsGraph() {
      const pa = {
        filters: `state=1;graphId="${this.data.graphId}"`
      }
      queryDraftsGraph(pa).then(res => {
        if (res.content.length) {
          this.dialogVisible = true;
        } else {
          this.confirm()
        }
      })
    },
    // 确认恢复
    confirm() {
      const pa = {
        id: this.data.id,
        graphId: this.data.graphId
      }
      recoveryGraph(pa).then(res => {
        this.updateCall(res)
      })
    },
    // 恢复成功回调
    updateCall(res) {
      if (res.result == "success") {
        this.dialogVisible = false;
        this.$emit("recoverSuc");
        this.$message.success(`已恢复至${this.getCategoryName(this.data.categoryId) || ''}`);
      } else {
        this.$message(res.message)
      }
    },
    // 获取恢复的图的分类
    getCategoryName(id) {
      if (!this.codeToName[id].parentId) {
        return this.codeToName[id].name
      } else {
        return this.getCategoryName(this.codeToName[id].parentId) + '-' + this.codeToName[id].name
      }
    }
  }
};
</script>