
<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="600px"
    >
      <div class="user-panel" v-loading="loading">
        <el-form
          ref="form"
          :model="formModel"
          :rules="ruleValidate"
          :label-width="'100px'"
        >
          <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="address">
            <el-input v-model="formModel.address" placeholder="请输入企业地址" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="企业联系人" prop="contactsPersonId">
            <el-input v-model="formModel.contactsPersonId" placeholder="请输入企业联系人" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactsPhone">
            <el-input v-model="formModel.contactsPhone" placeholder="请输入联系电话" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="营业执照" prop="licenseImage">
              <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>
      </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 enterpriseInfoApi from "@/api/base/enterpriseInfo";
  
  export default {
    props: ["businessKey", "title"],
    data() {
      const validateIsReName=(rule,value,callBack)=>{

        var formData = new FormData();

        formData.append("id", this.businessKey);
        formData.append("name", value);

        enterpriseInfoApi.nameIsRepeatCheck(formData).then(function (response) {
            self.loading = false;

            var jsonData = response.data;

            if(jsonData.result){
              if(!jsonData.data){
                callBack(new Error("检测到重复的企业名称，不能重复添加！"));
              }
              else{
                callBack();
              }
            }
        })
      }
      return {
          showPwd: true,
          ruleValidate: {
              name: [
                { required: true, message: "企业名称不能为空", trigger: "blur" },
                { validator: validateIsReName, trigger: "blur" }
              ],
          },
          roleList: [],
          formModel: {},
          showDialog: true,
          loading: false,
          submitting: false,
          companyProps: {
              value: "id",
              label: "name",
          },
          //上传地址
          uploadUrl: Constant.serverUrl + "/uploadPicture",
          uploadData: {
              subFolder: "temporary-workers",
          },
          fileUrl: "",
          headers: {
              Authorization: getToken(),
          },
      };
    },
    methods: {
      closeDialog() {
        this.$emit("close", false);
      },
      handleSubmit() {
        var self = this;
  
        this.$refs["form"].validate((valid) => {
          if (valid) {
            (function () {
              var id = self.formModel.id;
  
              if (id == null || id.length == 0) {
                return enterpriseInfoApi.add(self.formModel);
              } else {
                return enterpriseInfoApi.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.licenseImage = res.data;
  
          self.fileUrl =
            res.data + "?x-oss-process=image/resize,m_lfit,h_300,w_300";
      },
      beforeAvatarUpload(file) {
          const isJPG = file.type === 'image/jpeg';
          const isLt2M = file.size / 1024 / 1024 < 2;
  
          // if (!isJPG) {
          //     this.$message.error('上传头像图片只能是 JPG 格式!');
          // }
          if (!isLt2M) {
              this.$message.error('上传头像图片大小不能超过 2MB!');
          }
          return isLt2M;
      }
    },
    async mounted() {
      var self = this;
      self.loading = true;
  
      (function () {
        if (self.businessKey != null && self.businessKey.length > 0) {
          return enterpriseInfoApi.edit(self.businessKey);
        } else {
          return enterpriseInfoApi.create();
        }
      })()
        .then((response) => {
          var jsonData = response.data;
  
          if (jsonData.result) {
            self.formModel = jsonData.data;

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

            self.showModal = true;
          } else {
            self.$message.error(jsonData.message + "");
          }
  
          self.loading = false;
        })
        .catch((error) => {
          self.$message.error(error + "");
          self.loading = false;
        });
    },
    components: {
    },
  };
  </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>