<template>
  <div class="pb_content" style="background: unset">
    <div
      class="pb_content_body"
      style="
        background: #fff;
        padding: 0px 25px;
        box-sizing: border-box;
        border-radius: 5px;
      "
    >
      <div class="pb_head">
        <span>Banner列表</span>
      </div>
      <div class="student_head">
        <div class="head_right">
          <el-button @click="dialogVisible = true">添加Banner</el-button>
        </div>
      </div>
    </div>
    <div class="pb_content_body">
      <div class="student_table">
        <el-table
          ref="table"
          :data="tableData"
          border
          :height="tableHeight"
          :fit="true"
          v-loading="isLoading"
          style="width: 100%"
          :header-cell-style="{ background: '#f1f1f1', fontSize: '17px' }"
          :row-class-name="tableRowClassName"
        >
          <el-table-column label="图片" min-width="60" align="center">
            <template slot-scope="scope">
              <el-image
                style="width: 200px; height: 100px; cursor: pointer"
                :src="scope.row.poster"
                fit="cover"
                @click="handlePictureCardPreviewA(scope.row.poster)"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="分类" min-width="20">
            <template slot-scope="scope">
              {{
                scope.row.type == 1
                  ? "绘画"
                  : scope.row.type == 2
                  ? "科技"
                  : scope.row.type == 3
                  ? "人文"
                  : "艺术"
              }}
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="20">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="deleteBList(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="student_page">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="10"
          :total="total"
          v-if="page"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      title="添加Banner"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
      class="dialog_diy"
      center
    >
      <div>
        <div class="dialogBox">
          <span>添加Banner</span>
          <el-upload
            :class="{ disUoloadSty: noneBtnImg }"
            action="#"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            v-loading="uploadLoading"
            :http-request="beforeUpload"
            ref="upload"
            :show-file-list="true"
            :limit="1"
            accept="image/*"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
        <div class="dialogBox" style="color: #bebebe; margin: 10px 0 0 0">
          注:适宜上传banner尺寸为1218×300
        </div>
        <div class="cTypeCss">
          <div>分类：</div>
          <el-select v-model="cType" placeholder="请选择分类">
            <el-option
              v-for="(t, tIndex) in typeList"
              :key="tIndex"
              :label="t.label"
              :value="t.value"
            ></el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBanner">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="imgVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-dialog :visible.sync="imgVisible1">
      <img width="100%" :src="dialogImageUrl1" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableHeight: "500px",
      isLoading: false,
      formLabelWidth: "100px",
      tableData: [],
      fileList: [],
      typeList: [
        {
          value: 1,
          label: "绘画",
        },
        {
          value: 2,
          label: "科技",
        },
        {
          value: 3,
          label: "人文",
        },
        {
          value: 4,
          label: "艺术",
        },
      ],
      cType: "",
      dialogVisible: false,
      noneBtnImg: false,
      dialogImageUrl: "",
      imgVisible: false,
      dialogImageUrl1: "",
      imgVisible1: false,
      page: 1,
      total: 0,
      userid: this.$route.query.userid,
      oid: this.$route.query.oid,
      cid: this.$route.query.cid,
      uploadLoading: false,
      tx: require("../../assets/avatar.png"),
    };
  },
  mounted() {
    this.$nextTick(function () {
      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;
        }
      };
    });
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if ((rowIndex + 1) % 2 === 0) {
        return "even_row";
      } else {
        return "";
      }
    },
    handleClose(done) {
      done();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getBannerList();
    },
    handlePictureCardPreviewA(url) {
      this.dialogImageUrl1 = url;
      this.imgVisible1 = true;
    },
    imgChange(file, fileList) {
      var _tmp = this.fileList;
      this.noneBtnImg = _tmp.length >= 1;
    },
    handleRemove(file) {
      var _tmp = this.fileList;
      for (var i = 0, len = _tmp.length; i < len; i++) {
        if (_tmp[i].uid == file.uid) {
          _tmp.splice(i, 1);
          break;
        }
        this.fileList = _tmp;
      }
      this.noneBtnImg = _tmp.length >= 1;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.fileList[0].url;
      this.imgVisible = true;
    },
    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;
        }
      }
    },
    beforeUpload(data) {
      this.$refs.upload.uploadFiles;
      this.uploadLoading = 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.uploadLoading = false;
            if (err) {
              var a = _this.$refs.upload.uploadFiles;
              a.splice(a.length - 1, a.length);
              _this.$message.error("上传失败");
            } else {
              //上传成功处理
              _this.fileList.push({
                name: file.name,
                url: data.Location,
                uid: file.uid,
              });
              console.log(data.Location);
              _this.imgChange();
            }
          });
      }
    },
    getBannerList() {
      this.isLoading = true;
      let params = {
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "selectBannerList", 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);
        });
    },
    addBanner() {
      var list = this.fileList;
      if (list.length == 0) {
        this.$message.error("请上传需要添加的banner");
        return;
      }
      if (this.time()) {
        let params = [
          {
            url: list[0].url,
            t: this.cType,
          },
        ];
        this.ajax
          .post(this.$store.state.api + "insertBannerList", params)
          .then((res) => {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.cType = "";
            this.getBannerList();
            this.init();
          })
          .catch((err) => {
            this.$message.error("添加失败");
            console.error(err);
          });
      }
    },
    deleteBList(id) {
      let params = {
        id: id,
      };
      this.ajax
        .get(this.$store.state.api + "deleteBannerList", params)
        .then((res) => {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getBannerList();
        })
        .catch((err) => {
          this.$message.error("删除失败");
          console.error(err);
        });
    },
    init() {
      this.fileList = [];
      this.$refs.upload ? (this.$refs.upload.uploadFiles.length = 0) : "";
      this.noneBtnImg = false;
      this.dialogImageUrl = "";
    },
  },
  created() {
    this.page = 1;
    this.getBannerList();
  },
};
</script>

