<template>
  <basic-container>
    <div v-loading="loading" class="avue--view">
      <el-row>
        <el-col :span="24" class="title">
          用工单位信息
          <span style="float: right">
            <el-button
              type="text"
              @click="isCanEdit = true"
              v-show="!isCanEdit && type === 'add'"
              style="padding: 0"
              >新增</el-button
            >
            <el-button
              type="text"
              @click="isCanEdit = true"
              v-show="!isCanEdit && type === 'edit'"
              style="padding: 0"
              >编辑</el-button
            >
          </span>
        </el-col>
      </el-row>

      <el-row v-show="!isCanEdit && type === 'add'">
        <el-col :span="1">&nbsp;</el-col>
        <el-col :span="22" class="empty-tip"
          >添加用工单位信息让用户更生动地了解公司吧~</el-col
        >
        <el-col :span="1">&nbsp;</el-col>
      </el-row>

      <el-form
        :model="form"
        ref="form"
        class="avue-form"
        :class="{'closeInputBorder': !isCanEdit}"
        v-show="isCanEdit || type === 'edit'"
        label-position="right"
        label-width="100px"
        style="padding: 10px 10px;"
        :disabled="!isCanEdit"
        :rules="rules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="企业简称：" prop="companyName">
              <el-input v-model="form.companyName" maxlength="50" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="公司规模：" prop="companySize">
              <el-input v-model="form.companySize"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">&nbsp;</el-col>
          <el-col :span="11">
            <el-form-item label="公司网站：">
              <el-input v-model="form.websiteUrlId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公司logo：">
              <el-upload
                :class="{ disabled: !isCanEdit }"
                list-type="picture-card"
                :auto-upload="true"
                :file-list="logoList"
                :limit="1"
                :action="putFile"
                :on-preview="handleLogoPreview"
                :on-exceed="handleLogoLimit"
                :on-success="handleLogoSuccess"
                :on-remove="handleLogoRemove"
                :before-remove="beforeRemove"
                :before-upload="beforeUpload"
              >
                <div slot="tip" class="el-upload__tip">
                  图片大小：不超过5M，仅能上传1张
                </div>
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible2">
                <img width="100%" :src="dialogImageUrl2" alt />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="企业简介：">
              <el-input
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 5 }"
                v-model="form.introduce"
                :readonly="!isCanEdit"
                maxlength="50"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公司环境：">
              <el-upload
                :class="{ disabled: !isCanEdit }"
                list-type="picture-card"
                :auto-upload="true"
                :file-list="imgList"
                :limit="10"
                :action="putFile"
                :on-preview="handleImgPreview"
                :on-exceed="handleImgLimit"
                :on-success="handleImgSuccess"
                :on-remove="handleImgRemove"
                :before-remove="beforeRemove"
                :before-upload="beforeUpload"
              >
                <div slot="tip" class="el-upload__tip">
                  添加公司环境、员工照片，给用户展示更生动的公司全貌，最多上传10张照片
                </div>
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item style="text-align: center; margin-left: -112px">
              <el-button
                @click="resetOrCancel"
                :loading="loading"
                v-show="isCanEdit && type === 'edit'"
                class="btn"
                >取消</el-button
              >
              <el-button
                type="primary"
                @click="submit"
                :loading="loading"
                v-show="isCanEdit"
                class="btn"
                >保存</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </basic-container>
</template>
<script>
import { getDetail, add, update } from "@/api/tenant/company";
import { putFile } from "@/api/resource/oss";
import { validatenull } from "@/util/validate";

const getReq = (type, form) => {
  if (type === "add") {
    return add(form);
  } else if (type === "edit") {
    return update(form);
  }
};

