<template>
  <div style="width: 100%">
    <el-main>
      <div class="tou">发现管理</div>
      <div>
        <div class="bbox">
          <el-button size="small" type="primary" style="" @click="insertPop"
            >添加文章</el-button
          >
        </div>
        <el-table
          ref="table"
          v-loading="isLoading"
          :data="tableData"
          stripe
          border
          :header-cell-style="{ background: '#f1f1f1', 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          style="width: 100%; margin-top: 15px"
          :height="tableHeight"
        >
          <el-table-column
            prop="title"
            label="文章标题"
            min-width="35"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column prop="time" label="创建时间" min-width="15">
          </el-table-column>
          <el-table-column prop="do" label="操作" min-width="20">
            <template slot-scope="scope">
              <div class="pb_buttonBox">
                <el-button
                  size="mini"
                  type="primary"
                  @click="getDetail(scope.row.id)"
                  >查看详情</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  @click="updatePop(scope.row.id, scope.$index)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  @click="deleteFind(scope.row.id)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="student_page">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="10"
          :total="total"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-main>
    <el-dialog
      title="添加文章"
      :visible.sync="dialogVisible1"
      width="500px"
      :before-close="handleClose"
      class="dialog_diyA dialog_diy"
      center
    >
      <div>
        <div class="tian1">
          <span>标题</span>
          <el-input
            v-model="contentTitle"
            style="width: 250px; margin: 15px 0px"
            placeholder="请输入文章标题"
          ></el-input>
        </div>
        <div class="tian1">
          <span>文章海报</span>
          <!-- :on-success="handle_success" -->
          <!-- :before-upload="beforeUpload1" -->
          <el-upload
            action="#"
            list-type="picture"
            style="margin: 15px 0px"
            v-loading="uploadLoading1"
            :http-request="beforeUpload1"
            ref="upload1"
            :on-preview="handlePictureCardPreview"
            :on-remove="handle_remove1"
            :show-file-list="true"
            accept="image/*"
            :file-list="fileList1"
            :limit="1"
          >
            <!-- <i class="el-icon-plus"></i> -->
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
        <div class="tian1">
          <span>文章内容</span>
          <!-- <el-input
            type="textarea"
            rows="10"
            v-model="input"
            style="width: 100%; margin: 15px 0px"
            placeholder="请输入文章内容"
          ></el-input> -->
          <editor-bar
            v-model="detail"
            :isClear="isClear"
            @change="change"
          ></editor-bar>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="addContent">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改文章"
      :visible.sync="dialogVisible3"
      width="500px"
      :before-close="handleClose"
      class="dialog_diyA dialog_diy"
      center
    >
      <div>
        <div class="tian1">
          <span>标题</span>
          <el-input
            v-model="updateJson.title"
            style="width: 250px; margin: 15px 0px"
            placeholder="请输入修改的文章标题"
          ></el-input>
        </div>
        <div class="tian1">
          <span>文章海报</span>
          <!-- :on-success="handle_success" -->
          <!-- :before-upload="beforeUpload1" -->
          <el-upload
            action="#"
            list-type="picture"
            style="margin: 15px 0px"
            v-loading="uploadLoading1"
            :http-request="beforeUpload1"
            ref="upload1"
            :on-preview="handlePictureCardPreview"
            :on-remove="handle_remove1"
            :show-file-list="true"
            accept="image/*"
            :file-list="fileList1"
            :limit="1"
          >
            <!-- <i class="el-icon-plus"></i> -->
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
        <div class="tian1">
          <span>文章内容</span>
          <!-- <el-input
            type="textarea"
            rows="10"
            v-model="input"
            style="width: 100%; margin: 15px 0px"
            placeholder="请输入文章内容"
          ></el-input> -->
          <editor-bar
            v-model="updateJson.content"
            :isClear="isClear"
            @change="change"
          ></editor-bar>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="updateDetail">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="查看详情"
      :visible.sync="dialogVisible2"
      width="50%"
      :before-close="handleClose"
      class="dialog_diyA dialog_diyH dialog_diy"
      height="500px"
      center
    >
      <div>
        <div class="head">
          <span>{{ homeDeatail.title }}</span>
          <span class="name">{{ homeDeatail.time }}</span>
        </div>
        <div class="cont" v-html="homeDeatail.content"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible2 = false"
          >关闭</el-button
        >
      </span>
    </el-dialog>
    <el-dialog :visible.sync="ImageVisible1" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import EditorBar from "../../components/tools/wangEnduit";
