<template>
  <div class="sc_body">
    <div class="sc_btnBox">
      <el-button type="primary" size="small" @click="cardDialog = true,updateB = false">创建积分电子卡</el-button>
    </div>
    <div class="sc_content">
      <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%"
        :height="tableHeight"
      >
        <el-table-column prop="name" label="积分卡名称" min-width="30" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="score" label="积分设置" min-width="10"></el-table-column>
        <el-table-column prop="cardType" label="卡片类型" min-width="20"></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="20" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div>{{scope.row.remark ?scope.row.remark : '暂无'}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="do" label="操作" width="230px">
          <template slot-scope="scope">
            <!--  -->
            <div class="pb_buttonBox">
              <el-button size="mini" type="primary" @click="updateC(scope.row)">修改</el-button>
              <el-button size="mini" type="primary" @click="check(scope.row)">查看</el-button>
              <el-button size="mini" type="primary" @click="deleteCard(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="student_page">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="10"
          :total="total"
          v-if="!isListAjax && page"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      :title="updateB ? '修改礼品卡':'添加礼品卡'"
      :visible.sync="cardDialog"
      width="600px"
      :before-close="handleClose"
      :append-to-body="true"
      class="dialog_diy"
    >
      <div>
        <el-form class="sc_add_content">
          <el-form-item label="积分卡名称" :label-width="formLabelWidth">
            <el-input v-model="name" auto-complete="off" placeholder="请填写卡片名称..."></el-input>
          </el-form-item>
          <el-form-item label="电子卡类型" :label-width="formLabelWidth">
            <el-select v-model="cardType" placeholder="请选择卡片类型...">
              <el-option label="与校长共进午餐" value="与校长共进午餐"></el-option>
              <el-option label="校长推荐书籍" value="校长推荐书籍"></el-option>
              <el-option label="校级社团荣誉团员" value="校级社团荣誉团员"></el-option>
              <el-option label="VR社团体验卡" value="VR社团体验卡"></el-option>
              <el-option label="创客社团体验卡" value="创客社团体验卡"></el-option>
              <el-option label="书面作业减免卡" value="书面作业减免卡"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="积分类型" :label-width="formLabelWidth">
            <el-select
              filterable
              allow-create
              default-first-option
              v-model="scoreType"
              placeholder="请选择积分类型..."
            >
              <el-option label="认真听讲" value="认真听讲"></el-option>
              <el-option label="课堂互动活跃" value="课堂互动活跃"></el-option>
              <el-option label="作业优质完成" value="作业优质完成"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="兑换积分" :label-width="formLabelWidth">
            <!-- <el-input v-model="score" auto-complete="off" placeholder="数字如：1" type='number'></el-input> -->
            <el-input-number
              v-model="score"
              :controls="false"
              :min="1"
              placeholder="数字如：1"
              style="width:100px;text-align:left;"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input v-model="remark" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="cardDialog = false">关闭</el-button>
        <el-button type="primary" @click="addScoreCard" v-if="!updateB">添加</el-button>
        <el-button type="primary" @click="updateCard" v-else>修改</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="礼品卡"
      :visible.sync="cardPDialog"
      width="800px"
      :before-close="handleClose"
      :append-to-body="true"
      class="dialog_diy"
    >
      <div class="cpd_body" ref="qrcodePicture">
        <el-image
          class="cpd_img"
          style="width: 100%"
          :src="require('../../../assets/score/scoreCard.png')"
        ></el-image>
        <div class="cpd_typeBox">
          <div class="cpd_cardType">
            <div v-for="(item,index) in cardRow.cardType" :key="index">{{item}}</div>
          </div>
          <div class="cpd_scoreType">
            <div v-for="(item,index) in cardRow.scoreType+'分'" :key="index">{{item}}</div>
          </div>
        </div>
        <div class="cpd_qrcodeBox">
          <div class="cpd_score">{{'+'+(cardRow && cardRow.score)+'积分'}}</div>
          <div class="cpd_qrcode" ref="qrCodeUrl"></div>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="cardPDialog = false">关闭</el-button>
        <el-button type="primary" @click="saveImage">保存图片</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
import html2canvas from "html2canvas";

export default {
  props: ["countA"],
  data() {
    return {
      tableHeight: 600,
      tableData: [],
      isLoading: false,
      cardDialog: false,
      cardPDialog: false,
      formLabelWidth: "90px",
      cardType: "",
      scoreType: "",
      score: "",
      remark: "",
      name: "",
      total: 0,
      page: 1,
      isListAjax: false,
      cardRow: {},
      updateB: false,
    };
  },
  methods: {
    handleClose(done) {
      done();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.getData();
    },
    init() {
      this.name = "";
      this.cardType = "";
      this.scoreType = "";
      this.score = "";
      this.remark = "";
      this.updateB = false;
    },
    getData() {
      this.isLoading = true;
      let params = {
        oid: this.$store.state.userInfo.organizeid,
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "getScoreCard", params)
        .then((res) => {
          this.isListAjax = false;
          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);
        });
    },
    addScoreCard() {
      if (this.name == "" || this.name.trim() == "") {
        this.$message.error("请填写积分卡名称");
        return;
      } else if (this.scoreType == "") {
        this.$message.error("请选择积分类型");
        return;
      } else if (this.cardType == "") {
        this.$message.error("请选择电子卡类型");
        return;
      } else if (this.score == "" || this.score == 0) {
        this.$message.error("请填写兑换积分");
        return;
      }

      let params = [
        {
          n: this.name,
          s: this.score,
          ct: this.cardType,
          st: this.scoreType,
          r: this.remark,
          userid: this.$store.state.userInfo.userid,
        },
      ];

      this.ajax
        .post(this.$store.state.api + "addScoreCard", params)
        .then((res) => {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.init();
          this.getData();
          this.cardDialog = false;
        })
        .catch((err) => {
          this.$message.error("添加失败");
          console.error(err);
        });
    },
    updateC(row) {
      this.cardRow = row;
      this.name = row.name;
      this.cardType = row.cardType;
      this.scoreType = row.scoreType;
      this.score = row.score;
      this.remark = row.remark;
      this.updateB = true;
      this.cardDialog = true;
    },
    updateCard() {
      if (this.name == "" || this.name.trim() == "") {
        this.$message.error("请填写积分卡名称");
        return;
      } else if (this.scoreType == "") {
        this.$message.error("请选择积分类型");
        return;
      } else if (this.cardType == "") {
        this.$message.error("请选择电子卡类型");
        return;
      } else if (this.score == "" || this.score == 0) {
        this.$message.error("请填写兑换积分");
        return;
      }

      let params = [
        {
          n: this.name,
          s: this.score,
          ct: this.cardType,
          st: this.scoreType,
          r: this.remark,
          aid: this.cardRow.id,
        },
      ];

      this.ajax
        .post(this.$store.state.api + "updateScoreCard", params)
        .then((res) => {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.init();
          this.getData();
          this.cardDialog = false;
        })
        .catch((err) => {
          this.$message.error("修改失败");
          console.error(err);
        });
    },
    deleteCard(row) {
      let params = [{ id: row.id }];
      this.$confirm("确定删除此礼品卡吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "deleteScoreCard", 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(() => {});
    },
    check(row) {
      this.cardRow = row;
      if (this.$refs.qrCodeUrl) {
        this.$refs.qrCodeUrl.innerHTML = "";
      }
      setTimeout(() => {
        var qrcode = new QRCode(this.$refs.qrCodeUrl, {
          text:
            window.location.origin + "/app/index.html#/myScore?scoreCard=" +
            row.id, // 需要转换为二维码的内容
          // text:
          //   "http://localhost:8080/app/index.html#/myScore?scoreCard=" + row.id, // 需要转换为二维码的内容
          width: this.$refs.qrCodeUrl.offsetWidth - 20,
          height: this.$refs.qrCodeUrl.offsetWidth - 20,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.H,
        });
      }, 500);
      this.cardPDialog = true;
    },
    //保存图片
    saveImage() {
      // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
      html2canvas(this.$refs.qrcodePicture, {
        backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        useCORS: true, //支持图片跨域
        scale: 1, //设置放大的倍数
      }).then((canvas) => {
        // 把生成的base64位图片上传到服务器,生成在线图片地址
        let url = canvas.toDataURL("image/png"); // toDataURL: 图片格式转成 base64
        this.imgUrl = url;
        //将图片下载到本地
        let a = document.createElement("a"); // 生成一个a元素
        let event = new MouseEvent("click"); // 创建一个单击事件
        a.download = "礼品卡"; // 设置图片名称没有设置则为默认
        a.href = this.imgUrl; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      });
    },
  },
  watch: {
    countA() {
      this.tableData = [];
      this.page = 1;
      this.getData();
    },
  },
  created() {
    this.page = 1;
    this.getData();
  },
};
</script>

<style scoped>
.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;
}
.sc_body {
  width: 100%;
}

