<template>
  <div style="width: 100%">
    <el-main>
      <div class="tou">积分兑换</div>
      <div>
        <el-button
          size="small"
          type="primary"
          style="position: absolute; right: 20px; top: 90px"
          @click="goTo('/scoreProduct')"
          >礼品列表</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="classname" label="班级" min-width="15">
          </el-table-column>
          <el-table-column prop="spname" label="兑换礼品" min-width="15">
          </el-table-column>
          <el-table-column label="兑换码" min-width="15">
            <template slot-scope="scope">
              {{ scope.row.number ? scope.row.number : "暂无" }}
            </template>
          </el-table-column>
          <el-table-column label="是否审核" min-width="15">
            <template slot-scope="scope">
              {{
                scope.row.type == 0
                  ? "未审核"
                  : scope.row.type == 1
                  ? "已通过"
                  : scope.row.type == 3 ? '已兑换'
                  : "已拒绝"
              }}
            </template>
          </el-table-column>
          <el-table-column prop="time" label="创建时间" width="180px">
          </el-table-column>
          <el-table-column prop="do" label="操作" width="180px">
            <template slot-scope="scope">
              <div class="pb_buttonBox" style="justify-content: flex-start;">
                <el-button
                  size="mini"
                  type="primary"
                  @click="shen(scope.row)"
                  >{{scope.row.type != 0 ? '已审核' : '审核'}}</el-button
                >
                <el-button type="primary" size="mini" v-if="scope.row.type == 1" @click="isCan(scope.row.id)">
                    兑换确认
                </el-button>
                <el-button type="primary" size="mini" v-if="scope.row.type == 3" :disabled="true" @click="isCan(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="dialogVisible"
      width="600px"
      :before-close="handleClose"
      class="dialog_diy"
    >
      <div class="spBox">
        <div class="addBox">
          <span class="tian1">姓名</span>
          <span>{{ res.name }}</span>
        </div>
        <div class="addBox">
          <span class="tian1">目前积分</span>
          <span style="font-weight: 600; font-size: 18px">{{ res.score }}</span>
        </div>
        <div class="addBox">
          <span class="tian1">兑换礼品</span>
          <el-divider style="height: 2px"></el-divider>
        </div>
        <div class="addBox">
          <span class="tian1">学生账号</span>
          <span>{{ res.username }}</span>
        </div>
        <div class="addBox">
          <span class="tian1">礼品名称</span>
          <span>{{ res.spname }}</span>
        </div>
        <div class="addBox">
          <span class="tian1">扣去积分</span>
          <span style="color: orange; font-size: 18px">{{ -res.spscore }}</span>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="reject" v-if="res.type == 0">拒 绝</el-button>
        <el-button type="primary" @click="confirm" v-if="res.type == 0">通 过</el-button>
        <el-button @click="handleClose" v-if="res.type != 0">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      tableData: [],
      isLoading: false,
      total: 0,
      page: 1,
      tableHeight: 500,
      res: {},
    };
  },
  methods: {
    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表示你想要调整的表格距离底部的高度（你可以自己随意调整），因为我们一般都有放分页组件的，所以需要给它留一个高度
    },
    init() {
      this.res = {};
      this.dialogVisible = false;
    },
    handleClose(done) {
      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 + "getScoreHistory", 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);
        });
    },
    shen(res) {
      this.res = res;
      this.dialogVisible = true;
    },
    isCan(res){
         var _this = this;
      _this
        .$confirm("此礼品确定是否被学生兑换了吗?", "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        })
        .then(() => {
          let params = [
            {
              aid: res,
            },
          ];
          this.ajax
            .post(this.$store.state.api + "updateScoreCan", params)
            .then((res) => {
              this.$message.success("修改成功");
              this.getData();
            })
            .catch((err) => {
              this.$message.error("修改失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    reject() {
      var _this = this;
      _this
        .$confirm("确定拒绝学生兑换此礼品吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          let params = [
            {
              aid: this.res.id,
              uid: this.res.userid,
              anum: null,
              t: "2",
              nc: `您兑换的“<span style="color: orange">${this.res.spname}</span>”礼品，已拒绝审核， 请联系线下管理员了解情况。`,
            },
          ];
          this.ajax
            .post(this.$store.state.api + "updateScoreHistory", params)
            .then((res) => {
              console.log(res);
              if (res.data[0][0].success == "1") {
                this.$message.success("拒绝成功");
                this.init();
              } else if (res.data[0][0].success == "5") {
                this.$message.error(
                  "通过失败，此礼品已经审核过了，请刷新后重试"
                );
              } else if (res.data[0][0].success == "2") {
                this.$message.error("通过失败，此礼品不存在");
              }
              this.getData();
            })
            .catch((err) => {
              console.error(err);
            });
        })
        .catch(() => {});
    },
    confirm() {
      var num = "";
      for (var c = 0; c < 3; c++) {
        num += Math.floor(Math.random() * 10);
      }
      var _number = "G" + this.res.index + num;
      console.log(_number);
      let params = [
        {
          aid: this.res.id,
          uid: this.res.userid,
          anum: _number,
          t: "1",
          nc: `您兑换的“<span style="color: orange">${this.res.spname}</span>”礼品，已通过审核， 请联系线下管理员，将姓名与班级或兑换码报给管理员，进行兑换。兑换编码：<span style="color: orange">${_number}</span>`,
          c:"兑换" + this.res.spname
        },
      ];
      this.ajax
        .post(this.$store.state.api + "updateScoreHistory", params)
        .then((res) => {
          console.log(res);
          if (res.data[0][0].success == "1") {
            this.$message.success("通过成功");
            this.init();
          } else if (res.data[0][0].success == "5") {
            this.$message.error("通过失败，此礼品已经审核过了，请刷新后重试");
          } else if (res.data[0][0].success == "4") {
            this.$message.error("通过失败，学生积分不够");
          } else if (res.data[0][0].success == "3") {
            this.$message.error("通过失败，此礼品库存不足");
          } else if (res.data[0][0].success == "2") {
            this.$message.error("通过失败，此礼品不存在");
          }
          this.getData();
        })
        .catch((err) => {
          console.error(err);
        });
    },
  },
  created() {
    this.$nextTick(function () {
      this.changeHeight();
      this.getData();
    });
  },
};
</script>

<style scoped>
.tou {
  border-bottom: 1px solid #c9c9c9;
  height: 50px;
  font-size: 30px;
}
.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;
  font-size: 17px;
}
.addBox {
  display: flex;
  justify-content: flex-start;
  width: 80%;
  align-items: center;
  margin: 20px;
}
.addBox span:first-child {
  min-width: 80px;
}
.addBox span:last-child {
  margin-left: 10px;
}
.tian1 {
  margin-right: 10px;
}
</style>
