<template>
  <div>
    <div class="search-wrapper ins-content">
      <el-button type="primary" @click="addHandle">新增</el-button>
    </div>
    <div class="table-wrapper">
      <table-template
        :tableData="tableData"
        :tableColumns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        @Jump="jumpPage"
      >
        <el-table-column slot="iconUrl" label="图标" align="center">
          <template slot-scope="scope">
            <el-image
              style="width: 30px; height: 30px"
              :src="scope.row.iconUrl"
              :preview-src-list="[scope.row.iconUrl]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column slot="delFlag" label="启用状态" align="center">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.delFlag == 0 || scope.row.delFlag == 1"
              :type="
                scope.row.delFlag == 1
                  ? 'danger'
                  : scope.row.delFlag == 0
                  ? 'success'
                  : ''
              "
              >{{ scope.row.delFlag == 1 ? "禁用" : "启用" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" round @click="view(scope.row)"
              >查看</el-button
            >

            <el-button
              type="primary"
              size="mini"
              class="btn"
              round
              @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button
              @click="delFlagHandle(scope.row)"
              :type="scope.row.delFlag == 0 ? 'warning' : 'success'"
              size="mini"
              round
              slot="reference"
              >{{ scope.row.delFlag == 0 ? "禁用" : "启用" }}
            </el-button>
          </template>
        </el-table-column>
      </table-template>
    </div>
    <el-dialog
      :title="type == 'view' ? '查看' : '编辑'"
      :visible.sync="dialogVisible"
      width="70%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      class="editorDialog"
    >
      <el-form
        :model="messageForm"
        ref="messageForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="messageForm.title"
            placeholder="请输入标题"
            clearable
            :disabled="type === 'view'"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="messageForm.sort"
            :min="1"
            :disabled="type === 'view'"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <!-- <quillEditor v-model="content" class="edit" /> -->
      <template>
        <div style="border: 1px solid #ccc" v-if="dialogVisible">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
          />
        </div>
      </template>

      <span
        slot="footer"
        class="dialog-footer"
        v-if="type == 'edit' || type == 'add'"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="contentConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

import TableTemplate from "@/components/Table";
import { config } from "@/utils/request.js";

import axios from "axios";
import {
  contentList,
  contentAdd,
  contentEdit,
  contentEnable,
} from "@/api/instructions";
export default {
  name: "detail",
  components: { TableTemplate, Editor, Toolbar },

  data() {
    return {
      searchForm: {
        manualId: "",
      },
      type: "add",
      editor: null,
      content: "",
      toolbarConfig: {},
      editorConfig: { placeholder: "请输入内容...", MENU_CONF: {} },
      mode: "default", // or 'simple'
      messageForm: {
        title: "",
        sort: "",
        id: "",
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],

        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
      },
      tableData: [],
      pagination: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },

      tableColumns: [
        {
          key: "title",
          label: "标题",
        },
        {
          key: "manualTitle",
          label: "手册名称",
        },

        {
          key: "sort",
          label: "排序",
        },
        {
          key: "delFlag",
          label: "启用状态",
          type: "slot",
        },
        {
          key: "createTime",
          label: "创建时间",
        },
      ],
      loading: false,
      dialogVisible: false,
    };
  },
  created() {
    this.editorConfig.placeholder = "请输入使用说明内容...";
    const uploadConfig = {
      // 自定义图片上传
      async customUpload(file, insertFn) {
        let formData = new FormData();
        formData.append("file", file);
        // localFileUpload
        axios
          .post(config.proxy + "/admin-api/file/uploadImg", formData, {
            headers: {
              "Content-Type": "application/json;charset=utf-8",
              Authorization: "Bearer " + localStorage.getItem("Authorization"),
            },
          })
          .then((response) => {
            console.log(response);
            if (response.data.code != 200) {
              this.$message.error(response.data.msg);
              return;
            } else {
              const url = response.data.data;
              // 插入图片
              insertFn(url);
            }
          })
          .catch(() => {});
      },
    };
    // 图片配置设置
    this.editorConfig.MENU_CONF["uploadImage"] = uploadConfig;
    // 视频配置设置
    this.editorConfig.MENU_CONF["uploadVideo"] = uploadConfig;
  },
  mounted() {
    this.searchForm.manualId = this.$route.query.id;
    this.init();
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.$nextTick(() => {
          this.content = "";
          this.messageForm.title = "";
          this.messageForm.sort = "";
          this.messageForm.id = "";
          const editor = this.editor;
          if (editor == null) return;
          editor.destroy(); // 组件销毁时，及时销毁编辑器
        });
      }
    },
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错

      if (this.type == "view") {
        this.editor.disable();
      } else {
        this.editor.enable();
      }
    },
    init() {
      this.loading = true;

      contentList({
        ...this.searchForm,
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
      })
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.data.list;
            this.pagination.total = res.data.total;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    jumpPage() {
      this.init();
    },

    addHandle() {
      this.type = "add";
      this.dialogVisible = true;
    },
    addContent() {
      contentAdd({
        title: this.messageForm.title,
        sort: this.messageForm.sort,
        content: this.content,
        manualId: this.$route.query.id,
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("新增成功");
            this.dialogVisible = false;
            this.init();
          } else {
            this.$message.warning(res.msg || "新增失败");
          }
        })
        .catch(() => {});
    },
    editContent() {
      contentEdit({
        title: this.messageForm.title,
        sort: this.messageForm.sort,
        content: this.content,
        manualId: this.$route.query.id,
        id: this.messageForm.id,
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("编辑成功");
            this.dialogVisible = false;
            this.init();
          } else {
            this.$message.warning(res.msg || "编辑失败");
          }
        })
        .catch(() => {});
    },
    contentConfirm() {
      this.$refs.messageForm.validate((valid) => {
        if (valid) {
          if (this.content) {
            if (this.type == "add") {
              this.addContent();
            } else {
              this.editContent();
            }
          } else {
            this.$message.error("请输入内容");
          }
        }
      });
    },
    delFlagHandle(row) {
      contentEnable(row.id)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("操作成功");
            this.init();
          } else {
            this.$message.warning(res.msg || "操作失败");
          }
        })
        .catch(() => {});
    },
    view(row) {
      this.type = "view";
      this.dialogVisible = true;
      this.messageForm.title = row.title;
      this.messageForm.sort = row.sort;
      this.messageForm.id = row.id;
      this.content = row.content;
    },
    edit(row) {
      this.type = "edit";
      this.dialogVisible = true;
      this.messageForm.title = row.title;
      this.messageForm.sort = row.sort;
      this.messageForm.id = row.id;
      this.content = row.content;
    },
  },
};
</script>

<style scoped>
.ins-content {
  margin-bottom: 20px;
  text-align: right;
}
.editorDialog >>> .el-dialog__body {
  padding-top: 0px;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>
