<template>
  <div class="common-box">
    <!--条件-->
    <el-form :model="listQuery" ref="queryForm" :inline="true">
      <el-form-item label="公告标题">
        <el-input
          v-model="listQuery.msgTitle"
          placeholder="请输入公告标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="公告类型">
        <el-select
          v-model="listQuery.msgType"
          placeholder="请选择公告类型"
          clearable
        >
          <el-option
            v-for="item in typeList"
            :key="item.dicCode"
            :label="item.dicVal"
            :value="item.dicCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getData('search')"> 查询 </el-button>
        <el-button @click="reset()">重置</el-button>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button
          type="primary"
          class="lake-Blue"
          icon="el-icon-plus"
          @click="handleAddOrEdit(0, null, 'create')"
        >
          新增
        </el-button>
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane
        :label="item.label"
        :name="item.id"
        v-for="item in tabs"
        :key="item.id"
      >
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="加载中"
          fit
          stripe
          border
        >
          <template slot="empty">
            <img src="@/assets/nopage.png" alt />
            <p>暂无数据</p>
          </template>
          <el-table-column
            fixed
            type="index"
            label="序号"
            width="60"
          ></el-table-column>
          <el-table-column label="公告标题" prop="msgTitle" />
          <el-table-column label="公告类型" width="200">
            <template slot-scope="scope">{{
              reversedMessage(scope.row.msgType)
            }}</template>
          </el-table-column>
          <el-table-column label="发布者" width="200" prop="msgPubdUser" />
          <el-table-column
            v-if="activeName == '1'"
            label="发布时间"
            width="200"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.msgPubdTime | formatDate }}</span>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                v-if="activeName == '0'"
                class="cyan"
                :disabled="scope.row.state === 'deleted'"
                type="text"
                @click="handleAddOrEdit(scope.$index, scope.row, 'update')"
                >编辑
              </el-button>

              <el-button
                class="red"
                :disabled="scope.row.state === 'deleted'"
                type="text"
                @click="handleDelete(scope.row, 'deleted')"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <yl-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.current"
          :limit.sync="listQuery.size"
          @pagination="getData"
        />
      </el-tab-pane>
    </el-tabs>

    <!--添加/修改-->
    <el-dialog
      v-if="dialogFormVisible"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="1300px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="msgTitle">
              <el-input v-model.trim="temp.msgTitle" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分类" prop="msgType">
              <el-select
                v-model="temp.msgType"
                placeholder="请选择分类"
                style="width: 100%"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.dicCode"
                  :label="item.dicVal"
                  :value="item.dicCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布者">
              <el-input v-model.trim="temp.msgPubder" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="发送给">
          <!-- :disabled="noticeDetail.msgStas == 1" -->
          <el-radio-group v-model="temp.forAll">
            <el-radio label="1">全部用户</el-radio>
            <el-radio label="0">部分用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="接收用户" v-if="temp.forAll == 0">
          <div class="textarea-box">
            <el-tooltip
              :content="tag.id"
              placement="bottom"
              effect="light"
              :key="tag.id"
              v-for="tag in temp.receiveUser"
              popper-class="notice-testtooltip"
              open-delay="500"
            >
              <!-- :closable="noticeDetail.msgStas != 1" -->
              <el-tag
                closable
                @close="handleUsersClose(tag)"
                style="margin-right: 5px"
              >
                {{ tag.name }}
              </el-tag>
            </el-tooltip>
          </div>
          <!-- :disabled="noticeDetail.msgStas == 1" -->
          <el-button type="primary" icon="el-icon-plus" @click="chooseUsers"
            >选择</el-button
          >
        </el-form-item>
        <el-form-item label="接收角色" v-if="temp.forAll == 0">
          <div class="textarea-box">
            <el-tooltip
              :content="tag.id"
              placement="bottom"
              effect="light"
              :key="tag.id"
              v-for="tag in temp.receiveRole"
              popper-class="notice-testtooltip"
              open-delay="500"
            >
              <!-- :closable="noticeDetail.msgStas != 1" -->
              <el-tag
                closable
                @close="handleRolesClose(tag)"
                style="margin-right: 5px"
              >
                {{ tag.name }}
              </el-tag>
            </el-tooltip>
          </div>
          <!-- :disabled="noticeDetail.msgStas == 1" -->
          <el-button type="primary" icon="el-icon-plus" @click="chooseRoles"
            >选择</el-button
          >
        </el-form-item>
        <el-form-item label="内容">
          <div class="editor-css" style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="temp.mainText"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="success"
          @click="commitData(0)"
          v-if="
            (dialogStatus == 'update' && noticeDetail.msgStas == 0) ||
            dialogStatus == 'create'
          "
          :loading="btLoading1"
          >{{ btLoading1 ? "保存中" : "保存" }}</el-button
        >
        <el-button
          type="primary"
          @click="commitData(1)"
          :loading="btLoading2"
          >{{ btLoading2 ? "发布中" : "发布" }}</el-button
        >
      </div>
    </el-dialog>

    <!--添加接收用户-->
    <el-dialog
      v-if="dialogUsersFormVisible"
      title="选择接收用户"
      :visible.sync="dialogUsersFormVisible"
      width="1300px"
    >
      <users
        :checkUser="temp.receiveUser"
        @usersClose="usersClose"
        @usersSubmit="usersSubmit"
      ></users>
    </el-dialog>

    <!--添加接收角色-->
    <el-dialog
      v-if="dialogRolesFormVisible"
      title="选择接收角色"
      :visible.sync="dialogRolesFormVisible"
      width="1300px"
    >
      <roles
        :checkRole="temp.receiveRole"
        @rolesClose="rolesClose"
        @rolesSubmit="rolesSubmit"
      ></roles>
    </el-dialog>
  </div>