<style scoped>
.pb_head > span:nth-child(2) {
  font-size: 20px;
  margin-left: 5px;
  color: #828282;
}
.pb_head {
  margin: 0 !important;
  width: 100% !important;
}
.student_page {
  margin-top: 10px;
}
.student_head {
  margin-top: 10px;
  padding-bottom: 10px;
  display: flex;
  justify-content: flex-end;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
}
.head_left {
  display: flex;
  align-items: center;
}
.head_right {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: baseline;
}
.student_input >>> .el-input__inner {
  height: 30px;
  width: 190px;
  font-size: 13px;
  padding: 0 10px;
}
.student_button {
  color: #fff;
  background: #2268bc;
  width: 60px;
  height: 30px;
  padding: 0 !important;
  font-size: 12px;
  line-height: 30px;
}
.head_right > button:nth-child(1) {
  color: #fff;
  background: #2268bc;
  width: 120px;
  height: 35px;
  padding: 0 !important;
  font-size: 12px;
  line-height: 35px;
}
.head_right > button:nth-child(2) {
  color: #fff;
  background: #2268bc;
  width: 70px;
  height: 30px;
  padding: 0 !important;
  font-size: 12px;
  line-height: 30px;
}
.head_right > div {
  font-size: 12px;
  line-height: 40px;
  margin-left: 10px;
  color: #2a6dbe;
  text-decoration: underline;
  cursor: pointer;
}
.student_table >>> .el-table--border td {
  border-right: 0px !important;
}
.student_table >>> .el-table,
.student_table >>> .el-table__body-wrapper {
  height: auto !important;
}
.el-table >>> .even_row {
  background-color: #f1f1f1 !important;
}
.de_button {
  color: #fff;
  background: #5190fd;
  width: 50px;
  height: 25px;
  padding: 0 !important;
  font-size: 12px;
  line-height: 25px;
}
.add_student >>> .el-dialog__header {
  padding: 20px 20px 10px;
  text-align: center;
  background: #32455b;
}
.add_student >>> .el-dialog__title {
  font-size: 14px !important;
  color: #fff !important;
}
.add_student >>> .el-dialog__headerbtn {
  font-size: 20px !important;
}
.add_student >>> .el-form-item__label {
  margin-left: 65px;
}
.add_student >>> .el-form-item {
  display: flex;
}
.add_student >>> .el-form-item__content {
  margin: 0 !important;
}
.add_input {
  width: 365px;
}
.add_student >>> .el-dialog__footer {
  text-align: center !important;
}
.right {
  width: 250px;
  color: #fff;
  background: #0e72e6;
  margin-bottom: 20px;
}
.header-title {
  display: flex;
}
.logoImg {
  width: 30px;
}
.logoImg > img {
  width: 100%;
  height: 100%;
}
.title_add_student {
  margin: 0 auto;
  color: #fff;
}
.upload-demo {
  line-height: 0px !important;
}
.upload-demo >>> .el-button {
  color: #fff;
  background: #2268bc;
  width: 70px;
  height: 30px;
  padding: 0 !important;
  font-size: 12px;
  line-height: 0 !important;
}

.userImg {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.tx {
  width: 40px;
  margin-right: 10px;
}

.delete {
  width: 25px;
  cursor: pointer;
}

.tx > img,
.delete > img {
  width: 100%;
  height: 100%;
}

.newCss {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: baseline;
}
.disUoloadSty >>> .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
.dialogBox {
  display: flex;
  align-items: center;
  justify-content: center;
}
.dialogBox span {
  margin: 0 20px;
}
.cTypeCss {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
  padding-top: 20px;
}
</style>
