<template>
  <div style="width: 100%">
    <el-main>
      <div class="tou">
        <span>积分兑换-礼品列表</span>
        <el-button type="text" style="font-size: 16px" @click="goTo('/score')"
          >返回</el-button
        >
      </div>
      <div>
        <el-button
          size="small"
          type="primary"
          style="position: absolute; right: 20px; top: 90px"
          @click="(dialogVisible = true), (uB = false)"
          >新建礼品</el-button
        >
        <!-- <div>Banner管理</div>      -->
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :header-cell-style="{ background: '#f1f1f1', 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          style="width: 100%; margin-top: 70px"
          :height="tableHeight"
          v-loading="isLoading"
        >
          <el-table-column prop="name" label="礼品名称" min-width="15">
          </el-table-column>
          <el-table-column prop="score" label="兑换积分" min-width="20">
          </el-table-column>
          <el-table-column prop="number" label="库存" min-width="20">
          </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="update(scope.row)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  @click="deleteP(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="uB ? '修改礼品' : '创建礼品'"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
      class="dialog_diy"
    >
      <div class="spBox">
        <div class="addBox">
          <span class="tian1">礼品名称</span>
          <el-input
            v-model="scoreName"
            style="width: 250px; margin: 15px 0px"
            placeholder="请输入礼品名称"
          ></el-input>
        </div>
        <div class="addBox">
          <span class="tian1">兑换积分</span>
          <el-input
            v-model="score"
            style="width: 250px; margin: 15px 0px"
            placeholder="请输入扣除的积分"
          ></el-input>
        </div>
        <div class="addBox">
          <span class="tian1">礼品图片</span>
          <el-upload
            class="uploadStyle"
            :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"
            :file-list="fileList"
            :limit="1"
            accept="image/*"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
        <div class="addBox">
          <span class="tian1">库存数量</span>
          <el-input
            v-model="scoreNum"
            style="width: 250px; margin: 15px 0px"
            placeholder="请输入库存"
          ></el-input>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="updateProduct" v-if="uB"
          >修 改</el-button
        >
        <el-button type="primary" @click="addProduct" v-else>确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="imgVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      isLoading: false,
      total: 0,
      page: 1,
      tableHeight: 500,
      dialogVisible: false,
      dialogImageUrl: "",
      imgVisible: false,
      fileList: [],
      uploadLoading: false,
      noneBtnImg: false,
      scoreName: "",
      score: "",
      scoreNum: "",
      upJson: "",
      uB: false,
    };
  },
  methods: {
    update(id) {
      this.scoreName = id.name;
      this.fileList = [
        {
          name: id.photo.split("//")[1].split("/")[1].split(".")[0],
          url: id.photo,
        },
      ];
      this.score = id.score;
      this.scoreNum = id.number;
      this.upid = id.id;
      this.uB = true;
      this.imgChange();
      this.dialogVisible = true;
    },
    goTo(path) {
      this.$router.push(path);
    },
    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;
        }
      }
    },
    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表示你想要调整的表格距离底部的高度（你可以自己随意调整），因为我们一般都有放分页组件的，所以需要给它留一个高度
    },
    handleClose(done) {
      this.dialogVisible = false;
      this.init();
      done();
    },
    change(val) {
      console.log(val);
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.getData();
    },
    getData() {
      this.isLoading = true;
      let params = {
        page: this.page,
        oid: this.$store.state.userInfo.organizeid,
      };
      this.ajax
        .get(this.$store.state.api + "getScoreProduct", 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);
        });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.fileList[0].url;
      this.imgVisible = true;
    },
    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;
    },
    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();
            }
          });
      }
    },
    imgChange(file, fileList) {
      var _tmp = this.fileList;
      this.noneBtnImg = _tmp.length >= 1;
    },
    init() {
      this.scoreName = "";
      this.fileList = [];
      this.score = "";
      this.scoreNum = "";
      this.upid = "";
      this.imgChange();
    },
    updateProduct() {
      if (this.scoreName == "") {
        this.$message.error("请填写礼品名称！");
        return;
      }
      if (this.fileList.length == 0) {
        this.$message.error("请上传礼品图片！");
        return;
      }
      if (this.score == "") {
        this.$message.error("请填写兑换积分！");
        return;
      }
      if (this.scoreNum == "") {
        this.$message.error("请填写库存数量！");
        return;
      }
      if (this.time()) {
        let params = [
          {
            n: this.scoreName,
            p: this.fileList[0].url,
            s: this.score,
            nu: this.scoreNum,
            id: this.upid,
          },
        ];
        this.ajax
          .post(this.$store.state.api + "updateScoreProduct", params)
          .then((res) => {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.init();
            this.getData();
          })
          .catch((err) => {
            this.$message.error("添加失败");
            console.error(err);
          });
      }
    },
    addProduct() {
      if (this.scoreName == "") {
        this.$message.error("请填写礼品名称！");
        return;
      }
      if (this.fileList.length == 0) {
        this.$message.error("请上传礼品图片！");
        return;
      }
      if (this.score == "") {
        this.$message.error("请填写兑换积分！");
        return;
      }
      if (this.scoreNum == "") {
        this.$message.error("请填写库存数量！");
        return;
      }
      if (this.time()) {
        let params = [
          {
            n: this.scoreName,
            p: this.fileList[0].url,
            s: this.score,
            nu: this.scoreNum,
            oid:this.$store.state.userInfo.organizeid
          },
        ];
        this.ajax
          .post(this.$store.state.api + "addScoreProduct", params)
          .then((res) => {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.init();
            this.getData();
          })
          .catch((err) => {
            this.$message.error("添加失败");
            console.error(err);
          });
      }
    },
    deleteP(id) {
      let params = [{ id: id }];
      var _this = this;
      _this
        .$confirm("确定删除此礼品吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          _this.ajax
            .post(_this.$store.state.api + "deleteScoreProduct", params)
            .then((res) => {
              _this.$message({
                message: "删除成功",
                type: "success",
              });
              if (_this.page != 1 && _this.tableData.length == 1) {
                _this.page--;
              }
              _this.getData();
            })
            .catch((err) => {
              _this.$message.error("删除失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
  },
  created() {
    this.$nextTick(function () {
      this.getData();
      this.changeHeight();
    });
  },
};
</script>

<style scoped>
.tou {
  border-bottom: 1px solid #c9c9c9;
  height: 50px;
  font-size: 30px;
  display: flex;
  justify-content: space-between;
}
.name {
  float: right;
  /* margin-top: -30px; */
  font-size: 14px;
  width: 200px;
}
.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: 600px;
}
.dialog_diyA >>> .el-dialog__body {
  max-height: 750px;
  overflow: auto;
}
.spBox {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.addBox {
  display: flex;
  justify-content: flex-start;
  width: 60%;
  align-items: center;
}
.tian1 {
  margin-right: 10px;
}
.disUoloadSty >>> .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
.uploadStyle >>> .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 110px;
}
.uploadStyle >>> .el-upload-list--picture-card {
  width: 100px;
  height: 100px;
}
</style>
