<template>

  <el-upload
      class="upload-demo"
      drag
      action=""
      :on-change="handleChange"
      :auto-upload="false"
      :limit="1"
      multiple>
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <div class="el-upload__tip" slot="tip">只能上传html文件</div>
  </el-upload>
</template>
<script>
import {parseByString } from "bookmark-file-parser"
import axios from "axios";
import Vue from "vue";
export default {
  name: "Import",
  data() {
    return {}
  },
  mounted() {

  },
  created() {

  },
  computed: {},
  methods: {
    handleChange(file) {
      let _this=this;
      let reader = new FileReader();   //先new 一个读文件的对象 FileReader
      if (typeof FileReader === "undefined") {  //用来判断你的浏览器是否支持 FileReader
        this.$message({
          type: "info",
          message: "您的浏览器不支持文件读取。"
        });
        return;
      }
      //  reader.readAsText(file.raw, "gb2312");  //读.txt文件
      reader.readAsArrayBuffer(file.raw); //读任意文件
      reader.onload = function (e) {
        var ints = new Uint8Array(e.target.result); //要使用读取的内容，所以将读取内容转化成Uint8Array
        // ints = ints.slice(0, 5000); //截取一段读取的内容
        // let snippets = new TextDecoder('gb2312').decode(ints); //二进制缓存区内容转化成中文（即也就是读取到的内容）
        let snippets = new TextDecoder('utf-8').decode(ints); //二进制缓存区内容转化成中文（即也就是读取到的内容）
        // console.log("读取的内容如下：");
        if(snippets){
          _this.disposeJson(parseByString(snippets));
        }


      };
    },
    disposeJson(json) {
      let _this = this;
      if (localStorage.getItem('userId')) {
        axios({
          method: 'post',
          url: '/api/UrlAndCate/disposeJson',
          params: {
            userId:localStorage.getItem('userId'),
          },
          data:json
        }).then(function (res) {
          if(res.data.code!==200){
            Vue.prototype.$notify.error({
              title: '错误',
              message: "插入失败！",
              offset: 0
            });
          }else {
            Vue.prototype.$notify({
              title: '成功',
              message: ('i', {style: 'color: teal'}, "插入成功！"),
              type: 'success',
              offset: 0
            });
          }

        }).catch((error) => {
          Vue.prototype.$notify.error({
            title: '错误',
            message: error,
            offset: 0
          });
        })

      } else {
        Vue.prototype.$notify.error({
          title: '错误',
          message: '登录状态失效，请重新登录！',
          offset: 0
        });
      }

    },
  }

}
</script>
<style scoped>
.el-upload__tip {
  color: var(--theme-color);
}


</style>