import "../../common/aws-sdk-2.235.1.min";

export default {
  components: { EditorBar },
  data() {
    return {
      isClear: false,
      detail: "",
      dialogVisible1: false,
      dialogVisible2: false,
      tableData: [],
      uploadLoading1: false,
      fileList1: [],
      ImageVisible1: false,
      dialogImageUrl: "",
      now: "",
      contentTitle: "",
      isLoading: false,
      total: 0,
      page: 1,
      tableHeight: 500,
      homeDeatail: [],
      updateJson: {},
      dialogVisible3: false,
      updateId: "",
    };
  },
  methods: {
    time() {
      if (!this.now) {
        this.now = new Date().getTime();
        return true;
      } else {
        let time = new Date().getTime();
        if (time - this.now > 3000) {
          this.now = time;
          return true;
        } else {
          return false;
        }
      }
    },
    init() {
      this.detail = "";
      this.fileList1 = [];
      this.contentTitle = "";
      this.updateJson = {};
      this.updateId = "";
    },
    insertPop() {
      this.init();
      this.dialogVisible1 = true;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.ImageVisible1 = true;
    },
    handle_remove1(file, fileList) {
      var _tmp = this.fileList1;
      for (var i = 0, len = _tmp.length; i < len; i++) {
        if (_tmp[i].uid == file.uid) {
          _tmp.splice(i, 1);
          break;
        }
        this.fileList1 = _tmp;
      }
    },
    beforeUpload1(data) {
      this.$refs.upload1.uploadFiles;
      this.uploadLoading1 = true;
      var file = data.file;
      var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域

      var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
      var _this = this;

      if (file) {
        var params = {
          Key:
            file.name.split(".")[0] +
            new Date().getTime() +
            "." +
            file.name.split(".")[1],
          ContentType: file.type,
          Body: file,
          "Access-Control-Allow-Credentials": "*",
          ACL: "public-read",
        }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
        var options = {
          partSize: 2048 * 1024 * 1024,
          queueSize: 2,
          leavePartsOnError: true,
        };
        bucket
          .upload(params, options)
          .on("httpUploadProgress", function (evt) {
            //这里可以写进度条
            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
          })
          .send(function (err, data) {
            _this.uploadLoading1 = false;
            if (err) {
              var a = _this.$refs.upload1.uploadFiles;
              a.splice(a.length - 1, a.length);
              _this.$message.error("上传失败");
            } else {
              //上传成功处理
              _this.fileList1.push({
                name: file.name,
                url: data.Location,
                uid: file.uid,
              });
              console.log(data.Location);
            }
          });
      }
    },
    change(val) {
      console.log(val);
    },
    //添加文章
    addContent() {
      if (this.contentTitle === "") {
        this.$message.error("请输入文章标题");
        return;
      } else if (this.detail === "") {
        this.$message.error("请输入文章内容");
        return;
      }
      console.log(this.detail);
      if (this.time()) {
        let params = [
          {
            p: this.fileList1.length ? this.fileList1[0].url : "",
            t: this.contentTitle,
            c: this.detail.replace(/%/g, "%25"),
            u: this.$store.state.userInfo.userid,
          },
        ];
        this.ajax
          .post(this.$store.state.api + "addFind", params)
          .then((res) => {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.init();
            this.getFind();
            this.dialogVisible1 = false;
          })
          .catch((err) => {
            this.$message.error("添加失败");
            console.error(err);
          });
      }
    },
    handleClose(done) {
      done();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.getFind();
    },
    //查询文章
    getFind() {
      this.isLoading = true;
      let params = {
        oid: this.$store.state.userInfo.organizeid,
        pid: this.pid,
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "getFindAdmin", params)
        .then((res) => {
          this.isLoading = false;
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          this.tableData = res.data[0];
        })
        .catch((err) => {
          this.isLoading = false;
          console.error(err);
        });
    },
    changeType() {
      this.page = 1;
      this.getFind();
    },
    //查看文章详情
    getDetail(id) {
      let params = { id: id };
      this.ajax
        .get(this.$store.state.api + "getFindByid", params)
        .then((res) => {
          this.dialogVisible2 = true;
          this.homeDeatail = res.data[0][0];
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //删除文章
    deleteFind(id) {
      let params = [{ id: id }];

      this.$confirm("确定删除此发现文章吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "deleteFind", params)
            .then((res) => {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              if (this.page != 1 && this.tableData.length == 1) {
                this.page--;
              }
              this.getFind();
            })
            .catch((err) => {
              this.$message.error("删除失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    changeHeight() {
      this.tableHeight =
        window.innerHeight - this.$refs.table.$el.offsetTop - 200;
      if (this.tableHeight <= 530) {
        this.tableHeight = 530;
      }
      // 监听窗口大小变化
      let self = this;
      window.onresize = function () {
        self.tableHeight =
          window.innerHeight - self.$refs.table.$el.offsetTop - 200;
        if (self.tableHeight <= 530) {
          self.tableHeight = 530;
        }
      };
      // this.$refs.table.$el.offsetTop：表格距离浏览器的高度 //200表示你想要调整的表格距离底部的高度（你可以自己随意调整），因为我们一般都有放分页组件的，所以需要给它留一个高度
    },
    //修改
    updatePop(id, index) {
      this.init();
      this.dialogVisible3 = true;
      this.updateJson = this.tableData[index];
      this.fileList1 = [];
      if (this.tableData[index].poster != "") {
        this.fileList1.push({
          name: this.tableData[index].poster
            .split("//")[1]
            .split("/")[1]
            .split(".")[0],
          url: this.tableData[index].poster,
        });
      }

      this.updateId = id;
    },
    updateDetail() {
      if (this.updateJson.title === "") {
        this.$message.error("请输入文章标题");
        return;
      } else if (this.updateJson.content === "") {
        this.$message.error("请输入文章内容");
        return;
      }
      if (this.time()) {
        let params = [
          {
            p: this.fileList1.length ? this.fileList1[0].url : "",
            t: this.updateJson.title,
            c: this.updateJson.content.replace(/%/g, "%25"),
            id: this.updateId,
          },
        ];
        this.ajax
          .post(this.$store.state.api + "updateFind", params)
          .then((res) => {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.init();
            this.getFind();
            this.dialogVisible3 = false;
          })
          .catch((err) => {
            this.$message.error("修改失败");
            console.error(err);
          });
      }
    },
  },
  mounted() {
    this.$nextTick(function () {
      this.page = 1;
      this.getFind();
      this.changeHeight();
    });
  },
};
</script>

<style scoped>
.tou {
  border-bottom: 1px solid #c9c9c9;
  height: 50px;
  font-size: 30px;
}
.tian1 {
  margin-top: 15px;
}
.tian1 span {
  display: block;
}
.tutor_type {
  display: flex;
  align-items: center;
  margin: 15px 0px;
}
.head {
  font-size: 20px;
  border-bottom: 1px solid;
  /* height: 35px; */
  display: flex;
  align-items: center;
  padding-bottom: 10px;
  justify-content: space-between;
}
.name {
  float: right;
  /* margin-top: -30px; */
  font-size: 14px;
  width: 200px;
}
.cont {
  /* font-size: 16px; */
  line-height: 34px;
  text-indent: 2em;
}
.dialog_diy >>> .el-dialog__header {
  background: #3d67bc !important;
  padding: 15px 20px;
}
.dialog_diy >>> .el-dialog__title {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn {
  top: 19px;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close:hover {
  color: #fff;
}
.student_page {
  margin-top: 15px;
}
.dialog_diyA >>> .el-dialog {
  min-width: 800px;
}
.dialog_diyH >>> .el-dialog__body {
  height: 750px;
  overflow: auto;
}
.bbox {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
  align-items: center;
}
/* table 样式 */
.cont >>> table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
.cont >>> table td,
.cont >>> table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
}
.cont >>> table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
}

/* blockquote 样式 */
.cont >>> blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
.cont >>> code {
  display: inline-block;
  *display: inline;
  *zoom: 1;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}
.cont >>> pre code {
  display: block;
}

/* ul ol 样式 */
.cont >>> ul,
ol {
  margin: 10px 0 10px 20px;
}
</style>
