<template>
  <div class="payment" v-if="data">
    <ul class="payment-left">
      <li
        v-for="(itemP, indexP) in payList"
        :key="indexP"
        @click="handleChangePay(itemP.type)"
        :class="[payType === itemP.type ? 'active' : '']"
      >
        <img :src="itemP.img" />
        <span>{{ itemP.label }}</span>
      </li>
    </ul>
    <div class="payment-right">
      <i class="el-icon-close" @click="closeDialogue"></i>
      <h2>{{ data.name || data.cn_title }}</h2>
      <h3>{{ data.org_name || "二十一世纪英文报" }}</h3>
      <p class="price">
        ￥{{
          data.hasOwnProperty("price_discount")
            ? data.price_discount
            : payAmount || data.price | cutMoneyFiter
        }}
      </p>
      <template v-if="payType === 'dui'">
        <el-input
          class="code"
          placeholder="在此输入兑换码"
          v-model="codeValue"
          maxlength="20"
        ></el-input>
        <a class="exchange" @click="handleExchange">兑换</a>
        <b class="tips">输入兑换码</b>
      </template>
      <div v-else v-loading="loading">
        <canvas
          id="QRCode_header"
          style="width: 338px; height: 338px; cursor: pointer"
          @click="handleRefresh"
        ></canvas>
      </div>
      <template v-if="payType === 'wei'">
        <b class="tips">请使用微信扫一扫</b>
      </template>
      <template v-else-if="payType === 'zhi'">
        <b class="tips">请使用支付宝扫一扫</b>
      </template>
    </div>
    <div class="toPage" v-if="showToPage">
      此兑换码包含多种商品，请到个人中心统一兑换。<a @click="toPage">去兑换</a>
      <i class="el-icon-error" @click="showToPage = !showToPage"></i>
    </div>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import { cutMoneyFiter } from "@/utils/defined";
