<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="tmpName">
        <el-input v-model="dataForm.tmpName" 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 v-if="!this.dataForm.id" 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="描述信息" 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,
        tmpName: "",
        // 本模板的类别
        categoryId: 1, 
        remark: "",
      },
      textarea2: "",
      fileList: [

      ],
      dataRule: {
        tmpName: [
          { 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.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
          });
        })
        .then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/algs/templs/info/${this.dataForm.id}`),
              method: "get",
              params: this.$http.adornParams(),
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.dataForm.tmpName = data.temp.tmpName;
                this.dataForm.categoryId = data.temp.categoryId;
                this.dataForm.remark = data.temp.remark;
                // 模板文件地址
                // this.dataForm.dfsUrlv = data.temp.dfsUrlv;
              }
            });
          }else{
            this.fileList=[];
          }
        });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.visible=false
          MessageBox.confirm(`确定${this.dataForm.id ? '修改':'新增'}该算法模板?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let formData=new FormData();
          //若是新增模板，则添加文件
          if(!this.dataForm.id){
            this.fileList.forEach(file=>{
              formData.append('file',file.raw);
            }); 
          }
          formData.append('tmpId',this.dataForm.id || undefined);
          formData.append('tmpName',this.dataForm.tmpName);
          formData.append('categoryId',this.dataForm.categoryId);
          formData.append('remark',this.dataForm.remark);
          formData.append('uid',this.$store.state.user.id);
          this.$http({
            url: this.$http.adornUrl(
              `/algs/templs/${!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(
        `当前限制选择 1 个文件，本次选择了 ${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>
