<!--  -->
<template>
  <div class=''>
    <el-breadcrumb class="divi2" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/alg-algs'}">算法管理</el-breadcrumb-item>
      <el-breadcrumb-item>新建传统算法</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider class="divi"></el-divider>

    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="180px">
      <el-form-item label="传统算法名称" prop="algorithmName">
        <el-input v-model="dataForm.algorithmName" placeholder="请输入传统算法名称"></el-input>
      </el-form-item>
      <el-form-item label="类别" size="mini" prop="categoryId">
        <el-radio-group v-model="dataForm.categoryId">
          <el-radio v-for="category in categoryList" :key="category.categoryId" :label="category.categoryId">
            {{ category.categoryName }}
          </el-radio>
        </el-radio-group>
      </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>
          <div slot="tip" class="el-upload__tip">请上传代码文件</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="选择数据集：">
        <el-select v-model="datasetSelected" multiple placeholder="选择数据集">
          <el-option v-for="item in datasetOptions" :key="item.filename" :label="item.filename" :value="item.filename">
          </el-option>
        </el-select>
      </el-form-item>
      

      <!-- 算法参数设置 -->
      <el-form-item
        v-for="(algParameter, index) in dataForm.algParameters"
        :label="'输入参数' + (index+1)"
        :key="algParameter.key"
        :prop="'algParameters.' + index + '.value'"
      >
        <el-input v-model="algParameter.label" placeholder="请输入参数名"></el-input>
        <el-select v-model="algParameter.type" placeholder="请选择参数类别">
          <el-option
            v-for="item in algParameterOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button @click.prevent="removealgParameter(algParameter)">删除</el-button>
      </el-form-item>
      <el-form-item>
         <el-button @click="addalgParameter">新增输入参数</el-button>
      </el-form-item>

      <!-- 算法输出结果 -->
      <el-form-item
        v-for="(algResult, index) in dataForm.algResults"
        :label="'输出结果' + (index+1)"
        :key="algResult.key"
        :prop="'algResults.' + index + '.value'"
      >
        <el-input v-model="algResult.label" placeholder="请输入算法结果名"></el-input>
        <el-input v-model="algResult.value" placeholder="请输入算法结果文件名"></el-input>
        <!-- <el-select v-model="algResult.type" placeholder="请选择算法结果类别">
          <el-option
            v-for="item in algResultOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select> -->
        <el-button @click.prevent="removealgResult(algResult)">删除</el-button>
      </el-form-item>
      <el-form-item>
         <el-button @click="addalgResult">新增算法输出</el-button>
      </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-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item style="float:right">
        <el-button @click="visible = false;redirectHandle()">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { MessageBox } from 'element-ui'
import { Message } from "element-ui"
export default {
  created() {
    this.init();
  },
  data() {
    return {
      visible: false,
      // 获取所有类别列表
      categoryList: [],
      dataForm: {
        id: 0,
        algorithmName: "",
        categoryId: 1,
        algParameters:[
          {label:'',type:''}
        ],
        algResults:[
          {label:'',value:''}
        ],
        remark: "",
      },
      textarea2: "",
      fileList: [

      ],
      dataRule: {
        algorithmName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],

      },
      algParameterOptions:[
        {
          value: 'int',
          label: 'int'
        }, {
          value: 'string',
          label: 'string'
        }, {
          value: 'list',
          label: 'list'
        }
      ],
      algResultOptions:[
        {
          value: 'file',
          label: 'file'
        }
      ],
      datasetOptions: [
        
      ],
      datasetSelected: [],
    };
  },
  methods: {
    init() {
      this.dataForm.id = 0;
      this.fileList=[];
      this.$http({
        url: this.$http.adornUrl("/category/select"),
        method: "get",
        params: this.$http.adornParams(),
      })
        // 这块修改为获取类别
        .then(({ data }) => {
          this.categoryList = data && data.code === 0 ? data.list : [];
        })
        .then(() => {
          this.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
          });
        })
        // 这部分用不到
        .then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/algs/models/info/${this.dataForm.id}`),
              method: "get",
              params: this.$http.adornParams(),
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.dataForm.algorithmName = data.model.algorithmName;
                this.dataForm.categoryId = data.model.categoryId;
                this.dataForm.remark = data.model.remark;
                // 模板文件地址
                // this.dataForm.dfsUrlv = data.temp.dfsUrlv;
              }
            });
          }
        });
        //这块为获取所有数据集
        this.$http({
          url: this.$http.adornUrl("/dataset/listAll"),
          method: "get",
          params: this.$http.adornParams({
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.datasetOptions = data.list;
          } else {
            this.datasetOptions = [];
          }
      });
    },
    redirectHandle(){
        this.$router.replace({ path: "/alg-algs" });
    },

    //新增算法参数
    addalgParameter(){
      this.dataForm.algParameters.push({
        type:'',
        key:Date.now()
      });
    },
    //新增算法结果
    addalgResult(){
      this.dataForm.algResults.push({
        value:'',
        key:Date.now()
      });
    },
    //删除算法参数
    removealgParameter(item){
      var index = this.dataForm.algParameters.indexOf(item)
        if (index !== -1) {
          this.dataForm.algParameters.splice(index, 1)
        }
    },
    //删除算法结果
    removealgResult(item){
      var index = this.dataForm.algResults.indexOf(item)
        if (index !== -1) {
          this.dataForm.algResults.splice(index, 1)
        }
    },
    
    // 表单提交
    dataFormSubmit() {
      var algParameterNames=[];
      var algParameterTypes=[];
      var algResultNames=[];
      var algResultValues=[];
      for(var i=0;i<this.dataForm.algParameters.length;i++){
        algParameterNames.push(this.dataForm.algParameters[i].label);
        algParameterTypes.push(this.dataForm.algParameters[i].type);
      }
      for(var i=0;i<this.dataForm.algResults.length;i++){
        algResultNames.push(this.dataForm.algResults[i].label);
        algResultValues.push(this.dataForm.algResults[i].value);
      }
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          MessageBox.confirm(`是否新建传统算法?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let formData=new FormData();
          this.fileList.forEach(file=>{
            formData.append('file',file.raw);
          }); 
          formData.append("algorithmId",undefined);
          formData.append("algorithmName",this.dataForm.algorithmName);
          formData.append("remark",this.dataForm.remark);
          formData.append("categoryId",this.dataForm.categoryId);
          formData.append("uid",this.$store.state.user.id);
          formData.append("frameId",-1);
          formData.append("number",1);
          formData.append("dataSets",this.datasetSelected);
          formData.append("algParameterName",algParameterNames);
          formData.append("algParameterTypes",algParameterTypes);
          formData.append("algResultNames",algResultNames);
          formData.append("algResultLocations",algResultValues)
          this.$http({
            url: this.$http.adornUrl(
              `/algs/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data:formData,
          }).then(({ data }) => {
            if (data && data.code === 0) {
              Message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
              this.$router.replace({ path: "/alg-algs" });
            } else {
              Message.error(data.msg);
            }
          });
        }).catch(() => {})

          


        }
      });
    },
    // 以下4个函数是文件上传功能的
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      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>
.divi {
  display: block;
  height: 1px;
  width: 100%;
  margin: 24px 0;
  background-color: #dcdfe6;
  position: relative;
}
.divi2 {
  display: block;
  height: 1px;
  width: 100%;
  position: relative;
}
.sele {
  border: 1px solid #409eff;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 5px 0px;
  margin: 10px;
}
.el-input {
    width: 250px;
}
</style>