<template>
  <el-dialog width="400px" :title="title" v-model="show" @close="reset">
    <div class="u-p-15">
      <div v-if="openSwitch" class="u-m-b-20">
        <el-button @click="changeKey('paysSel', index)" v-for="(item, index) in pays" :key="index"
          :type="paysSel == index ? 'primary' : ''">
          {{ item.text }}
        </el-button>
      </div>
      <div class="">
        <el-alert :closable="false" v-if="tips" :title="tips" type="warning" show-icon></el-alert>
      </div>
      <div class="u-m-t-20">
        <template v-if="paysSel == 0">
          <el-form label-width="90px" label-position="left">
            <el-form-item label="应付金额">
              <el-input :value="form.money" disabled></el-input>
            </el-form-item>
            <el-form-item label="付款码">
              <el-input v-model="form.code" @change="inputChange" autofocus placeholder="请扫码或者输入付款码"
                ref="refInputCode"></el-input>
            </el-form-item>
            <div class="u-flex u-row-center u-m-t-50">
              <el-button @click="close">取消</el-button>
              <el-button type="primary" @click="confirm">确定</el-button>
            </div>
          </el-form>
        </template>
        <template v-else>
          <div class="u-text-center">
            <div class="u-flex u-row-center">
              <div class="codeImg">
                <canvas ref="canvas" id="QRCode_header"></canvas>
              </div>

              <!-- <img :src="codeImg" class="codeImg" alt="" /> -->
            </div>
            <div class="color-333 u-font-20 u-m-t-20">{{ form.money }}元</div>
            <div class="color-aaa u-font-12 u-m-t-10">
              <el-icon class="loading-ani">
                <Loading />
              </el-icon>
              <span>等待用户支付</span>
            </div>
          </div>
        </template>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import _ from 'lodash'
import QRCode from "qrcode";
import orderApi from "@/api/order/order";
import payApi from "@/api/order/pay";
import { ElMessage } from "element-plus";
export default {
  props: {
    order: {
      type: Object,
      default: () => ({}),
    },
    price: {
      type: [String, Number],
      default: 0,
    },
    defaultTips: {
      type: String,
      default: "请使用扫码枪扫描付款码",
    },
  },
  data() {
    return {
      title: "支付",
      openSwitch: false,
      tips: "",
      paymentQrcode: "",
      paysSel: 0,
      form: {
        money: "",
        code: "",
      },
      codeImg:
        "https://zhyx.eingdong.com/qrcode/api.php?url=https%3A%2F%2Fzhyx.eingdong.com%2Fcopyright%2F%23%2Fpay%3Fid%3D139451580",
      pays: [
        {
          text: "主扫",
        },
        {
          text: "被扫",
        },
      ],
      number: "0",
      show: false,
      timer: null,
      payPar: {},
    };
  },
  watch: {
    defaultTips(val) {
      this.tips = val;
    },
    price(val) {
      console.log(val);
      this.form.money = Number(val).toFixed(2);
    },
    paysSel(newval) {
      if (newval == 0) {
        this.clear();
        this.tips = "请使用扫码枪扫微信/支付宝收款码";
        this.$nextTick(() => {
          this.$refs.refInputCode.focus();
        });
      } else {
        this.getPayUrl();
        this.tips = "请用户使用微信/支付宝扫描付款码";
        this.startGetOrderInfo();
      }
    },
    number(newval) {
      this.$emit("input", newval);
    },
  },
  methods: {
    inputChange: _.debounce(function (e) {
      this.confirm();
    }, 100),
    to2(n) {
      return n.toFixed(2);
    },
    clear() {
      clearInterval(this.timer);
    },
    async getOrderDetail() {
      const res = await payApi.queryOrderStatus({
        shopId: localStorage.getItem("shopId"),
        orderId: this.order.id,
      });
      console.log(res);
      // if (res == "done") {
      //   ElMessage({
      //     message: "支付已完成",
      //     type: "success",
      //   });
      // }
      if (res != "unpaid") {
        console.log("已支付或取消");
        this.close();
        this.clear();
        if (res == "done") {
          this.$emit("paysuccess");
        }
      }
    },
    startGetOrderInfo() {
      clearInterval(this.timer);
      this.getOrderDetail();
      this.timer = setInterval(() => {
        this.getOrderDetail();
      }, 1000);
    },
    codeInputChange(e) {
      console.log(e);
      // this.$emit("confirm", this.form.code);
    },
    reset() {
      // this.form.money=''
      this.form.code = "";
      this.paysSel = 0;
      this.clear();
    },
    changeKey(key, val) {
      this[key] = val;
    },
    confirm() {
      if (!this.form.code) {
        return ElMessage.error("请输入或扫付款码");
      }
      this.close();
      this.$emit("confirm", this.form.code, this.paysSel ? true : false);
    },
    async getPayUrl() {
      const formdata = { ...this.payPar, ...this.payPar.checkOrderPay };
      delete formdata.checkOrderPay;
      const res = await payApi.orderPayUrl(formdata);
      console.log(res);
      this.paymentQrcode = res;
      this.$nextTick(() => {
        QRCode.toCanvas(
          this.$refs.canvas,
          this.paymentQrcode,
          { width: 160, height: 160 },
          function (error) {
            console.log(error);
          }
        );
      });
    },
    open(data, payType) {
      if (payType == "deposit") {
        // 储值卡
        this.openSwitch = false;
        this.title = "储值卡支付";
      }
      if (payType == "scanCode") {
        this.openSwitch = true;
        this.title = "扫码支付";
      }
      this.show = true;
      this.form.money = Number(data.money).toFixed(2);
      this.payPar = data;
      if (this.openSwitch) {
        // this.getPayUrl();
      }
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.refInputCode.focus();
        }, 100);
      });
    },
    close() {
      this.show = false;
    },
    numberInput(val) {
      console.log(val);
      this.number = `${Number(val)}`;
    },
    keyboradConfirm() {
      this.$emit("confirm", this.number);
    },
  },
  mounted() {
    this.number = `${this.value}`;
    this.tips = this.defaultTips;
  },
};
</script>

<style lang="scss" scoped>
.codeImg {
  width: 164px;
  border: 1px solid rgb(220, 223, 230);
  height: 164px;
  overflow: hidden;
}

@keyframes rotating {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  to {
    -webkit-transform: rotate(1turn);
    transform: rotate(1turn);
  }
}

.loading-ani {
  animation: rotating 2s linear infinite;
}
</style>