import { getLogin } from "@/api/ajax";
import QRCode from "qrcode";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: ["data", "payWay", "qr_code_url", "orderId", "order_amount"],
  filters: {
    cutMoneyFiter,
  },
  data() {
    //这里存放数据
    return {
      payList: [
        {
          img: require("../../../assets/duihuanma.png"),
          label: "兑换码",
          type: "dui",
        },
        {
          img: require("../../../assets/weixin.png"),
          label: "微信支付",
          type: "wei",
        },
        {
          img: require("../../../assets/zhifubao.png"),
          label: "支付宝",
          type: "zhi",
        },
      ], // 支付方式
      payType: "dui",
      codeValue: "", // 兑换码的值
      codeImg: "",
      payCode: {
        wei: "http://localhost:9970/#/people_manage",
        zhi: "http://localhost:9970/#/organize_manage",
      },
      opts: {
        errorCorrectionLevel: "H", //容错级别
        type: "image/png", //生成的二维码类型
        quality: 1, //二维码质量
        margin: 0, //二维码留白边距
        width: 330, //宽
        height: 330, //高
        text: "", //二维码内容
        color: {
          dark: "#333333", //前景色
          light: "#fff", //背景色
        },
      },
      timer: null,
      loading: false,
      payAmount: this.order_amount ? this.order_amount : null,
      showToPage: false, // 多条兑换码跳转去个人中心
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中数据变化
  watch: {
    //  data:{
    //   handler(val, oldVal) {
    //     const _this = this;
    //     if (val) {
    //
    //     }
    //   },
    //   // 深度观察监听
    //   deep: true,
    // },
  },
  //方法集合
  methods: {
    // 支付方式
    handleChangePay(type) {
      this.payType = type;
      clearInterval(this.timer);
      if (type === "dui") {
        return false;
      }
      this.timer = setInterval(() => {
        this.getOrderStatus();
      }, 5000);
      this.loading = true;
      let MethodName = "/ShopServer/Client/OrderManager/UpdateOrderPayType";
      let data = {
        id: this.orderId,
        pay_type:
          this.payType === "wei" ? 3 : this.payType === "zhi" ? 4 : null,
      };
      getLogin(MethodName, data).then((res) => {
        if (res.status === 1) {
          this.payCode[this.payType] = res.qr_code_url;
          this.payAmount = res.order_amount;
          this.createQRCode();
        }
      });
    },
    createQRCode() {
      let msg = document.getElementById("QRCode_header");
      setTimeout(() => {
        QRCode.toCanvas(
          msg,
          this.payCode[this.payType],
          this.opts,
          function (error) {
            if (error) {
              console.log("二维码加载失败", error);
              this.$message.error("二维码加载失败");
            }
          }
        );
        this.loading = false;
      }, 1000);
    },
    closeDialogue() {
      clearInterval(this.timer);
      this.$emit("handleClose");
    },
    // 兑换
    handleExchange() {
      let MethodName = "/ShopServer/Client/OrderManager/UpdateOrderPayType";
      let data = {
        id: this.orderId,
        pay_type: 5,
        discount_code: this.codeValue.trim(),
      };
      getLogin(MethodName, data).then((res) => {
        if (res.status === 1) {
          if (this.$emit("handleSuccess")) {
            this.$emit("handleSuccess");
          } else {
            this.$emit("handleClose");
          }
        } else if (res.status === -6) {
          this.showToPage = true;
        }
      });
    },
    // 跳转到个人中心-兑换码
    toPage() {
      this.$router.push({
        path: "/peraonal",
        query: {
          headerConfig: this.$route.query.headerConfig
            ? this.$route.query.headerConfig
            : "",
          type: encodeURIComponent("duihuanma"),
          codeId: encodeURIComponent(this.codeValue.trim()),
        },
      });
    },
    handleRefresh() {
      let MethodName = "/ShopServer/Client/OrderManager/GetOrderNewPayQRCode";
      let data = {
        id: this.orderId,
      };
      getLogin(MethodName, data).then((res) => {
        if (res.status === 1) {
          this.payCode[this.payType] = res.qr_code_url;
          this.createQRCode();
        }
      });
      // this.payCode = {
      //     wei: 'https://baidu.com',
      //     zhi: 'https://xdf.cn'
      // }
      // this.createQRCode()
    },
    getOrderStatus() {
      let MethodName = "/ShopServer/Client/OrderManager/GetOrderPayStatus";
      let data = {
        id: this.orderId,
      };
      getLogin(MethodName, data).then((res) => {
        if (res.status === 1) {
          if (res.is_success === "true") {
            clearInterval(this.timer);
            if (this.$emit("handleSuccess")) {
              this.$emit("handleSuccess");
            } else {
              this.$emit("handleClose");
            }
          }
        }
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.payType = this.payWay;
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    if (this.qr_code_url) {
      this.payCode[this.payType] = this.qr_code_url;
      this.createQRCode();
      this.timer = null;
      this.timer = setInterval(() => {
        this.getOrderStatus();
      }, 5000);
    }
  },
  //生命周期-创建之前
  beforeCreated() {},
  //生命周期-挂载之前
  beforeMount() {},
  //生命周期-更新之前
  beforUpdate() {},
  //生命周期-更新之后
  updated() {},
  //生命周期-销毁之前
  beforeDestory() {},
  //生命周期-销毁完成
  destoryed() {},
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {},
};
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.payment {
  display: flex;
  &-left {
    background: #f5f5f5;
    width: 216px;
    padding: 24px;
    list-style: none;
    margin: 0;
    li {
      border: 1px solid #ebebeb;
      border-radius: 8px;
      background: #ffffff;
      margin-bottom: 16px;
      cursor: pointer;
      padding: 16px 24px;
      display: flex;
      align-items: center;
      img {
        width: 24px;
        margin-right: 8px;
      }
      span {
        color: rgba(0, 0, 0, 0.88);
        font-weight: 400;
        font-size: 18px;
        line-height: 26px;
      }
      &:hover {
        background: #eef3ff;
      }
      &.active {
        border-color: #3459d2;
        background: #eef3ff;
      }
    }
  }
  &-right {
    flex: 1;
    background: #ffffff;
    box-shadow: 0px 6px 30px 5px rgba(0, 0, 0, 0.05),
      0px 16px 24px 2px rgba(0, 0, 0, 0.04),
      0px 8px 10px -5px rgba(0, 0, 0, 0.08);
    position: relative;
    padding: 64px 80px;
    text-align: center;
    .el-icon-close {
      position: absolute;
      right: 16px;
      top: 16px;
      width: 16px;
      cursor: pointer;
    }
    h2 {
      margin: 0 0 2px 0;
      color: rgba(0, 0, 0, 0.88);
      font-weight: 400;
      font-size: 24px;
      line-height: 32px;
    }
    h3 {
      font-weight: 500;
      font-size: 14px;
      line-height: 22px;
      color: rgba(0, 0, 0, 0.4);
      margin: 0;
    }
    .price {
      font-weight: 700;
      font-size: 64px;
      line-height: 72px;
      color: #ec5e41;
      margin: 40px 0;
    }
    .code {
      height: 248px;
      width: 336px;
      background: #f5f5f5;
      border: 1px solid #ebebeb;
      border-radius: 16px;
      overflow: hidden;
      display: flex;
      align-items: center;
      align-content: center;
    }
    .exchange {
      background: #3459d2;
      border-radius: 40px;
      padding: 8px 40px;
      display: inline-block;
      margin-top: 40px;
      color: #ffffff;
      font-weight: 400;
      font-size: 24px;
      line-height: 32px;
    }
    .tips {
      font-weight: 400;
      font-size: 16px;
      line-height: 24px;
      color: rgba(0, 0, 0, 0.4);
      display: block;
      margin-top: 40px;
    }
    #QRCode_header {
      border: 1px solid #ebebeb;
      padding: 8px;
    }
  }
}
.toPage {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 442px;
  height: 40px;
  margin-left: -221px;
  margin-top: -20px;
  border-radius: 4px;
  background: #000;
  padding: 8px 12px;
  z-index: 999;
  color: #fff;
  text-align: center;
  font-size: 16px;
  font-weight: 400;
  line-height: 24px;
  a {
    color: #20f53b;
    margin-left: 8px;
  }
  .el-icon-error {
    position: absolute;
    width: 24px;
    height: 24px;
    top: -12px;
    right: -12px;
    cursor: pointer;
    color: #000;
  }
}
</style>
<style lang="scss">
.payment {
  .code {
    .el-input__inner {
      border: none;
      background: none;
      height: 100%;
      text-align: center;
      color: rgba(0, 0, 0, 1);
      font-weight: 400;
      font-size: 20px;
      line-height: 28px;
    }
  }
}
</style>
