<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>上传json文件，生成新的图表</span>
        <el-upload
          style="float: right; padding: 3px 0"
          class="upload-demo"
          action=""
          :before-upload="beforeUpload"
          :http-request="customUpload"
          multiple
          :file-list="fileList"
        >
          <el-button size="small" type="text">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传json文件</div>
        </el-upload>
      </div>
      <div id="creatNewChart"></div>
    </el-card>
  </div>
</template>

<script>
import Plotly from "plotly.js-dist";

export default {
  data() {
    return {
      fileList: [], // 保存上传的文件
      mergedData: [], // 合并后的图表数据
      mergedLayout: {}, // 合并后的布局数据
    };
  },
  methods: {
    // 文件类型检查
    beforeUpload(file) {
      const isJSON =
        file.type === "application/json" || file.name.endsWith(".json");
      if (!isJSON) {
        this.$message.error("只能上传 JSON 文件");
      }
      return isJSON;
    },
    // 自定义上传方法
    customUpload({ file }) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const jsonData = JSON.parse(e.target.result);
          this.mergeChartData(jsonData);
          this.generateChart();
        } catch (error) {
          this.$message.error("上传的文件不是有效的 JSON 格式");
        }
      };
      reader.readAsText(file); // 读取文件内容
    },
    // 合并图表数据
    mergeChartData(jsonData) {
      // 合并 data 部分
      this.mergedData = this.mergedData.concat(jsonData.data);

      // 合并 layout 部分，假设 layout 相同，否则需要根据需求处理
      if (Object.keys(this.mergedLayout).length === 0) {
        this.mergedLayout = jsonData.layout;
      }
    },
    // 生成图表
    generateChart() {
      const config = {
        displaylogo: false,
        editable: false,
        scrollZoom: true,
      };

      Plotly.newPlot(
        "creatNewChart",
        this.mergedData,
        this.mergedLayout,
        config
      );
    },
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}
</style>
