<!--  -->
<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-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="first">

        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" 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="类别" 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="python版本和框架">
            <el-select v-model="imageSelected" placeholder="环境选择">
              <el-option v-for="data in images" :key="data.baseImageId" :label="data.pythonAndFrame" :value="data.baseImageId">
              </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-item style="float:right">
            <el-button type="primary" @click="activeName='second'">下一步</el-button>
          </el-form-item>
        </el-form>

      </el-tab-pane>

      <el-tab-pane label="数据集选择" name="second">
        <el-form :model="dataForm2" :rules="dataRule" ref="dataset" label-width="180px">

          <el-form-item label="选择数据集：">

            <el-select v-model="value1" 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 style="float:right">
            <el-button @click="activeName='first'">返回</el-button>
            <el-button type="primary" @click="activeName='third'">下一步</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="算法及模板" name="third">
        <el-form :model="dataForm2" :rules="dataRule" ref="dataset" label-width="180px">

          <el-form-item label="上传代码：" size="mini">
            <el-upload class="upload-demo" action="#"
              :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" 
              :on-change="fileChange"
              multiple :limit="10"
              :on-exceed="handleExceed" :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="value2" multiple placeholder="选择算法">
              <el-option v-for="item in algOptions" :key="item.modelId" :label="item.modelName" :value="item.modelId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择模板：">
            <el-select v-model="value3" multiple placeholder="选择模板">
              <el-option v-for="item in tmpOptions" :key="item.tmpId" :label="item.tmpName" :value="item.tmpId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item style="float:right">
            <el-button @click="activeName='second'">返回</el-button>
            <el-button type="primary" @click="activeName='fourth'">下一步</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="完成" name="fourth">

        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="180px" :disabled="true">
          <el-form-item label="智能算法名称" prop="algorithmName">
            <el-input v-model="dataForm.algorithmName" placeholder="请输入传统算法名称"></el-input>
          </el-form-item>

          <el-form-item label="类别" 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="python版本和框架">
            <el-select v-model="imageSelected" placeholder="环境选择">
              <el-option v-for="data in images" :key="data.baseImageId" :label="data.pythonAndFrame" :value="data.baseImageId">
              </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-item label="选择数据集：">

            <el-select v-model="value1" 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 label="上传代码：" size="mini">
            <el-upload class="upload-demo" action=""
              :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :auto-upload="false"
              multiple :limit="10"
              :on-exceed="handleExceed" :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="value2" multiple placeholder="选择算法">
              <el-option v-for="item in algOptions" :key="item.modelId" :label="item.modelName" :value="item.modelId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择模板：">
            <el-select v-model="value3" multiple placeholder="选择模板">
              <el-option v-for="item in tmpOptions" :key="item.tmpId" :label="item.tmpName" :value="item.tmpId">
              </el-option>
            </el-select>
          </el-form-item>

         

        </el-form>
        <el-form>
          <el-form-item style="float:right">
            <el-button @click="activeName='second'">返回</el-button>
            <el-button type="primary" @click="dataFormSubmit()">完成</el-button>
          </el-form-item>
        </el-form>
         

      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { MessageBox } from 'element-ui'
import { Message } from "element-ui"
export default {
  created() {
    this.init();
  },
  activated() {
    this.init();
  }, 
  data() {
    return {
      datasetOptions: [
        {datasetId:1,datasetName:"fea_data.csv"},
        {datasetId:2,datasetName:"st_test.csv"},
      ],
      algOptions: [],
      tmpOptions: [],
      value1: [],
      value2: [],
      value3: [],
      images:[],
      fileList: [
        
      ],

      activeName: "first",
      imageSelected: null,
      dataSets: [],
      visible: false,
      // 获取所有类别列表
      categoryList: [],
      dataForm: {
        id: 0,
        algorithmName: "",
        categoryId: 1,
        remark: "",
        dataset: [],
      },
      textarea2: "",
      dataRule: {
        algorithmName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        // imageSelected: [
        //   { 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" },
        // ],
      },
    };
  },
  methods: {
    init() {
      this.activeName="first",
      this.value1= [],
      this.value2= [],
      this.value3=[],
      this.fileList=[],
      this.imageSelected=null,
      this.dataForm.id = 0;
      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("/baseImage/listAll"),
          method: "get",
          params: this.$http.adornParams({
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.images = data.list;
          } else {
            this.images = [];
          }
        });

        //这块为获取所有数据集
        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 = [];
          }
      });

        //这块为获取所有算法模型
        this.$http({
          url: this.$http.adornUrl("/algs/models/listAll"),
          method: "get",
          params: this.$http.adornParams({
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.algOptions = data.list;
          } else {
            this.algOptions = [];
          }
      });

        //这块为获取所有模板
        this.$http({
          url: this.$http.adornUrl("/algs/templs/listAll"),
          method: "get",
          params: this.$http.adornParams({
            tmpname: '',
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.tmpOptions = data.list;
          } else {
            this.tmpOptions = [];
          }
      });
    },
    redirectHandle() {
      this.$router.replace({ path: "/alg-algs" });
    },
    // 表单提交
    dataFormSubmit() {
      console.log(this.fileList);
      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",this.imageSelected);
          formData.append("number",1);
          formData.append("dataSets",this.value1);
          formData.append("algModels",this.value2);
          formData.append("algTemplates",this.value3);
          console.log(formData);

          this.$http({
            url: this.$http.adornUrl(
              `/algs/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data:formData,
            Headers:{
              'Content-Type':'application/json;charset=UTF-8'
            },
          }).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 scoped>
.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;
}
</style>