<template>
  <div class="payment">
    <Header></Header>
    <section class="section">
      <div class="container">
        <div class="section__header">
          <div class="icon">
            <i class="img el-icon-bank-card"></i>
          </div>
          <div class="title">支付中心</div>
        </div>
        <div class="section__body">
          <div class="order-msg">
            <div class="order-msg__header" v-if="orderSn">
              <!-- <div class="icon">✔</div> -->
              <!-- <div class="title">订单提交成功！订单编号：20220305100636</div> -->
              <div class="title">订单编号：{{ orderSn }}</div>
              <!-- <div class="desc">订单详情▼</div> -->
            </div>

            <div class="order-msg__body" v-else>
              <div
                class="goods_item"
                v-for="(goodsItem, goodsIndex) in checkGoodsList"
                :key="goodsIndex"
              >
                商品名称：{{ goodsItem.goodsName }}
                <span>应付金额：{{ goodsItem.standPrice | toFixed }}元</span>
              </div>
            </div>
          </div>

          <div class="payment-way">
            <ul>
              <li :class="{ active: radio == 1 }">
                <el-radio v-model="radio" label="1">
                  <img src="@/assets/wep.png" alt="" />
                </el-radio>
              </li>
              <!-- <li :class="{ active: radio == 2 }">
                <el-radio v-model="radio" label="2">
                  <img src="@/assets/unp.png" alt="" />
                </el-radio>
              </li> -->
            </ul>
          </div>

          <div class="payment-btn">
            应付金额：
            <div class="price">{{ total | toFixed }}</div>
            <el-button type="danger" class="btn" id="pay" @click="pay"
              >立即支付</el-button
            >
          </div>
        </div>
      </div>
    </section>

    <el-dialog
      title="请使用微信扫码支付"
      :visible.sync="qrCodeShow"
      width="348px"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="closePay"
      class="qrcode"
    >
      <div class="qrcode__body">
        <div class="img" @click="refreshCode">
          <img
            :src="lastTime <= 0 ? require('@/assets/qrcode.png') : urlBase64"
            alt=""
          />
        </div>
        <p v-if="lastTime > 0">
          距离二维码过期还剩<span>{{ lastTime }}</span
          >秒
        </p>
        <p v-else>二维码已过期，点击图片重新获取二维码</p>
        <p>过期后请刷新重新获取二维码</p>
        <p>客服电话：020-87085982</p>
      </div>
    </el-dialog>

    <ToolBar></ToolBar>
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from "@/components/footer/index";
import Header from "@/components/header/index";
import ToolBar from "@/components/toolbar/index";
import { mapGetters, mapMutations } from "vuex";
export default {
  name: "Payment",
  components: {
    Footer,
    Header,
    ToolBar,
  },
  data() {
    return {
      lastTime: 60,
      radio: "1",
      qrCodeShow: false,
      total: 0,
      urlBase64: "",
      orderSn: "",
      checkOrderTimer: null,
      loading: null,
      countTimer: null,
      checkGoodsList: [],
      isBK: "",
    };
  },
  computed: {},
  beforeDestroy() {
    clearInterval(this.countTimer);
    clearInterval(this.checkOrderTimer);
  },
  mounted() {
    console.log(this.$route, "this.$route.params");
    this.isBK = this.$route.query.isBK;
    let checkGoodsList = localStorage.getItem("checkGoodsList");
    if (!this.$tools.isLogin()) {
      this.setCurrentRouter(this.$route);
      this.$router.push({
        path: "/login",
      });
      return;
    }
    if (!checkGoodsList && !this.$route.params.orderSn) {
      this.$router.push({ path: "/person-center/my-order" });
      return;
    } else {
      if (this.$route.params.orderSn) {
        this.orderSn = this.$route.params.orderSn;
        this.total = this.$route.params.total;
        this.orderGoodsList();
      } else if (checkGoodsList) {
        this.checkGoodsList = JSON.parse(checkGoodsList);
        this.caculate();
      }
    }
  },
  methods: {
    ...mapMutations(["setCurrentRouter"]),
    refreshCode() {
      if (this.lastTime > 0) {
        return;
      }
      this.$request
        .orderResumePCOrder({ orderSn: this.orderSn })
        .then((res) => {
          this.loading.close();
          this.urlBase64 = res.data.urlBase64;
          this.orderSn = res.data.orderSn;
          this.checkOrderTimer = setInterval(() => {
            this.orderPayStatus();
          }, 2000);
          this.lastTime = 60;
          this.countTimer = setInterval(() => {
            if (this.lastTime <= 0) {
              clearInterval(this.countTimer);
              clearInterval(this.checkOrderTimer);
              return;
            }
            this.lastTime--;
          }, 1000);
        })
        .catch((err) => {
          // this.loading.close();
        });
    },
    closePay() {
      console.log(999);
      this.$confirm("确定离开支付页面吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then((_) => {
          this.qrCodeShow = false;
          this.$router.back(-1);
        })
        .catch((_) => {});
    },
    caculate() {
      this.total = 0;
      this.checkGoodsList.forEach((item) => {
        this.total += item.standPrice;
      });
    },
    orderGoodsList() {
      this.$request
        .orderGoodsList({
          orderSn: this.orderSn,
        })
        .then((res) => {
          this.checkGoodsList = res.rows;
        });
    },

    pay() {
      if (this.radio == 1) {
        //微信

        this.loading = this.$loading({
          lock: true,
          text: "支付中",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0)",
          target: document.querySelector(".section__body"),
        });

        if (this.orderSn) {
          //订单继续支付
          this.orderResumePCOrder();
        } else {
          //购物车进入支付
          this.orderPlacePcOrder();
        }
      } else {
        //银联
      }
    },

    orderPlacePcOrder() {
      this.$request
        .orderPlacePcOrder({ goodsList: this.checkGoodsList })
        .then((res) => {
          this.loading.close();
          localStorage.removeItem("checkGoodsList");
          console.log(res);

          //0元商品
          if (this.total == 0) {
            this.orderSn = res.data.orderSn;
            if (this.isBK) {
              this.$router.replace({
                path: "/payment-success",
                name: "支付成功",
                params: {
                  orderSn: this.orderSn,
                  total: this.total,
                  isBK: this.isBK,
                  goodsId: this.checkGoodsList[0].learnGoodsId,
                  gradeId: this.checkGoodsList[0].learnGradeId,
                  orderGoodsId: this.checkGoodsList[0].learnOrderGoodsId,
                },
                query: {
                  orderSn: this.orderSn,
                  isBK: this.isBK,
                  goodsId: this.checkGoodsList[0].learnGoodsId,
                  gradeId: this.checkGoodsList[0].learnGradeId,
                  orderGoodsId: this.checkGoodsList[0].learnOrderGoodsId,
                },
              });
            } else {
              this.$router.replace({
                path: "/payment-success",
                name: "支付成功",
                params: {
                  goodsId: this.checkGoodsList[0].goodsId,
                  gradeId: this.checkGoodsList[0].gradeId,
                  orderGoodsId: this.checkGoodsList[0].orderGoodsId,
                  orderSn: this.orderSn,
                  total: this.total,
                },
                query: {
                  goodsId: this.checkGoodsList[0].goodsId,
                  gradeId: this.checkGoodsList[0].gradeId,
                  orderGoodsId: this.checkGoodsList[0].orderGoodsId,
                  orderSn: this.orderSn,
                },
              });
            }
            return;
          } else {
            this.urlBase64 = res.data.urlBase64;
            this.orderSn = res.data.orderSn;
            this.qrCodeShow = true;
            this.checkOrderTimer = setInterval(() => {
              this.orderPayStatus();
            }, 2000);
            this.lastTime = 60;
            this.countTimer = setInterval(() => {
              if (this.lastTime <= 0) {
                clearInterval(this.countTimer);
                clearInterval(this.checkOrderTimer);
                return;
              }
              this.lastTime--;
            }, 1000);
          }
        })
        .catch((err) => {
          this.loading.close();

          setTimeout(() => {
            if (err.code == 510) {
              this.$confirm(err.msg + "。点击确定跳转待支付订单列表", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
              })
                .then((_) => {
                  this.$router.push({
                    path: "/person-center/my-order",
                  });
                })
                .catch((_) => {});
              // this.qrCodeShow = true;
            } else {
              this.$message({
                type: "warning",
                message: err.msg,
              });
            }
          }, 500);
        });
    },

    orderResumePCOrder() {
      this.$request
        .orderResumePCOrder({ orderSn: this.orderSn })
        .then((res) => {
          this.loading.close();
          this.urlBase64 = res.data.urlBase64;
          this.orderSn = res.data.orderSn;
          this.qrCodeShow = true;
          this.checkOrderTimer = setInterval(() => {
            this.orderPayStatus();
          }, 2000);
          this.lastTime = 60;
          this.countTimer = setInterval(() => {
            if (this.lastTime <= 0) {
              clearInterval(this.countTimer);
              clearInterval(this.checkOrderTimer);
              return;
            }
            this.lastTime--;
          }, 1000);
        })
        .catch((err) => {
          // this.loading.close();
        });
    },

    orderPayStatus() {
      this.$request
        .orderPayStatus(this.orderSn)
        .then((res) => {
          if (res.data) {
            clearInterval(this.checkOrderTimer);
            console.log(1);
            if (this.isBK) {
              console.log(2);
              this.$router.replace({
                path: "/payment-success",
                name: "支付成功",
                params: {
                  orderSn: this.orderSn,
                  total: this.total,
                  isBK: this.isBK,
                  goodsId: this.checkGoodsList[0].learnGoodsId,
                  gradeId: this.checkGoodsList[0].learnGradeId,
                  orderGoodsId: this.checkGoodsList[0].learnOrderGoodsId,
                },
                query: {
                  orderSn: this.orderSn,
                  isBK: this.isBK,
                  goodsId: this.checkGoodsList[0].learnGoodsId,
                  gradeId: this.checkGoodsList[0].learnGradeId,
                  orderGoodsId: this.checkGoodsList[0].learnOrderGoodsId,
                },
              });
            } else {
              console.log(3);
              this.$router.replace({
                path: "/payment-success",
                name: "支付成功",
                params: {
                  goodsId: this.checkGoodsList[0].goodsId,
                  gradeId: this.checkGoodsList[0].gradeId,
                  orderGoodsId: this.checkGoodsList[0].orderGoodsId,
                  orderSn: this.orderSn,
                  total: this.total,
                },
                query: {
                  goodsId: this.checkGoodsList[0].goodsId,
                  gradeId: this.checkGoodsList[0].gradeId,
                  orderGoodsId: this.checkGoodsList[0].orderGoodsId,
                  orderSn: this.orderSn,
                },
              });
            }

            console.log(this.checkGoodsList);
          }
        })
        .catch((err) => {
          console.log(err, "err");
        });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.payment {
  .section {
    &__header {
      height: 80px;
      background: #ebf3ff;
      display: flex;
      align-items: center;
      padding: 0 20px;

      .icon {
        width: 40px;
        height: 40px;
        background: #3f8dfd;
        box-shadow: 0px 0px 9px 1px rgba(63, 141, 253, 0.3);
        border-radius: 50%;
        text-align: center;
        line-height: 40px;

        .img {
          vertical-align: middle;
          display: inline-block;
          color: #fff;
          font-size: 24px;
        }
      }

      .title {
        margin-left: 20px;
        flex: 1;
        font-size: 30px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #333333;
      }
    }

    &__body {
      .order-msg {
        border-bottom: 2px solid #eee;
        &__header {
          display: flex;
          align-items: center;
          padding: 0 20px;
          height: 40px;
          .icon {
            color: #fff;
            width: 24px;
            height: 24px;
            line-height: 24px;
            border-radius: 50%;
            text-align: center;
            background: rgba(52, 199, 89, 1);
          }

          .title {
            flex: 1;
            margin-left: 10px;
          }
        }

        &__body {
          padding-left: 50px;
          .goods_item {
            margin: 16px 0;
            span {
              margin-left: 20px;
            }
          }
        }
      }
      .payment-way {
        border-bottom: 2px solid #eee;
        ul {
          li {
            margin: 24px 0;
            width: 100%;
            background: #fafbfc;
            box-shadow: 0px 0px 7px 1px rgba(0, 0, 0, 0.04);
            border-radius: 16px;
            height: 80px;
            border-radius: 16px;
            display: flex;
            align-items: center;
            padding: 0 20px;

            &.active {
              background: #f2f7fc;
              border: 1px solid #3f8dfd;
              box-shadow: 0px 0px 7px 1px rgba(0, 0, 0, 0.04);
            }

            /deep/ .el-radio__label {
              vertical-align: middle;
            }
          }
        }
      }

      .payment-btn {
        margin: 24px 0;
        display: flex;
        align-items: center;
        .price {
          font-size: 24px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #ff3b30;
        }

        .btn {
          cursor: pointer;
          margin-left: 40px;
          width: 120px;
          height: 40px;
          padding: 0;
          background-color: #ff3b30;
          border-radius: 20px;
          text-align: center;
          line-height: 40px;
          color: #fff;
          font-size: 16px;

          &:hover {
            background-color: #f78989;
          }
        }
      }
    }
  }

  .qrcode {
    &__body {
      .img {
        cursor: pointer;
        margin: 0 auto;
        width: 180px;
        height: 180px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      p {
        margin: 5px 0;
        text-align: center;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #333333;
        line-height: 24px;
        span {
          color: #ff3b30;
        }
      }
    }
  }
}
</style>