export default {
  data() {
    return {
      disabled: false,
      dialogImageUrl: "",
      dialogVisible: false,
      dialogImageUrl2: "",
      dialogVisible2: false,
      logoList: [],
      imgList: [],
      form: {},
      isCanEdit: false,
      loading: false,
      putFile,
      rules: {
        companyName: [
          { max: 50, message: "长度在 50 个字以内", trigger: "blur" },
        ],
        companySize: [
          { max: 50, message: "长度在 50 个字以内", trigger: "blur" },
        ],
        websiteUrlId:[
          { max: 50, message: "长度在 50 个字以内", trigger: "blur" },
        ],
        introduce:[
          { max: 50, message: "长度在 500 个字以内", trigger: "blur" },
        ]
      },
    };
  },
  created() {
    this.getInfo();
  },
  computed: {
    uploadDisabled() {
      return this.isCanEdit;
    },
    type() {
      if (validatenull(this.form.id)) {
        return "add";
      } else {
        return "edit";
      }
    },
  },
  methods: {
    /*获取公司主页 */
    getInfo() {
      this.loading = true;
      getDetail().then((res) => {
        let form = res.data.data || {};
        this.form = {
          id: form.id,
          companyName: form.companyName,
          companySize: form.companySize,
          logoUrlId: form.logoUrlId,
          websiteUrlId: form.websiteUrlId,
          baseUrlId: form.baseUrlId,
          introduce: form.introduce,
        };
        //给缩略图赋值url
        if (form.logoUrlId) {
          var arr = form.logoUrlId.split(",");
          for (var i = 0; i < arr.length; i++) {
            this.logoList.push({
              url: arr[i],
            });
          }
        }
        if (form.baseUrlId) {
          var arr2 = form.baseUrlId.split(",");
          for (var j = 0; j < arr2.length; j++) {
            this.imgList.push({
              url: arr2[j],
            });
          }
        }
        this.loading = false;
      });
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          getReq(this.type, this.form)
            .then(() => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.resetOrCancel();
              this.loading = false;
            })
            .catch((error) => {
              window.console.log(error);
              this.loading = false;
            });
        }
      });
    },
    /*取消 */
    resetOrCancel() {
      if (this.$refs.groups) {
        this.$refs.groups.clearValidate();
      }
      this.logoList = [];
      this.imgList = [];
      this.getInfo();
      this.isCanEdit = false;
    },
    /*上传logo */
    handleLogoSuccess(res) {
      if (res.code === 200) {
        this.form.logoUrlId = res.data.link;
      } else {
        this.$message.error(`上传失败`);
      }
    },
    /*删除logo */
    beforeRemove() {
      return this.$confirm(`是否确定移除该选项？`);
    },
    handleLogoRemove() {
      this.form.logoUrlId = "";
    },
    /*查看logo */
    handleLogoPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /*验证图片个数 */
    handleLogoLimit() {
      this.$message.warning(`当前限制选择 1 张图片`);
    },
    /*下载 */
    handleDownload() {},
    /*上传公司环境 */
    handleImgSuccess(res) {
      if (res.code === 200) {
        this.imgList.push({
          url: res.data.link,
        });
        var str = "";
        for (var i = 0; i < this.imgList.length; i++) {
          str += this.imgList[i].url + ",";
        }
        if (str.length > 0) {
          str = str.substr(0, str.length - 1);
        }
        this.form.baseUrlId = str;
      } else {
        this.$message.error(`上传失败`);
      }
    },
    /*查看图片 */
    handleImgPreview(file) {
      this.dialogImageUrl2 = file.url;
      this.dialogVisible2 = true;
    },
    handleImgRemove(file) {
      var index = 0;
      for (var i in this.imgList) {
        if (this.imgList[i]["uid"] == file.uid) {
          index = i;
          break;
        }
      }
      this.imgList.splice(index, 1);

      var str = "";
      for (var k = 0; k < this.imgList.length; k++) {
        str += this.imgList[k].url + ",";
      }
      if (str.length > 0) {
        str = str.substr(0, str.length - 1);
      }
      this.form.baseUrlId = str;
    },
    /*验证图片个数和大小 */
    handleImgLimit() {
      this.$message.warning(`当前限制选择 10 张图片`);
    },
    /*上传图片前 判断大小 */
    beforeUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error("上传图片大小不能超过 5MB!");
      }
      return isLt5M;
    },
  },
};
</script>
<style scoped>
.el-row {
  margin-top: 10px;
}
.el-col {
  margin-bottom: 0px;
}

.title {
  margin-bottom: 20px;
  background: #f8f8f8;
  padding: 10px 10px 10px 10px;
}
.empty-tip {
  height: 200px;
  line-height: 200px;
  border: 1px solid #ebebeb;
  text-align: center;
}
.el-button {
  padding: 14px 42px;
}
.closeInputBorder ::v-deep .el-input__inner {
  border: 0;
}
.closeInputBorder ::v-deep .el-textarea__inner {
  border: 0;
}
</style>
<style>
.disabled .el-upload--picture-card {
  display: none !important;
}
</style>
