<template>
  <el-dialog :title="!dataForm.id ? '新增模板' : '修改模板'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label="模板名称" prop="modelName">
        <el-input v-model="dataForm.modelName" 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" 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="形式" prop="form">
          <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-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>
    <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: "",
      },
      textarea2: "",
      fileList: [
      ],
      forms:[
        {
          label:"传统算法",
          value:1
        },
        {
          label:"智能算法",
          value:2
        }
      ],
      dataRule: {
        modelName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" },
        ],
        form: [
          { 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(id) {
      this.dataForm.id = 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.fileList=[];
          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.modelName = data.model.modelName;
                this.dataForm.categoryId = data.model.categoryId;
                this.dataForm.remark = data.model.remark;
                // 模板文件地址
                // this.dataForm.dfsUrlv = data.temp.dfsUrlv;
              }
            });
          }
        });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.visible=false;
          MessageBox.confirm(`是否上传该算法?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let formData=new FormData();
          this.fileList.forEach(file=>{
            formData.append('file',file.raw);
          }); 
          formData.append('modelName',this.dataForm.modelName);
          formData.append('categoryId',this.dataForm.categoryId);
          formData.append('remark',this.dataForm.remark);
          formData.append('uid',this.$store.state.user.id);
          formData.append('form',this.dataForm.form);
          this.$http({
            url: this.$http.adornUrl(
              `/algs/models/${!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");
                },
              });
            } 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>
