<template>
  <el-dialog :title="'数据输入'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form label-width="160px">
      <el-form-item label="静态数据集文件" prop="st_dataListurl">
        <el-select value-key="datasetName" v-model="st_dataListvalue" multiple placeholder="请选择">
          <el-option
            v-for="item in st_dataList"
            :key="item.datasetName"
            :label="item.datasetName"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="动态数据集文件" prop="dy_dataListurl">
        <!-- 选择  dataset -->
        <el-select v-model="dy_dataListvalue" multiple placeholder="请选择">
          <el-option
            v-for="item in dy_dataList"
            :key="item.datasetName"
            :label="item.datasetName"
            :value="item.datasetName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件" size="mini">
        <el-upload
          class="upload-demo"
          action="#"
          multiple
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :limit="10"
          :on-exceed="handleExceed"
          :on-change="fileChange"
          :file-list="fileList"
          :auto-upload="false"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { Message, MessageBox } from "element-ui";
export default {
  data() {
    return {
      visible: false,
      // 数据集文件选择
      st_dataList: [],
      dy_dataList: [],
      // 选择器的值
      st_dataListvalue: [],
      dy_dataListvalue: [],
      // 包含文件名与url
      st_dataListmap: [],
      dy_dataListmap: [],
      // 外部上传文件最终包含文件名和url
      externalfilemap: [],
      // 外部文件上传
      fileList: [],
      // 包含所有文件
      allfilemap: [],
      cell: null,
      // 用户编号
      userID: this.$store.state.user.id,
      // 类型
      category: {}
    };
  },
  methods: {
    async init(cell) {
      this.visible = true;
      this.cell = cell;
      this.st_dataListvalue = this.cell.getData().st_dataListvalue || [];
      this.dy_dataListvalue = this.cell.getData().dy_dataListvalue || [];
      this.fileList = this.cell.getData().fileList || [];
      this.allfilemap = this.cell.getData().allfilemap || [];
      this.fileList[0];


      var link = document.createElement("a");
      link.download = this.fileList[0].name;
      link.href = window.URL.createObjectURL(this.fileList[0].raw);
      link.click();
      window.URL.revokeObjectURL(link.href);


      const { data } = await this.$http({
        url: this.$http.adornUrl("/dataset/listAll"),
        method: "get"
      });
      this.st_dataList = data.list;
      const {
        data: { list }
      } = await this.$http({
        url: this.$http.adornUrl("/datasetdy/listAll"),
        method: "get"
      });
      this.dy_dataList = list;

      const res = await this.$http({
        url: this.$http.adornUrl("/category/select"),
        method: "get"
      });
      res.data.list.forEach((item) => {
        this.category[item.categoryId] = item.categoryName;
      });
    },
    // 表单提交
    async dataFormSubmit() {
      // 处理选择的 静态数据集或者动态数据集
      this.st_dataListmap = [];
      this.dy_dataListmap = [];
      this.externalfilemap = [];
      this.allfilemap = [];

      for (let item of this.st_dataListvalue) {
        const categoryName = this.category[item.categoryId];
        const { data } = await this.$http({
          url: this.$http.adornUrl("/dataset/downloadDataset"),
          method: "get",
          params: this.$http.adornParams({
            datasetName: categoryName.includes("文件") ? item.datasetName : item.datasetName + ".csv",
            categoryName
          })
        });
        if (data && data.code === 0 && data.downloadUrl) {
          let fileitem = {};
          fileitem["name"] = item.datasetName;
          fileitem["bucketname"] = "dataset";
          fileitem["fileurl"] = data.downloadUrl;
          this.st_dataListmap.push(fileitem);
          this.allfilemap.push(fileitem);
        }
      }

      for (let item of this.dy_dataListvalue) {
        const { data } = await this.$http({
          url: this.$http.adornUrl("/dataset/downloadDataset"),
          method: "get",
          params: this.$http.adornParams({
            datasetName: item + ".csv"
          })
        });
        if (data && data.code === 0) {
          let fileitem = {};
          fileitem["name"] = dydatasetname;
          fileitem["bucketname"] = "dydataset";
          fileitem["fileurl"] = data.downloadUrl;
          this.dy_dataListmap.push(fileitem);
          this.allfilemap.push(fileitem);
        }
      }
      // 处理外部上传的数据
      if (this.fileList.length > 0) {
        let formData = new FormData();
        this.fileList.forEach((file) => {
          formData.append("file", file.raw);
        });
        const { data } = await this.$http({
          url: this.$http.adornUrl("/visi/visiworkflow/saveinputfile"),
          method: "post",
          data: formData
        });
        if (data && data.code === 0) {
          let jsonfileurl = data.jsonfileurl;
          for (let val in jsonfileurl) {
            let fileitem = {};
            fileitem["name"] = val;
            fileitem["bucketname"] = "visiarguartifact";
            fileitem["fileurl"] = jsonfileurl[val];
            this.externalfilemap.push(fileitem);
            this.allfilemap.push(fileitem);
          }
        }
      }
      this.cell.setData({
        st_dataListvalue: this.st_dataListvalue,
        dy_dataListvalue: this.dy_dataListvalue,
        fileList: this.fileList,
        allfilemap: this.allfilemap
      });
      this.visible = false;
      Message.success("保存成功");
    },
    // 以下4个函数是文件上传功能的
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return MessageBox.confirm(`确定移除 ${file.name}？`);
    },
    // 文件改变时
    fileChange(file, fileList) {
      this.fileList.push(file);
    }
  }
};
</script>
