<template>
  <div>
    <div class="search-wrapper">
      <el-form
        :inline="true"
        :model="searchForm"
        class="search_form"
        style="text-align: left"
      >
        <el-form-item label="资讯标题">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入资讯标题"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="searchForm.categoryId"
            placeholder="请选择通知类型"
            clearable
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="(item, index) in categoryList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="addHandle">添加便民通知</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-wrapper">
      <table-template
        :tableData="tableData"
        :tableColumns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        @Jump="jumpPage"
      >
        <el-table-column slot="onLine" label="启用状态" align="center">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.onLine == 0 || scope.row.onLine == 1"
              :type="
                scope.row.onLine == 1
                  ? 'danger'
                  : scope.row.onLine == 0
                  ? 'success'
                  : ''
              "
              >{{ scope.row.onLine == 0 ? "在线" : "下线" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column slot="state" label="审核状态" align="center">
          <template slot-scope="scope">
            <el-tag
              v-if="
                scope.row.state == 0 ||
                scope.row.state == 1 ||
                scope.row.state == 4
              "
              :type="
                scope.row.state == 4
                  ? 'warning'
                  : scope.row.state == 1
                  ? 'success'
                  : 'primary'
              "
              >{{
                scope.row.state == 0
                  ? "未审核"
                  : scope.row.state == 1
                  ? "通过"
                  : "驳回"
              }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="350" align="center">
          <template slot-scope="scope">
            <!-- <el-button
              @click="delFlagHandle(scope.row)"
              :type="scope.row.onLine == 0 ? 'warning' : 'success'"
              size="mini"
              round
              slot="reference"
              >{{ scope.row.onLine == 0 ? "下线" : "上线" }}
            </el-button> -->
            <el-button type="primary" size="mini" round @click="view(scope.row)"
              >查看</el-button
            >
            <el-button
              type="success"
              size="mini"
              round
              @click="edit(scope.row)"
              v-if="scope.row.userId == userId"
              >编辑</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
        :inline="true"
        :model="messageForm"
        ref="messageForm"
        :rules="rules"
      >
        <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="categoryId">
          <el-select
            v-model="messageForm.categoryId"
            placeholder="请选择通知类型"
            clearable
            :disabled="type === 'view'"
            style="width: 300px"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="(item, index) in categoryList"
              :key="index"
            ></el-option>
          </el-select>
        </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="infoConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TableTemplate from "@/components/Table";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { config } from "@/utils/request.js";

import axios from "axios";
import {
  infoList,
  infoAdd,
  infoDetail,
  menuCategoryList,
  infoEdit,
  infoEnable,
} from "@/api/info";
export default {
  components: { TableTemplate, Editor, Toolbar },
  data() {
    return {
      searchForm: {
        title: "",
        categoryId: "",
      },
      tableData: [],
      tableColumns: [
        {
          key: "title",
          label: "标题",
        },
        {
          key: "categoryName",
          label: "类型",
        },
        {
          key: "onLine",
          label: "启用状态",
          type: "slot",
        },
        {
          key: "state",
          label: "审核状态",
          type: "slot",
        },

        {
          key: "createTime",
          label: "创建时间",
        },
      ],
      pagination: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      loading: false,
      dialogVisible: false,
      messageForm: {
        title: "",
        categoryId: "",
        id: "",
      },
      menuId: 106,
      categoryList: [],
      type: "add",
      editor: null,
      content: "",
      toolbarConfig: {},
      editorConfig: { placeholder: "请输入内容...", MENU_CONF: {} },
      mode: "default", // or 'simple'
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        categoryId: [
          { required: true, message: "请选择类型", trigger: "blur" },
        ],
      },
      userId: 0,
    };
  },
  mounted() {
    this.userId = localStorage.getItem("userId");
    this.init();
    menuCategoryList(this.menuId).then((res) => {
      if (res.code == 200) {
        this.categoryList = res.data;
      }
    });
  },

  watch: {
    dialogVisible(val) {
      if (!val) {
        this.$nextTick(() => {
          this.content = "";
          this.messageForm.title = "";
          this.messageForm.categoryId = "";
          const editor = this.editor;
          if (editor == null) return;
          editor.destroy(); // 组件销毁时，及时销毁编辑器
        });
      }
    },
  },
  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/localFileUpload", 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;
  },

  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
      console.log("onCreated");
      if (this.type == "view") {
        this.editor.disable();
      } else {
        this.editor.enable();
      }
    },

    onSubmit() {
      this.init();
    },
    jumpPage() {
      this.init();
    },
    addHandle() {
      this.type = "add";
      this.dialogVisible = true;
    },
    init() {
      this.loading = true;
      infoList({
        menuId: this.menuId,
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        title: this.searchForm.title,
        categoryId: this.searchForm.categoryId,
      })
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.data.list;
            this.pagination.total = res.data.total;
          } else {
            this.$message.warning(res.msg || "查询失败");
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    delFlagHandle(row) {
      infoEnable(row.id).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.msg || "操作成功");
          this.init();
        } else {
          this.$message.warning(res.msg || "操作失败");
        }
      });
    },
    edit(row) {
      this.type = "edit";
      infoDetail(row.id).then((res) => {
        if (res.code == 200) {
          this.messageForm = res.data;
          this.content = res.data.content;
          this.messageForm.title = res.data.title;
          this.messageForm.categoryId = res.data.categoryId;
        }
      });
      this.dialogVisible = true;
    },
    view(row) {
      this.type = "view";

      infoDetail(row.id).then((res) => {
        if (res.code == 200) {
          this.$nextTick(() => {
            this.messageForm = res.data;
            this.content = res.data.content;

            this.messageForm.title = res.data.title;
            this.messageForm.categoryId = res.data.categoryId;
          });
        }
      });
      this.dialogVisible = true;
    },
    infoConfirm() {
      this.$refs.messageForm.validate((valid) => {
        if (!valid) return;
        let params = {
          content: this.content,
          introduction: "",
          title: this.messageForm.title,
          user: localStorage.getItem("userName"),
          categoryId: this.messageForm.categoryId,
        };
        if (this.type === "add") {
          infoAdd(params).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.msg || "添加成功");
              this.dialogVisible = false;
              this.init();
            }
          });
        } else {
          params.id = this.messageForm.id;
          infoEdit(params).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.msg || "编辑成功");
              this.dialogVisible = false;
              this.init();
            } else {
              this.$message.warning(res.msg || "编辑失败");
            }
          });
        }
      });
    },
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
};
</script>

<style lang="stylus" scoped>
@import '~@/stylus/common';
.btn{
    margin-right: 10px;
};
.edit{
    height: 500px;
    margin-bottom: 20px;

}
.editorDialog >>>.el-dialog__body{
    padding-top:0px ;
  }
</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>
