<template>
  <div class="container">
    <header-title :title="title" />
    <div class="form">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row type="flex" justify="center">
          <el-col :span="colSize">
            <el-form-item
              label="专家姓名"
              prop="name"
              label-class-name="labelClass"
            >
              <el-input v-model="form.name" placeholder="最多30个字" />
            </el-form-item>
          </el-col>
          <el-col :span="colSize">
            <el-form-item
              label="关联科室"
              prop="departmentId"
              label-class-name="labelClass"
            >
              <el-select
                v-model="form.departmentId"
                filterable
                multiple
                placeholder="请选择关联科室"
              >
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.departmentName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="colSize">
            <el-form-item
              label="专家手机号"
              prop="phone"
              label-class-name="labelClass"
            >
              <el-input v-model="form.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="colSize">
            <el-form-item
              label="是否首页展示"
              prop="isHome"
              label-class-name="labelClass"
            >
              <el-select v-model="form.isHome" filterable placeholder="请选择">
                <el-option label="否" value="0"> </el-option>
                <el-option label="是" value="1"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="colSize">
            <el-form-item
              label="上传证件"
              prop="certificate"
              label-class-name="labelClass"
            >
              <upload-img-single v-model="form.certificate" />
            </el-form-item>
          </el-col>

          <el-col :span="colSize">
            <el-form-item
              label="职位"
              prop="position"
              label-class-name="labelClass"
            >
              <el-input v-model="form.position" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="colSize * 3">
            <el-form-item
              label="专家介绍"
              prop="expertText"
              label-class-name="labelClass"
            >
              <div id="richText"></div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="confirm">
          <el-button type="primary" size="small" @click="submit"
            >确认</el-button
          >
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import userAPI from "@/api/user";
import departmentAPI from "@/api/department";
import HeaderTitle from "@/components/HeaderTitle/index";
import listItemInfo from "@/mixins/listItemInfo";
import E from "wangeditor";
import UploadImgSingle from "@/components/imageUploadSingle/index";
import { debounce, uuid } from "@/utils/index";
import { type } from "os";
import uploadAnyFile from "@/api/uploadAnyFile";
import { getUrl } from "@/config";

export default {
  name: "modifyPw",
  mixins: [listItemInfo],
  components: { HeaderTitle, UploadImgSingle },
  data() {
    return {
      id: this.$route.query.id ?? "",
      activeRefresh: false,
      form: {
        departmentId: [],
        phone: "",
        name: "",
        createUserId: "",
        isHome: "",
        certificate: "",
        expertText: "",
      },
      formMultipleKey: ["departmentId"],
      title: "title",
      colSize: 7,
      rules: {
        name: [
          { required: true, message: "请输入专家姓名", trigger: "blur" },
          { min: 0, max: 30, message: "最多30个字", trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "请选择关联科室", trigger: "change" },
        ],
        phone: [
          { required: true, message: "请填写手机号", trigger: "blur" },
          {
            required: true,
            trigger: "change",
            validator: (rule, value, callback) => {
              if (value.length > 0 && value.length !== 11) {
                callback(new Error("请输入正确格式的手机号"));
              } else {
                callback();
              }
            },
          },
        ],
        isHome: [{ required: true, message: "请选择", trigger: "change" }],
        certificate: [{ required: true, message: "请选择", trigger: "change" }],
        position: [{ required: true, message: "请输入职位", trigger: "blur" }],
      },
      departmentList: [],
    };
  },
  computed: {},
  mounted() {
    this.initWangEditor();
    this.getInfoByIdMethod = userAPI.getExpertById;
    this.addOrUpdateInfoMethod = userAPI.addOrUpdateExpert;
    this.initOptions();
    this.$route.query.id ? this.initInfo() : false;
    // console.log("this.$route.query: ", this.$route.query);
    // this.getMechanismsId();
  },
  methods: {
    //初始化所有配置数据
    initOptions() {
      this.getDepartmentManagementList();
    },

    initWangEditor() {
      this.$nextTick(() => {
        //初始化富文本编辑器及其事件
        this.richEditor = new E("#richText");
        this.richEditor.config.zIndex = 2; //编辑器
        this.richEditor.config.showLinkImg = false;
        this.richEditor.config.customUploadImg = function (
          resultFiles,
          insertImgFn
        ) {
          // resultFiles 是 input 中选中的文件列表
          // insertImgFn 是获取图片 url 后，插入到编辑器的方法
          let names = [];
          resultFiles.forEach((file) => {
            names.push(uuid() + file.name);
          });
          uploadAnyFile
            .uploadAnyFile(resultFiles, ["richText"], names)
            .then((res) => {
              // 上传图片，返回结果，将图片插入到编辑器中
              res.forEach((r) => {
                insertImgFn(getUrl() + r);
              });
            });
        };
        this.richEditor.config.menus = [
          "head", // 标题
          "bold", // 粗体
          "fontSize", // 字号
          "fontName", // 字体
          "italic", // 斜体
          "underline", // 下划线
          "strikeThrough", // 删除线
          "indent", // 缩进
          "lineHeight", // 行高
          "foreColor", // 文字颜色
          "backColor", // 背景颜色
          "splitLine", // 分割线
          "link", // 插入链接
          "list", // 列表
          "justify", // 对齐方式
          "quote", // 引用
          "emoticon", // 表情
          "image", // 插入图片
          "table", // 表格
          "video", // 插入视频
          "code", // 插入代码
          "undo", // 撤销
          "redo", // 重复
        ];
        this.richEditor.create();
        this.richEditor.config.onchange = (newHtml) => {
          this.form.expertText = newHtml;
        };
      });
    },

    afterInitInfo() {
      this.richEditor.txt.html(this.form.expertText);
    },

    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // if (isChange && !!this.id) {
          // console.log('this.form: ', this.form);
          this.addOrUpdateExpert(this.form);
        }
      });
    },

    getDepartmentManagementList() {
      let params = {};
      departmentAPI
        .getDepartmentManagementList(params)
        .then((res) => {
          if (res?.code === 1000) {
            this.departmentList = res.data;
          }
        })
        .catch((err) => {});
    },

    addOrUpdateExpert(params) {
      console.log("params: ", params);
      // return;
      if (!this.id) {
        let loginUser = JSON.parse(localStorage.getItem("mh_userInfo"));
        if (loginUser) params.createUserId = loginUser.id;
      }
      this.addOrUpdateInfo(params, "form");
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;

  .jurisdiction-checked-area {
    // border: 1px solid rgb(209, 204, 204);
    // margin-bottom: 5px;
    .checkbox-title {
      background-color: #f0f2f5;
      padding-left: 5px;

      .checkbox-title-text {
        font-size: 20px;
        font-weight: bold;
      }
    }

    .checkbox-area {
      padding-left: 10px;
    }
  }

  .form {
    width: 100%;
    margin: 0 auto;
    padding-top: 3rem;

    .confirm {
      display: flex;
      justify-content: center;
      padding-top: 1rem;
      text-align: center;
    }
  }
}

.el-select {
  width: 100%;
}
</style>
