<template>
  <!-- 公告信息 -->
  <div class="content-container">
    <el-row class="search">
      <el-col :span="5" class="left-box">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText"
          size="small"
          clearable
        ></el-input>
        <el-tree
          class="filter-tree"
          :data="data"
          :props="defaultProps"
          default-expand-all
          node-key="id"
          :filter-node-method="filterNode"
          highlight-current
          :current-node-key="111"
          @node-click="nodeClick"
          :expand-on-click-node="false"
          ref="tree"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span> {{ node.label }}</span>
            <span>
              <el-button
                v-if="data.rank == 0"
                type="text"
                size="mini"
                icon="el-icon-circle-plus-outline"
                @click="opendialog(data, 1)"
              ></el-button>

              <el-button
                v-if="data.rank != 0"
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="opendialog(data, 2)"
              ></el-button>
              <el-button
                v-if="data.rank != 0"
                type="text"
                size="mini"
                icon="el-icon-delete"
                style="color: #f40"
                @click="deleteBasetype(data)"
              ></el-button>
            </span>
          </span>
        </el-tree>
      </el-col>
      <el-col :span="19" class="right-box">
        <div class="top">
          <el-form
            ref="form"
            :inline="true"
            label-width="auto"
            :model="form"
            style="float: left; height: 45px"
          >
            <el-form-item label="公告名称">
              <el-input
                v-model="form.theme"
                size="small"
                placeholder="请输入公告名称"
                style="width: 260px"
              ></el-input>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="getNoticePage()"
                size="small"
                style="height: 30px"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>

          <el-button
            type="primary"
            @click="addNoticeInfo"
            size="small"
            icon="el-icon-plus"
            style="height: 30px"
            >新增</el-button
          >
          <!-- <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="editDialogVisible = true"
            style="height: 30px"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            style="height: 30px"
            >删除</el-button
          > -->
        </div>
        <div class="table-div">
          <el-table
            :data="tableData"
            :style="{ width: '100%' }"
            height="100%"
            stripe
            border
            :header-cell-style="{
              background: 'rgba(250,250,250)',
              color: 'rgb(50,59,65)',
              height: '38px',
              textAlign: 'center',
            }"
          >
            <template slot="empty">
              <img src="@/assets/icon/null.png" alt="" />
              <p class="empty-p">暂无数据</p>
            </template>
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="50"
            ></el-table-column>
            <!-- <el-table-column
              prop="id"
              label="编码"
              align="center"
            ></el-table-column> -->
            <el-table-column
              prop="theme"
              label="公告名称"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="folderName"
              label="公告分区"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="documentStateName"
              label="是否发布"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="createUserName"
              label="创建人"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="content"
              label="公告内容"
              width="160"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  @click="queryDetail(scope.row)"
                  type="text"
                  size="small"
                  >详细</el-button
                >
                <el-button
                  v-if="scope.row.documentState === 0"
                  @click="deleteNotice(scope.row)"
                  type="text"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          :current-page="pagination.current"
          :page-sizes="[20, 30, 40, 50, 100, 200]"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-col>
    </el-row>

    <!-- 新增文档 -->
    <el-dialog
      title="新增文档"
      :visible.sync="dialogFormVisible"
      label-width="auto"
      width="35%"
    >
      <el-form ref="folderForm" :model="folderForm" label-width="auto">
        <el-form-item label="分区名称:" prop="folderName">
          <el-input
            v-model="folderForm.folderName"
            placeholder="请输入分区名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFolder()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增公告 -->
    <el-dialog
      title="新增公告"
      :visible.sync="newDialogVisible"
      label-width="auto"
      destroy-on-close
      width="30%"
    >
      <el-form
        ref="noticeForm"
        :model="noticeForm"
        :rules="rules"
        label-width="auto"
        size="mini"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="公告名称:" prop="theme">
              <el-input
                v-model="noticeForm.theme"
                maxlength="20"
                placeholder="请输入内容"
                :disabled="optionType == 0"
                size="small"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="公告内容:" prop="content">
              <el-input
                v-model="noticeForm.content"
                type="textarea"
                :rows="2"
                :disabled="optionType == 0"
                placeholder="请输入内容"
                size="small"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-row :gutter="24">
              <el-col
                v-for="(file, index) in existsFiles"
                :key="index"
                class="tf-col"
                :span="8"
              >
                <div class="file">
                  <div
                    class="file-name"
                    @click="downloadFile(file)"
                    :style="optionType != 0 ? '' : 'width:100%;'"
                  >
                    {{ file.fileName }}
                  </div>
                  <div
                    v-if="optionType != 0"
                    class="btn-file"
                    @click="deleteFile(file)"
                  >
                    x
                  </div>
                </div>
              </el-col>
            </el-row>
            <upload
              ref="upload"
              :files="files"
              v-if="optionType == 0 ? false : true"
            ></upload>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button v-if="optionType != 0" type="primary" @click="commitNotice"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 新建分区 -->
    <el-dialog
      title="新建分区"
      :visible.sync="diamDialogVisible"
      label-width="auto"
      width="25%"
    >
      <el-form :model="form" label-width="auto" size="mini">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="分区名称:">
              <el-input v-model="input" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分区类型:">
              <el-input v-model="input" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="diamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="diamDialogVisible = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑公告 -->
    <el-dialog
      title="编辑公告"
      custom-class="custom-dialog"
      :visible.sync="editDialogVisible"
      width="96%"
    >
      <el-form ref="form" :model="sizeForm" label-width="100px" size="mini">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="标题:" required>
              <el-input v-model="sizeForm.theme"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="概要:">
              <el-input v-model="sizeForm.outline"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公告分区:">
              <el-input v-model="sizeForm.moduleType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否发布:" required>
              <el-input v-model="sizeForm.isRelease"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="链接地址:">
              <el-input v-model="sizeForm.linkUrl"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="txt" id="editor">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="sizeForm.content"
            :autosize="{ minRows: 12 }"
          >
          </el-input>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="releaseClick">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getListByPage,
  portalmoduleApi,
  getfolderTree,
  addfolderApi,
  editfolderApi,
  deleteFolder,
  getNoticeById,
  getNoticePage,
  addNotice,
  editNotice,
  deleteNotice,
} from "@/api/mbsys/collaborative";
import upload from "@/views/mbsys/components/upload.vue";
import { getFiles } from "@/api/base";
export default {
  components: { upload },
  data() {
    return {
      data: [
        {
          id: 0,
          folderName: "公告分区",
          rank: 0,
          fts: [],
        },
      ],
      defaultProps: {
        children: "fts",
        label: "folderName",
      },
      fileList: [],
      files: [], //上传附件
      existsFiles: [], //已上传附件
      form: {
        content: "",
      },
      limit: 5, //限制文件个数
      maxFileSize: 10, //最大文件大小
      optionType: 0, //操作类型 0:查看,1:新增,2:修改
      formFiles: [],
      noticeForm: {
        documentType: -1, //当前选中结点ID,文档类型
        documentState: 0, //状态0:草稿、1:提交(发布
        degreeSecrets: 1, //密级
        degreeUrgency: 1, //紧急程度
        fontSize: 14, //字号
        theme: "", //公告名称
        content: "", //公告内容
      },
      // 增加文档输入框
      input: "",
      tableData: [],
      pagination: { current: 1, size: 40, total: 0 },
      dialogFormVisible: false,
      newDialogVisible: false,
      diamDialogVisible: false,
      editDialogVisible: false,
      options: [],
      filterText: "",
      textarea: "",
      startDate: "",
      sizeForm: {
        theme: "",
        outline: "",
        moduleFunction: 1,
        moduleType: 1,
        isRelease: 1,
        linkUrl: "",
        content: "",
        remark: "", // 备注
      },
      documentStates: [
        { key: 0, value: "未发布" },
        { key: 1, value: "已发布" },
      ],
      value2: [],
      value1: "",
      folderForm: { dataType: 0, moduleType: 1, folderName: "" },
      opType: null,
      noticeType: [],
      rules: {
        theme: [{ required: true, message: "填写公告名称" }],
        content: [{ required: true, message: "填写公告内容" }],
      },
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getfolderTree();
    this.getNoticePage();
  },
  methods: {
    formatData(data, rank) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].fts.length < 1) {
          data[i].fts = undefined;
          data[i]["rank"] = rank + 1;
        } else {
          this.formatData(data[i].fts, rank + 1);
          data[i]["rank"] = rank + 1;
        }
      }
      return data;
    },
    // 获取树形控件的数据
    getfolderTree() {
      getfolderTree({ moduleType: 1 }).then((res) => {
        if (res.result.foldes.length > 0) {
          this.data[0].fts = this.formatData(res.result.foldes[0].fts, 0);
          this.noticeType = this.data[0].fts;
        } else {
          this.data[0].fts = [];
        }
      });
    },

    /* 
      添加文档
    */
    submitFolder() {
      this.$refs.folderForm.validate((valid) => {
        if (valid) {
          if (this.opType == 1) this.addfolderApi();
          else this.editfolderApi();
        } else {
          return false;
        }
      });
    },

    /**
     * 新增分区
     */
    addfolderApi() {
      addfolderApi(this.folderForm).then((res) => {
        if (res.code == 1) {
          this.getfolderTree();
          this.dialogFormVisible = false;
          this.$message.success("添加文档成功");
        }
      });
    },
    /**
     * 编辑文件夹
     */
    editfolderApi() {
      editfolderApi(this.folderForm).then((res) => {
        if (res.code == 1) {
          this.getfolderTree();
          this.dialogFormVisible = false;
          this.$message.success("编辑文档成功");
        }
      });
    },
    /* 
      删除文件夹
    */
    deleteBasetype(data) {
      this.$confirm("删除该类型?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteFolder(data.id).then((res) => {
            if (res.code == 1) {
              this.$message.success("删除成功");
              this.getfolderTree();
            }
          });
        })
        .catch(() => {});
    },
    /* 
      添加文档
    */
    addNoticeInfo() {
      this.optionType = 1;
      this.existsFiles = [];
      this.noticeForm.theme = "";
      this.noticeForm.content = "";
      //  {
      //   documentType: -1, //当前选中结点ID,文档类型
      //   documentState: 0, //状态0:草稿、1:提交(发布
      //   degreeSecrets: 1, //密级
      //   degreeUrgency: 1, //紧急程度
      //   fontSize: 14, //字号
      //   theme: "", //公告名称
      //   content: "", //公告内容
      // },
      if (this.noticeForm.documentType > 0) {
        this.newDialogVisible = true;
      } else {
        this.$message.warning("请先选择分区");
      }
    },
    cancelFn() {
      this.newDialogVisible = false;
      this.optionType = 1;
    },

    // 文章发布点击确定
    releaseClick() {
      portalmoduleApi(this.sizeForm).then((res) => {
        console.log("luo999", res);
      });
      this.editDialogVisible = false;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.folderName.indexOf(value) !== -1;
    },
    // 点击节点时
    nodeClick(data, node, self) {
      //记录当前ID
      this.noticeForm.documentType = data.id;
      //根据id分页查询
      this.getNoticePage();
    },

    /**
     * 分页查询公告
     */
    getNoticePage() {
      let param = Object.assign({}, this.pagination); //{ current: 1, size: 40, total: 0 }
      // Object.assign(param, {
      //   moduleType: 1,
      // });
      if (this.noticeForm.documentType > 0) {
        Object.assign(param, { documentType: this.noticeForm.documentType });
      }
      if (this.form.theme != "")
        Object.assign(param, { theme: this.form.theme });
      console.log("参数", param);
      getNoticePage(param).then((res) => {
        if (res.code == 1) {
          let tableData = res.result.records;
          this.pagination.total = res.result.total;
          tableData.forEach((item) => {
            const obj = this.noticeType.find((o) => o.id == item.documentType);
            if (obj) item["folderName"] = obj.folderName;
            item["documentStateName"] = item.hasOwnProperty("documentState")
              ? item.documentState == 0
                ? "未发布"
                : "已发布"
              : "未发布";
          });
          this.tableData = tableData;
          console.log(this.tableData);
        }
      });
    },

    //提交公告
    commitNotice() {
      let flag = false;
      this.$refs["noticeForm"].validate((valid) => {
        flag = valid;
        if (valid) {
          return true;
        } else {
          return false;
        }
      });
      if (flag) {
        let params = this.noticeForm;
        let formData = new FormData();
        this.optionType = 1;
        for (let param in params) {
          formData.append(param, params[param]);
        }
        //文件
        this.formFiles.forEach((file, index) => {
          formData.append("fileList", file.file);
        });
        addNotice(formData)
          .then((res) => {
            if (res.code == 1) {
              this.newDialogVisible = false;
              this.getNoticePage();
              this.$message.success("新增成功!");
            }
          })
          .catch((ex) => {
            this.$message.error("操作出错!");
          })
          .finally(() => {
            this.newDialogVisible = false;
          });
      }
    },
    /**
     * 添加分区
     */
    append() {
      this.diamDialogVisible = true;
    },

    //删除
    deleteNotice(row) {
      console.log(row);
      this.$confirm("确定删除该公告?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteNotice(row.id).then((res) => {
            if (res.code == 1) {
              this.$message.success("删除成功");
              this.getNoticePage();
            }
          });
        })
        .catch(() => {});
    },

    //查询公告详情
    queryDetail(row) {
      this.newDialogVisible = true;
      this.optionType = 0;
      this.existsFiles = [];
      getNoticeById(row.id).then((res) => {
        console.log("公告详情", res.result);
        let {
          documentType,
          documentState,
          degreeUrgency,
          fontSize,
          theme,
          content,
        } = res.result;
        this.noticeForm = {
          documentType,
          documentState,
          degreeUrgency,
          fontSize,
          theme,
          content,
        };
        //附件
        if (res.result.hasOwnProperty("files")) {
          const files = res.result.files;
          if (files) {
            files.forEach((file) => {
              this.existsFiles.push(file);
            });
          }
        }
      });
    },
    /* 
    打开对话框
   */
    opendialog(data, opType) {
      this.opType = opType;
      if (opType == 1) {
        if (data.id == 0) {
          this.folderForm = { dataType: 0 };
        } else {
          this.folderForm = { dataType: 0, parentId: data.id };
        }
      } else {
        this.folderForm["id"] = data.id;
        this.$set(this.folderForm, "folderName", data.folderName);
      }
      this.folderForm["moduleType"] = 1;

      this.dialogFormVisible = true;
    },
    /**
     * 获取上传的附件
     */ getFiles() {
      return this.$refs["upload"].submitFiles();
    },
    /**
     * 删除文件
     * @file 文件信息
     */
    deleteFile(file) {
      this.$confirm(
        "此操作将永久删除【" + file.fileName + "】文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.existsFiles = this.existsFiles.filter(
            (item) => item.id != file.id
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * 下载文件
     * @file 文件信息
     */ downloadFile(file) {
      if (
        file &&
        file.hasOwnProperty("filePath") &&
        file.hasOwnProperty("fileName")
      ) {
        const token = this.$store.state.user.token;
        const fileName = file.fileName;
        getFiles({
          access_token: token,
          fileName: fileName,
          remotePath: file.filePath,
        }).then((src) => {
          const reader = new FileReader();
          reader.readAsDataURL(src);
          reader.onload = (e) => {
            const a = document.createElement("a");
            a.download = fileName;
            // 后端设置的文件名称在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",
            a.href = e.target.result;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
          };
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.content-container {
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  position: absolute;
  top: 43px;
  bottom: 0;
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .filter-tree {
    margin-top: 10px;
  }

  .el-row {
    width: 100%;
    height: 100%;

    .left-box {
      height: 100%;
      border-right: 1px solid #ebeef5;
      overflow-y: auto;
      box-sizing: border-box;
      padding-right: 10px;
    }

    .right-box {
      height: 100%;
      overflow-y: auto;
      box-sizing: border-box;
      padding: 0 15px;

      .top {
        height: 33px;
        text-align: right;

        .upload-demo {
          display: inline-block;
        }
      }

      .table-div {
        height: calc(100% - 81px);
      }

      .el-pagination {
        margin-top: 16px;
      }
    }
  }
}

.custom-dialog {
  background-color: #f3f3f3;
}
</style>