</template>

<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
  addNotice,
  getNotice,
  delNotice,
  editNotice,
  getNoticeDetail
} from "@/api/system/notice";
import { getQueryDic } from "@/api/system/dic";
import users from "@/views/page/system/notice/components/users";
import roles from "@/views/page/system/notice/components/roles";
import ylPagination from "@/components/yl-pagination";
import moment from "moment";
export default {
  components: { Editor, Toolbar, ylPagination, users, roles },
  data() {
    return {
      btLoading1: false,
      btLoading2: false,
      // 公告详情
      noticeDetail: {},
      dialogUsersFormVisible: false,
      dialogRolesFormVisible: false,
      // 公告分类
      typeList: [
        {
          dicCode: "notice",

          dicVal: "公告"
        },
        {
          dicCode: "policyDoc",

          dicVal: "政策文件"
        }
      ],
      activeName: "0",
      listLoading: false,
      list: null, //列表
      total: 0, //分页
      listQuery: {
        //条件查询
        current: 1,
        size: 10,
        msgTitle: "",
        msgType: "",
        msgStas: 0
      },
      textMap: {
        update: "编辑",
        create: "添加"
      },
      //   tab栏
      tabs: [
        {
          id: "0",
          label: "未发布"
        },
        {
          id: "1",
          label: "已发布"
        }
      ],
      dialogFormVisible: false, //是否对话框
      dialogStatus: "",
      temp: {},
      rules: {
        msgType: [
          {
            required: true,
            message: "请选择分类",
            trigger: "change"
          }
        ],
        msgTitle: [
          {
            required: true,
            message: "标题不能为空",
            trigger: "blur"
          }
        ]
      },
      //   富文本编辑器
      editor: null,
      toolbarConfig: {
        excludeKeys: ["group-video", "codeBlock", "undo", "redo", "emotion"]
      },
      editorConfig: {
        placeholder: "请输入内容...",
        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          // 配置上传图片
          uploadImage: {
            customUpload: this.update,
            base64LimitSize: 1024 * 1024 // 5*1024 = 5kb
          }
          // 继续其他菜单配置...
        }
      },
      mode: "default" // or 'simple'
    };
  },

  filters: {
    formatDate(status) {
      if (status) {
        var time = moment(time).format("YYYY-MM-DD HH:mm:ss");
      }
      return time;
    }
  },

  created() {
    // this.getNoticeType();
    this.getData();
  },

  mounted() {},

  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },

  methods: {
    reversedMessage(val) {
      let newVal = this.typeList.find((item) => {
        return item.dicCode == val;
      });
      if (newVal) {
        return newVal.dicVal;
      }
    },
    // 删除用户标签
    handleUsersClose(tag) {
      this.temp.receiveUser.splice(this.temp.receiveUser.indexOf(tag), 1);
    },

    // 删除角色标签
    handleRolesClose(tag) {
      this.temp.receiveRole.splice(this.temp.receiveRole.indexOf(tag), 1);
    },

    // 获取到选中的用户
    usersSubmit(item) {
      this.temp.receiveUser = item;
      this.dialogUsersFormVisible = false;
    },

    // 获取到选中的用户
    rolesSubmit(item) {
      this.temp.receiveRole = item;
      this.dialogRolesFormVisible = false;
    },

    // 关闭用户对话框
    usersClose() {
      this.dialogUsersFormVisible = false;
    },

    // 关闭角色对话框
    rolesClose() {
      this.dialogRolesFormVisible = false;
    },

    // 选择用户对话框
    chooseUsers() {
      this.dialogUsersFormVisible = true;
    },

    // 选择角色对话框
    chooseRoles() {
      this.dialogRolesFormVisible = true;
    },

    // 获取公告分类
    getNoticeType() {
      getQueryDic({ dicCode: "noticeType" }).then((response) => {
        this.typeList = response.data;
      });
    },

    // 上传图片
    update(file, insertFn) {
      this.$message({
        message: "上传图片不能超过1MB！",
        type: "warning"
      });
      // file 即选中的文件
      // 自己实现上传，并得到图片 url alt href
      // let name = md5(file.name);
      // let suffix = file.type.split("/")[1];
      // name = name + "." + suffix;
      // uploadFile(name, file).then((res) => {
      //   if (res.statusCode == 200) {
      //     // 最后插入图片
      //     insertFn(
      //       "http://" + res.Location,
      //       file.name,
      //       "http://" + res.Location
      //     );
      //   } else {
      //   }
      // });
    },

    // 富文本编辑器
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },

    // tab栏跳转
    handleClick(tab, event) {
      this.activeName = tab.name;
      this.listQuery.current = 1;
      this.list = [];
      if (this.activeName == 0) {
        this.listQuery.msgStas = 0;
      } else {
        this.listQuery.msgStas = 1;
      }
      this.getData();
    },

    // 重置页面
    reset() {
      this.listQuery.msgType = "";
      this.listQuery.msgTitle = "";
      this.getData();
    },

    //获取列表数据
    getData(type) {
      if (type == "search") {
        this.listQuery.current = 1;
      }
      this.listLoading = true;
      getNotice(this.listQuery)
        .then((response) => {
          this.list = response.data.records;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },

    //提交表单数据
    commitData(type) {
      if (this.temp.forAll == "1") {
        delete this.temp.receiveUser;
        delete this.temp.receiveRole;
      } else {
        if (this.temp.receiveUser.length == 0 && this.temp.receiveRole == 0) {
          this.$message({
            message: "请选择接收用户或者角色",
            type: "warning"
          });
          return false;
        }
      }
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            if (type == "0") {
              this.btLoading1 = true;
            }
            if (type == "1") {
              this.btLoading2 = true;
            }

            this.temp.msgStas = type;
            if (this.dialogStatus === "create") {
              addNotice(this.temp)
                .then((response) => {
                  this.$message({
                    message: "操作成功",
                    type: "success"
                  });
                  this.btLoading1 = false;
                  this.btLoading2 = false;
                  this.dialogFormVisible = false;
                  this.getData();
                })
                .catch(() => {
                  this.btLoading1 = false;
                  this.btLoading2 = false;
                });
            } else {
              editNotice(this.temp)
                .then((response) => {
                  this.$message({
                    message: "操作成功",
                    type: "success"
                  });
                  this.btLoading1 = false;
                  this.btLoading2 = false;
                  this.dialogFormVisible = false;
                  this.getData();
                })
                .catch(() => {
                  this.btLoading1 = false;
                  this.btLoading2 = false;
                });
            }
          });
        }
      });
    },

    // 打开添加/修改对话框
    handleAddOrEdit(index, row, type) {
      this.temp = {};
      this.noticeDetail = {};
      //修改对话框
      if (type === "update") {
        getNoticeDetail({ id: row.id })
          .then((response) => {
            this.noticeDetail = response.data;
            this.temp = {
              id: row.id,
              msgTitle: this.noticeDetail.msgTitle,
              mainText: this.noticeDetail.mainText,
              msgType: this.noticeDetail.msgType,
              msgPubder: this.noticeDetail.msgPubdUser,
              forAll: this.noticeDetail.forAll + "",
              receiveUser: this.noticeDetail.receiveUser,
              receiveRole: this.noticeDetail.receiveRole
            };
          })
          .catch((err) => {});
      } else {
        this.temp = {
          id: "",
          msgTitle: "",
          msgType: "",
          msgPubder: "",
          mainText: "",
          receiveUser: [],
          receiveRole: [],
          forAll: "1"
        };
      }
      this.dialogStatus = type;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    //删除
    handleDelete(row, status) {
      this.$confirm("确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.temp = {
          msgIds: [row.id]
        };
        delNotice(this.temp).then((response) => {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          // 解决element el-pagination分页最后一页数据清空了页码显示正确，但是列表为空
          const totalPage = Math.ceil((this.total - 1) / this.listQuery.size);
          const currentPage =
            this.listQuery.current > totalPage
              ? totalPage
              : this.listQuery.current;
          this.listQuery.current = currentPage < 1 ? 1 : currentPage;
          this.getData();
        });
      });
    }
  }
};
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped type="scss">
.textarea-box {
  float: left;
  box-sizing: border-box;
  border-radius: 4px;
  background-color: #f5f7fa;
  border: 1px solid #dfe4ed;
  color: #c0c4cc;
  padding: 0px 15px;
  width: 1100px;
  min-height: 30px;
  margin-right: 5px;
}
</style>