<template>
  <el-dialog
    :title="'数据输入'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="160px"
    >
      <el-form-item label="静态数据集文件" prop="st_dataListurl">
        <el-select v-model="st_dataListvalue" multiple placeholder="请选择">
          <el-option
            v-for="item in st_dataList"
            :key="item.datasetName"
            :label="item.datasetName"
            :value="item.datasetName"
          >
          </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="#"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="10"
          :on-exceed="handleExceed"
          :on-change="fileChange"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>

      <!-- <el-form-item label="形式">
          <el-select v-model="dataForm.form" placeholder="选择算法形式">
            <el-option v-for="data in forms" :key="data.value" :label="data.label" :value="data.value">
            </el-option>
          </el-select>
      </el-form-item>

      <el-form-item label="描述信息" prop="remark">
        <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="请输入内容" v-model="dataForm.remark">
        </el-input>

      </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 { MessageBox } from 'element-ui'
import { Message } from "element-ui"
export default {
  data() {
    return {
      visible: false,
      // 获取所有类别列表
      categoryList: [],
      dataForm: {
        id: 0,
        modelName: "",
        // 本模板的类别
        categoryId: 1,
        form: null,
        remark: "",
        datasetName: "",
        st_dataListurl: [{ datasetName: "" }],
        dy_dataListurl: [{ datasetName: "" }],
      },
      textarea2: "",

      forms: [
        {
          label: "传统算法",
          value: 1,
        },
        {
          label: "智能算法",
          value: 2,
        },
      ],
      dataRule: {
        modelName: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        // email: [
        //   { required: true, message: "邮箱不能为空", trigger: "blur" },
        //   { validator: validateEmail, trigger: "blur" },
        // ],
        // mobile: [
        //   { required: true, message: "手机号不能为空", trigger: "blur" },
        //   { validator: validateMobile, trigger: "blur" },
        // ],
        // codes: [
        //   { required: true, message: "代码文件不能为空", trigger: "blur" },
        // ],
      },

      // 数据集文件选择
      st_dataList: [{ datasetName: "" }],
      dy_dataList: [{ datasetName: "" }],

      //选择器 值
      st_dataListvalue: [],
      dy_dataListvalue: [],

      //  包含文件名与url
      st_dataListmap: [],
      dy_dataListmap: [],
      externalfilemap: [], //外部上传文件最终   包含文件名和url

      //外部文件  上传
      fileList: [],

      //包含所有文件
      allfilemap: [{},],
      cell: null,

      pageIndex: 1,
      pageSize: 100,
      st_totalPage: 0,
      dy_totalPage: 0,
      datasetName: "",
    };
  },
  methods: {
    init(cell) {
      this.visible = true;

      this.$http({
        url: this.$http.adornUrl("/dataset/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          datasetName: this.datasetName,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.st_dataList = data.page.list;
          this.st_totalPage = data.page.totalCount;
          // this.statusunique = this.unique(data.page.list);
        } else {
          this.st_dataList = [];
          this.totalPage = 0;
        }
        // this.dataListLoading = false;
      });

      this.$http({
        url: this.$http.adornUrl("/datasetdy/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          datasetName: this.datasetName,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dy_dataList = data.page.list;
          this.dy_totalPage = data.page.totalCount;
          // this.statusunique = this.unique(data.page.list);
        } else {
          this.dy_dataList = [];
          this.totalPage = 0;
        }
        // this.dataListLoading = false;
      });
      this.cell = cell;
      this.st_dataListvalue = cell.getData().st_dataListvalue;
      this.dy_dataListvalue = cell.getData().dy_dataListvalue;
      this.fileList = cell.getData().fileList;
      this.allfilemap = cell.getData().allfilemap;
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          //处理选择的 静态数据集或者动态数据集

          console.log(this.st_dataListvalue);
          console.log(this.dy_dataListvalue);
          this.st_dataListmap = [];
          this.dy_dataListmap = [];
          this.externalfilemap = [];
          this.allfilemap = [];
          // for (itemname of this.st_dataListvalue)
          for (var i = 0; i < this.st_dataListvalue.length; i++) {
            const stdatasetname = this.st_dataListvalue[i];
            this.$http({
              url: this.$http.adornUrl("/dataset/downloadDataset"),
              method: "get",
              params: this.$http.adornParams({
                datasetName: this.st_dataListvalue[i] + ".csv",
              }),
            }).then(({ data }) => {
              if (data && data.code === 0) {
                // window.location.href = data.downloadUrl;
                var fileitem = {};
                fileitem["name"] = stdatasetname;
                fileitem["fileurl"] = data.downloadUrl;

                this.st_dataListmap.push(fileitem);
                this.allfilemap.push(fileitem);
                // celldata.allfilemap = this.allfilemap;
              } else {
                // this.$message.error("下载失败");
              }
            });
          }

          for (var j = 0; j < this.dy_dataListvalue.length; j++) {
            const dydatasetname = this.dy_dataListvalue[j];
            this.$http({
              url: this.$http.adornUrl("/dataset/downloadDataset"),
              method: "get",
              params: this.$http.adornParams({
                datasetName: this.dy_dataListvalue[j] + ".csv",
              }),
            }).then(({ data }) => {
              if (data && data.code === 0) {
                // window.location.href = data.downloadUrl;
                var fileitem = {};
                fileitem["name"] = dydatasetname;
                fileitem["fileurl"] = data.downloadUrl;

                this.dy_dataListmap.push(fileitem);
                this.allfilemap.push(fileitem);
                // celldata.allfilemap = this.allfilemap;
              } else {
                // this.$message.error("下载失败");
              }
            });
          }
          //处理外部上传的数据
          let formData = new FormData();
          this.fileList.forEach((file) => {
            formData.append("file", file.raw);
          });

          if (formData != null) {
            var jsonfileurl = {};
            this.$http({
              url: this.$http.adornUrl("/visi/visiworkflow/saveinputfile"),
              method: "post",
              data: formData,
            }).then(({ data }) => {
              if (data && data.code === 0) {
                jsonfileurl = data.jsonfileurl;
                // myJson = { name: "phpernote", password: "1111" };
                for (var val in jsonfileurl) {
                  // alert(val + " " + myJson[val]); //输出如:name
                  var fileitem = {};
                  fileitem["name"] = val;
                  fileitem["fileurl"] = jsonfileurl[val];
                  this.externalfilemap.push(fileitem);
                  this.allfilemap.push(fileitem);
                  // celldata.allfilemap = this.allfilemap;
                }

                console.log();
              } else {
                this.$message.error(data.msg);
              }
            });
            // .then(({ data }) => {
            //   if (data && data.code === 0) {
            //     this.$message({
            //       message: "操作成功",
            //       type: "success",
            //       duration: 1500,
            //       onClose: () => {
            //         this.visible = false;
            //         // this.$emit("refreshDataList");
            //         console.log("filemap");
            //         console.log(this.st_dataListmap);
            //         console.log(this.dy_dataListmap);
            //         console.log(this.externalfilemap)
            //         console.log(this.allfilemap);
            //       },
            //     });
            //   } else {
            //     this.$message.error(data.msg);
            //   }
            // });
          }

          this.visible = false;
          // this.$emit("refreshDataList");
          // console.log("filemap");
          // console.log(this.st_dataListmap);
          // console.log(this.dy_dataListmap);
          // console.log(this.externalfilemap);
          // console.log(this.allfilemap);
          var celldata = this.cell.getData();
          celldata.st_dataListvalue = this.st_dataListvalue;
          celldata.dy_dataListvalue = this.dy_dataListvalue;
          celldata.fileList = this.fileList;
          celldata.allfilemap = this.allfilemap;
          // this.$emit("refreshinputnode",this.cell,this.st_dataListvalue,this.dy_dataListvalue,this.fileList,this.allfilemap);
          this.$emit("refreshinputnode",this.cell,celldata);
        }
      });
    },
    // 以下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 = fileList;
      this.fileList.append(file);
    },
  },
};
</script>
<style>
.el-form-item .el-select {
  width: 100%;
}
.el-form-item .el-input {
  width: 100%;
}
</style>