.sc_btnBox {
  display: flex;
  justify-content: flex-end;
}
.sc_content {
  margin: 10px 0;
}

.sc_add_content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.sc_add_content >>> .el-form-item {
  margin-bottom: 0;
}
.sc_add_content >>> .el-form-item + .el-form-item {
  margin-top: 22px;
}

.sc_add_content >>> .el-form-item__content {
  width: 210px;
}

.sc_add_content >>> .el-input-number.is-without-controls .el-input__inner {
  text-align: left;
}

.student_page {
  margin-top: 10px;
}

.cpd_body {
  position: relative;
  min-height: 400px;
}
.cpd_img {
}
.cpd_typeBox {
  position: absolute;
  bottom: 45px;
  left: 60px;
  background: #52884c;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 10px 10px;
  width: 180px;
  height: 80px;
  box-sizing: border-box;
}
.cpd_cardType {
  font-size: 16px;
  color: #fff;
  opacity: 0.8;
  /* letter-spacing: 5px; */
  margin-bottom: 5px;
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.cpd_scoreType {
  width: 100%;
  font-size: 20px;
  color: #fff;
  /* letter-spacing: 5px; */
  display: flex;
  justify-content: space-between;
  overflow: hidden;
}
.cpd_qrcodeBox {
  position: absolute;
  bottom: 80px;
  right: 70px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.cpd_score {
  font-size: 35px;
  margin-bottom: 15px;
  color: #52884c;
}
.cpd_qrcode {
  background: #fff;
  width: 200px;
  height: 200px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
