<template>
  <div class="contentDetailContainer">
    <header-title :title="title" />
    <div class="contentForm">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-row type="flex" justify="center">
          <el-col :span="colSize">
            <el-form-item required label="所属栏目：" prop="contentType">
              <el-select
                :disabled="isDetail"
                v-model="form.contentType"
                placeholder="请选择所属栏目"
              >
                <el-option
                  v-for="(item, index) in contentTypeOption"
                  :key="index"
                  :label="item"
                  :value="index.toString()"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="colSize">
            <el-form-item required label="内容标题：" prop="contentTitle">
              <el-input
                :disabled="isDetail"
                v-model="form.contentTitle"
                placeholder="请输入内容标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="colSize">
            <el-form-item required label="展示图片：" prop="contentImage">
              <upload-img-single v-model="form.contentImage" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="colSize">
            <el-form-item required label="内容详情：" prop="contentText">
              <div id="richText"></div>
              <!-- <el-input :disabled="isDetail" v-model="form.contentText" placeholder="请输入内容详情"/> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="!isDetail" class="confirm">
        <el-button
          class="button-width"
          style="margin-right: 20px"
          @click="cancel"
          >取消</el-button
        >
        <el-button
          class="button-width"
          type="primary"
          :loading="submitLoading"
          @click="beforeSubmit"
          >确认
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import HeaderTitle from "@/components/HeaderTitle/index";
import contentManagementAPI from "@/api/contentManagement";
import E from "wangeditor";
import { debounce, uuid } from "@/utils/index";
import uploadAnyFile from "@/api/uploadAnyFile";
import { getUrl } from "@/config";
import UploadImgSingle from "@/components/imageUploadSingle/index";

export default {
  name: "contentDetail",
  components: { HeaderTitle, UploadImgSingle },
  data() {
    return {
      richEditor: null,
      isDetail: false,
      contentTypeOption: [
        "医疗护理 > 医保之窗 > 医保服务指南",
        "医疗护理 > 医保之窗 > 医保政策解读",
        "医疗护理 > 医保之窗 > 医院医保动态",
        "医务动态 > 医院动态",
        "医务动态 > 通知公告",
        "医务动态 > 健康园地",
        "医务动态 > 名医有约",
        "人才招聘",
        "就医指南",
      ],
      id: this.$route.query.id ?? "",
      form: {
        contentType: "",
        contentTitle: "",
        contentText: "",
        contentImage: "",
        status: "0",
      },
      submitLoading: false,
      title: "",
      colSize: 18,
      rules: {
        contentType: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请选择所属栏目",
          },
        ],
        contentImage: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请选择展示图片",
          },
        ],
        contentTitle: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入内容标题",
          },
        ],
        contentTitle: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入内容标题",
          },
        ],
      },
    };
  },
  mounted() {
    this.initWangEditor();
    this.$route.query.id ? this.initData() : false;
    this.title = this.$route.meta.name;
    this.isDetail = this.$route.query.isDetail;
  },
  methods: {
    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.contentText = newHtml;
        };
      });
    },
    initData() {
      contentManagementAPI
        .getContentManagementById({ id: this.id })
        .then((res) => {
          if (res.code === 1000) {
            this.form = res.data;
            this.richEditor.txt.html(this.form.contentText);
          } else {
            this.form = [];
          }
        })
        .catch((err) => {
          this.form = [];
          this.$message.error("获取数据失败，请重试");
        });
    },
    submitcontent() {
      let userId =
        localStorage.getItem("mh_userInfo") &&
        JSON.parse(localStorage.getItem("mh_userInfo")).id
          ? JSON.parse(localStorage.getItem("mh_userInfo")).id
          : "";
      let params = {
        id: this.id ? this.id : null,
        ...this.form,
        createUserId: userId,
      };
      contentManagementAPI
        .addOrUpdateContentManagement(params)
        .then((res) => {
          if (res.code === 1000) {
            this.$message.success(this.title + "成功！");
            this.submitLoading = false;
            this.cancel();
          } else {
            this.$message.error(this.title + "失败！");
            this.submitLoading = false;
          }
        })
        .catch((err) => {
          console.error(err);
          this.$message.error(this.title + "失败！");
          this.submitLoading = false;
        });
    },
    beforeSubmit: debounce(
      function () {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.submitLoading) {
              return;
            }
            this.submitLoading = true;
            this.submitcontent();
          }
        });
      },
      2000,
      true
    ),
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.go(-1);
    },
  },
};
</script>

<style scoped lang="scss">
.contentDetailContainer {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;

  /*添加css样式*/
  ::v-deep input::-webkit-outer-spin-button,
  ::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }

  ::v-deep input[type="number"] {
    -moz-appearance: textfield;
  }

  .contentForm {
    padding-top: 3rem;

    ::v-deep .el-input.is-disabled .el-input__inner {
      color: $color-333;
    }

    .secondaryTitle {
      line-height: 1.5rem;
      font-weight: bold;
      padding-left: 6px;
      border-left: 3px solid $theme-color;
      margin: 1rem 0;
    }

    .form-item {
      width: 45%;
    }

    .confirm {
      width: 90%;
      margin-top: 60px;
      margin-bottom: 40px;
      text-align: center;
    }
  }

  ::v-deep .el-form-item__content {
    text-align: left;
  }

  ::v-deep .el-date-editor {
    width: 600px;
  }

  ::v-deep .el-select {
    width: 600px;
  }

  ::v-deep .el-cascader {
    width: 600px;
  }

  ::v-deep .el-input {
    width: 600px;
  }

  .button-width {
    width: 120px;
  }
}
</style>
