<template>
  <div>
    <div class="form-wrapper">
      <el-form label-width="100px" :model="detail">
        <el-form-item label="名称：">
          <el-input v-model="detail.name"></el-input>
        </el-form-item>
        <el-form-item label="公司：">
          <el-input v-model="detail.company"></el-input>
        </el-form-item>
        <el-form-item label="部门：">
          <el-input v-model="detail.department"></el-input>
        </el-form-item>
        <el-form-item label="职位：">
          <el-input v-model="detail.post"></el-input>
        </el-form-item>
        <el-form-item label="电话：">
          <el-input v-model="detail.tel"></el-input>
        </el-form-item>
        <el-form-item label="标签：">
          <editabel-tag v-model="detail.personTags"></editabel-tag>
        </el-form-item>
        <el-form-item label="地址：">
          <el-input v-model="detail.address"></el-input>
        </el-form-item>
        <el-form-item label="授权项目：">
          <el-select v-model="detail.buildings" placeholder="请选择">
            <el-option v-for="(build,i) in buildings.list || []" :key="i" :label="build.buildingName" :value="build.buildingId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片：">
          <el-upload class="avatar-uploader" :headers="uploadHeaders" :action="upFileUrl" name="file" :show-file-list="false" :before-upload="beforeImgUpload" :on-success="handleAvatarSuccess">
            <img v-if="detail.photo" :src="detail.photo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
          <el-form-item label="简介：">
            <el-input type="textarea" :rows="5"  v-model="detail.personDescription"></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-radio-group v-model="detail.status">
            <el-radio-button :label="0">禁用</el-radio-button>
            <el-radio-button :label="1">启用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="$router.go(-1)">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
import apis from "../../config/api";
import E from "wangeditor";

const { mapActions: mapPersonActions } = createNamespacedHelpers("persons");
const {
  mapState: mapBuildingState,
  mapActions: mapBuildingActions
} = createNamespacedHelpers("building");
export default {
  name: "consultantEdit",
  components: {
    EditabelTag: () => import('@/components/EditableTag.vue')
  },
  data() {
    return {
      upFileUrl: apis.file.upload.url,
      detail: {
        name: undefined,
        company: undefined,
        department: undefined,
        post: undefined,
        tel: undefined,
        photo: undefined,
        status: 1,
        buildings: undefined,
        personDescription: undefined
      }
    };
  },
  created() {
    this.init();
  },
  computed: {
    ...mapBuildingState({
      buildings: x => x.buildings
    }),
    uploadHeaders() {
      const token = localStorage.getItem("x-token") || "";

      return {
        Authorization: `Bearer ${token}`
      };
    }
  },
  methods: {
    ...mapBuildingActions(["getBuildings"]),
    ...mapPersonActions(["getConsultant", "editConsultant"]),
    init() {
      if (this.$route.params.id) {
        this.getConsultant({ id: this.$route.params.id }).then(data => {
          this.detail = {
            ...data,
            buildings: Array.isArray(data.projects) ? data.projects[0] : '',
          };
        });
      }
    },
    beforeImgUpload(file) {
      if (file.type !== "image/jpeg" && file.type !== "image/png") {
        this.$message.error("上传图片只能是 JPG 或 PNG 格式!");
        return false;
      }

      this.showLoadding("上传中...");
      return true;
    },

    handleAvatarSuccess(res) {
      this.detail.photo = res.data;
      this.hideLoadding();
    },

    submitForm() {
      this.showLoadding("保存中...");
      this.editConsultant(this.detail)
        .then(res => {
          if (res.personId) {
            this.detail = res;
          }

          this.hideLoadding();
          this.$notify.info("保存成功");
          this.$router.go(-1)
        })
        .catch(err => {
          this.hideLoadding();
          this.$notify.error(err.message);
        });
    },

    showLoadding(text) {
      this.loading = this.$loading({
        text,
        lock: true,
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)"
      });
    },

    hideLoadding() {
      if (this.loading) this.loading.close();
    }
  },
  mounted() {
    const _that = this;
    const phoneEditor = new E("#websiteEditorElem");
    phoneEditor.customConfig.onchange = function(html) {
      _that.dynamic = { ..._that.dynamic, url: html };
    };
    // phoneEditor.customConfig.uploadImgServer = this.upFileUrl
    // phoneEditor.customConfig.uploadFileName = 'uploadFiles'

    phoneEditor.customConfig.customUploadImg = function(files, insert) {
      _that.uploadImg(files[0]).then(data => {
        insert(data);
      });
    };
    phoneEditor.customConfig.menus = [
      "head", // 标题
      "bold", // 粗体
      "fontSize", // 字号
      "fontName", // 字体
      "italic", // 斜体
      "underline", // 下划线
      "strikeThrough", // 删除线
      "foreColor", // 文字颜色
      "backColor", // 背景颜色
      "justify", // 对齐方式
      "image" // 插入图片
    ];
    // phoneEditor.create()

    this.getBuildings({
      pageNum: 1,
      pageSize: 100
    }).then(() => {
      if ((this.$route.query.id || "") !== "") {
        this.getDetail({ id: this.$route.query.id }).then(data => {
          phoneEditor.txt.html(data.url);
        });
      }
    });
  }
};
</script>

<style lang="scss" scoped>
.form-wrapper {
  width: 60%;
}
</style>

<style lang="scss">
.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>
