
<template>
    <el-dialog
      :visible.sync="showDialog"
      :title="title"
      :modal-append-to-body="false"
      style="text-align: left;"
      @close="closeDialog"
      :close-on-click-modal="false"
      width="900px"
    >
      <div class="user-panel" v-loading="loading">
        <el-form
          ref="form"
          :model="formModel"
          :rules="ruleValidate"
          :label-width="'100px'"
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="formModel.title" placeholder="请输入标题" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="企业名称" prop="enterpriseId">
            <el-select
            v-model="formModel.enterpriseId"
            placeholder="请选择"
            style="width: 300px"
            clearable
          >
            <el-option
              v-for="item in enterpriseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="formModel.name" placeholder="请输入名称" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="报名结束时间" prop="endTime">
            <el-date-picker
              style="width: 300px"
              v-model="formModel.endTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="缩略图" prop="thumbnailImage">
              <el-upload
                  style="width:300px"
                  class="avatar-uploader"
                  name="photoFile"
                  :action="uploadUrl"
                  :headers="headers"
                  :data="uploadData"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="fileUrl" :src="fileUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <mce-editor
                ref="editor"
                uploadName="upfile"
                v-model="formModel.content"
                :url="uploadUrl1"
                :config="editorConfig"
                style="width: 90%"
            ></mce-editor>
        </el-form-item>
        <el-form-item label="上传附件" prop="file">
          <el-upload
            class="upload-demo"
            name="photoFile"
            :action="uploadUrl2"
            :headers="headers"
            :data="uploadData2"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleAvatarSuccess1"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </template>
  <script>
  import Constant from "@/constant";
  import { getToken } from "@/utils/auth"; // get token from cookie
  import trainingInfoApi from "@/api/base/trainingInfo";
  import MceEditor from "@/components/Tinymce";
  import dataDictionaryApi from "@/api/sys/dataDictionary";
  import enterpriseInfoApi from "@/api/base/enterpriseInfo";

  
  export default {
    props: ["businessKey", "title"],
    data() {
      return {
          showPwd: true,
          ruleValidate: {
              title: [
              { required: true, message: "标题不能为空", trigger: "blur" },
              ],
              author: [
              { required: true, message: "作者不能为空", trigger: "blur" },
              ],
              type: [
              { required: true, message: "类型不能为空", trigger: "blur" },
              ],
          },
          roleList: [],
          formModel: {},
          showDialog: true,
          loading: false,
          submitting: false,
          companyProps: {
              value: "id",
              label: "name",
          },
          typeList:[],
          enterpriseList:[],
          //上传地址
          uploadUrl: Constant.serverUrl + "/uploadPicture",
          uploadData: {
              subFolder: "temporary-workers",
          },
          fileUrl: "",
          headers: {
              Authorization: getToken(),
          },
          uploadUrl1: Constant.serverUrl + "/tinymce/upload?token=" + getToken(),
          editorConfig: {
            height: 300,
            width: 660,
          },
          fileList:[],
          uploadUrl2: Constant.serverUrl + "/uploadFile",
          uploadData2: {
              subFolder: "temporary-workers",
          },
      };
    },
    created() {
        var self = this;

        dataDictionaryApi.findByCatalogName({catalogName: "共享用工类型",})
        .then((response) => {
            var jsonData = response.data;
            self.typeList = jsonData.data;
        });

        enterpriseInfoApi.list().then(function (response) {
          var jsonData = response.data;
          if (jsonData.result) {
              if (jsonData.data != null && jsonData.data != "") {
                  self.enterpriseList = jsonData.data;
              }
          }
        });
    },
    methods: {
      closeDialog() {
        this.$emit("close", false);
      },
      handleSubmit() {
        var self = this;
  
        this.$refs["form"].validate((valid) => {
          if (valid) {
            (function () {
              var id = self.formModel.id;

              self.formModel.fileList = self.fileList

              //alert(self.fileList);
  
              if (id == null || id.length == 0) {
                return trainingInfoApi.add(self.formModel);
              } else {
                return trainingInfoApi.update(self.formModel);
              }
            })().then(function (response) {
              var jsonData = response.data;
  
              if (jsonData.result) {
                self.$message({
                  message: "保存成功!",
                  type: "success",
                });
  
                self.$emit("close", true);
              } else {
                self.$message({
                  message: jsonData.message + "",
                  type: "warning",
                });
  
                self.$emit("close", false);
              }
            });
          }
        });
      },
      handleAvatarSuccess(res, file) {
          var self = this;
          self.formModel.thumbnailImage = res.data;
  
          self.fileUrl =
            res.data + "?x-oss-process=image/resize,m_lfit,h_300,w_300";
      },
      beforeAvatarUpload(file) {
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
              this.$message.error('上传头像图片大小不能超过 2MB!');
          }
          return isLt2M;
      },
      handleAvatarSuccess1(res, file) {
          var self = this;
          self.fileList.push(res.data);
      },
      handleRemove(file, fileList) {
        this.fileList = 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 this.$confirm(`确定移除 ${ file.name }？`);
      }
    },
    async mounted() {
      var self = this;
      self.loading = true;
  
      (function () {
        if (self.businessKey != null && self.businessKey.length > 0) {
          return trainingInfoApi.edit(self.businessKey);
        } else {
          return trainingInfoApi.create();
        }
      })()
        .then((response) => {
          var jsonData = response.data;
  
          if (jsonData.result) {
            self.formModel = jsonData.data;

            if (self.formModel.content != null) {
                self.$refs.editor.setContent(self.formModel.content);
            }

            let thumbnailImage = self.formModel.thumbnailImage;
            if (thumbnailImage != null) {
                self.fileUrl = thumbnailImage 
            }

            self.fileList = self.formModel.fileList

            self.showModal = true;
          } else {
            self.$message.error(jsonData.message + "");
          }
  
          self.loading = false;
        })
        .catch((error) => {
          self.$message.error(error + "");
          self.loading = false;
        });
    },
    components: {
        "mce-editor": MceEditor,
    },
  };
  </script>
  <style scoped>
  .user-panel {
    margin: 10px auto;
  }
  
  .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  </style>