<template>
  <scroll-view scroll-y="true" class="scroll-Y">
    <div class="worp">
      <div class="title">纸质优惠劵减免说明</div>
      <div style="font-size: 28px; color: #808080; padding-top: 12px">
        {{ parkPaperCouponRemark }}
      </div>
    </div>
    <template v-if="paperCouponList.length">
      <div
        class="worp_index1"
        v-for="(item, index) in paperCouponList"
        :key="item.discountCode"
      >
        <div class="worp_index1_index">
          <div class="content">劵码 {{ item.discountCode }}</div>
          <div @click="deleteCoupon(index)"><van-icon name="delete-o" /></div>
        </div>
        <div
          style="
            padding-bottom: 25px;
            margin-left: 20px;
            margin-top: 20px;
            font-size: 28px;
          "
        >
          优惠劵金额 :<span style="color: #064c8a">{{
            item.discountValueMoney | currency
          }}</span>
        </div>
      </div>
    </template>
    <div
      :class="{
        worp_button: true,
        blue_flewx_index3: custTypeId === 1,
        green_flewx_index3: custTypeId === 2,
      }"
      @click="scanCode"
    >
      <img
        :src="require('./static/images/sweep.png')"
        style="width: 35px; height: 35px; margin-right: 20px"
      />
      <div>扫码用劵</div>
    </div>
    <div class="flewx">
      <!-- <div class="flewx-content">应付<span style="color: red;font-size: 32px;padding-left: 20px;">{{actualFee |
      currency}}</span> 元 <span style="color: #8d8d8d;padding-left: 30px;font-size: 28px;">已优惠{{discountFee |
          currency}}元</span>
      </div> -->
      <div class="flewx-content">
        已选<span class="num">{{ paperCouponList.length }}张</span>
        <span class="discountFee"
          >优惠券可优惠{{ discountFee | currency }}</span
        >
      </div>
      <div
        :class="{
          flewx_index3: true,
          blue_flewx_index3: custTypeId === 1,
          green_flewx_index3: custTypeId === 2,
          'btn-disabled': !parkInfo.servicefee,
        }"
        @click="confirm"
      >
        确定
      </div>
    </div>
    <!-- 新的toast -->
    <fui-toast ref="toast"></fui-toast>
  </scroll-view>
</template>

<script>
import uni from '@/utils/uniHooks';
import { Toast } from 'vant';
// const app = getApp()
const app = {};
import { mapState } from 'vuex';
import fuiToast from '@/components/fui-toast/fui-toast.vue';
import { initWxJsSdkConfig } from '@/utils/login';
import { getPlatform } from '@/utils/index';

export default {
  components: {
    fuiToast,
  },
  created() {
    this.servicefee = uni.getStorageSync('servicefee'); // 应缴金额
    this.parkDiscountTotal = uni.getStorageSync('parkingTotal'); // 总停车优惠
    if (uni.getStorageSync('parkFee')) {
      this.parkFee = JSON.parse(uni.getStorageSync('parkFee')); // discount接口返回的数据
      this.parkMallCode = this.parkFee.parkInfoEntity.parkMallCode;
      // 上限金额
      this.maxonetimediscountFee =
        this.parkFee.parkInfoEntity.maxonetimediscount *
        this.parkFee.parkInfoEntity.needmoney;
      this.maxonedaydiscountFee =
        (this.parkFee.parkInfoEntity.maxOneDayHour -
          this.parkFee.parkInfoEntity.ticketandMemeberGradeAndConsumeUseHour) *
          this.parkFee.parkInfoEntity.needmoney || 0;
      if (this.maxonedaydiscountFee < 0) {
        this.maxonedaydiscountFee = 0;
      }

      // 纸质优惠券说明
      if (
        this.parkFee.parkPaperCouponsEntities &&
        this.parkFee.parkPaperCouponsEntities[0]
      ) {
        this.parkPaperCouponRemark =
          this.parkFee.parkPaperCouponsEntities[0].remark;
      }
    }

    // 本页面数据缓存
    this.paperCouponInfo = uni.getStorageSync('paperCouponInfo');
    if (this.paperCouponInfo && this.paperCouponInfo.paperCouponList) {
      // this.paperCouponList = this.paperCouponInfo.paperCouponList;

      this.paperDiscountFee = this.paperCouponInfo.paperDiscountFee;
      this.paperDiscountTime = this.paperCouponInfo.paperDiscountTime;
      this.parkDiscountTotal.feeCopy -= this.paperCouponInfo.paperDiscountFee;
    }
    // this.paperCouponList = [
    //   {
    //     discountCode: '123456',
    //     discountValueMoney: 10
    //   }
    // ];
  },
  data() {
    return {
      parkFee: {}, // 停车规则相关信息
      parkPaperCouponRemark: '', // 纸质优惠券说明
      servicefee: 0, // 应缴金额
      paperDiscountFee: 0, // 纸质优惠券减免金额
      paperDiscountTime: 0, // 纸质优惠券减免时长
      parkDiscountTotal: {}, // 总停车优惠
      paperCouponList: [], // 纸质券list
      paperCouponInfo: {}, // 页面缓存
      maxonetimediscountFee: 0, // 每次优惠上限金额
      maxonedaydiscountFee: 0, // 每天优惠上限金额
      parkMallCode: 1, // 0静安 1浦东 2杭州 3北京 4沈阳 5深圳
      parkInfo: {},
    };
  },
  async mounted() {
    const platform = getPlatform();
    if (platform === 'micromessenger') {
      // this.getTicket();
      await initWxJsSdkConfig(['checkJsApi', 'scanQRCode']);
      // await initWxJsSdkConfig(['checkJsApi', 'scanQRCode']);
      // if (window.wxJsSdkConfigInitPromise) {
      //   await window.wxJsSdkConfigInitPromise;
      // }
    }
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '优惠券',
      });
    }, 300);
  },
  computed: {
    ...mapState({
      custTypeId: (state) => state.custTypeId,
      mallid: (state) => state.mallId,
      openId: (state) => state.openid,
      member: (state) => state.member,
      groupId: (state) => state.groupId,
    }),
    // 实际支付金额
    actualFee() {
      const fee = this.servicefee - this.discountFee;
      return fee > 0 ? fee : 0;
    },
    // 已优惠金额
    discountFee() {
      // 超出上限按上限计算
      if (this.parkMallCode === 1) {
        if (this.parkDiscountTotal.feeCopy > this.maxonetimediscountFee) {
          this.parkDiscountTotal.feeCopy = this.maxonetimediscountFee;
        }
      }
      if (this.parkMallCode === 4) {
        if (
          this.parkDiscountTotal.feeCopy - this.parkDiscountTotal.bonusfee >
          this.maxonedaydiscountFee
        ) {
          this.parkDiscountTotal.feeCopy =
            this.maxonedaydiscountFee + this.parkDiscountTotal.bonusfee;
        }
      }
      return this.parkDiscountTotal.feeCopy + this.paperDiscountFee;
    },
  },
  methods: {
    showToast(text) {
      let options = {};
      options.text = text;
      this.$refs.toast.show(options);
    },
    // 扫码
    scanCode() {
      const runScanFn = (res) => {
        if (res.scanType == 'QR_CODE' && res.scanType) {
          console.log(res.result);
          const url = res.result;
          if (url.indexOf('auth/') === -1) {
            this.getPaperCouponInfo(res.result);
          } else {
            const start = url.indexOf('auth/');
            const end = url.indexOf('?');
            const params = url.slice(start, end).split('/');
            if (params && params.length) {
              const couponCode = params[1];
              this.getPaperCouponInfo(couponCode);
            }
          }
        }
      };
      // 微信小程序
      const platform = getPlatform();
      if (platform === 'miniprogram') {
        window.toWXSendMsg({
          type: 'scanQRCode',
        });
        window.subscribe('scanQRCodeOver', (options) => {
          console.log('微信扫码结束之后的返回参数', options);
          runScanFn(options);
        });
      } else {
        this.$wx.scanQRCode({
          desc: 'scanQRCode desc',
          needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
          // scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
          success: (res) => {
            console.log(237, res);
            runScanFn(res);
            // this.formMsg.deviceCode = res.resultStr;
          },
          error: (res) => {
            console.log(242, res);
          },
        });
      }

      /* uni.scanCode({
        onlyFromCamera: false,
        scanType: ['qrCode'],
        success: (res) => {
          console.log('扫码', res);
          if (res.scanType == 'QR_CODE' && res.scanType) {
            console.log(res.result);
            const url = res.result;
            if (url.indexOf('auth/') === -1) {
              this.getPaperCouponInfo(res.result);
            } else {
              const start = url.indexOf('auth/');
              const end = url.indexOf('?');
              const params = url.slice(start, end).split('/');
              if (params && params.length) {
                const couponCode = params[1];
                this.getPaperCouponInfo(couponCode);
              }
            }
          }
        },
      }); */
    },

    // 根据卡券ID查询卡券信息
    getPaperCouponInfo(couponCode) {
      uni.showLoading({
        title: '加载中',
      });
      const params = {
        groupId: this.groupId,
        mallid: this.mallid,
        couponcode: couponCode,
        orderno: uni.getStorageSync('orderno'),
      };
      this.$md(params);
      uni.request({
        url: this.$baseURL + 'api/1.0/park/queryTicketCount',
        data: params,
        method: 'POST',
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          uni.hideLoading();
          console.log(res);
          if (res.data.code !== 0) {
            // return uni.showToast({
            // 	title: res.data.msg,
            // 	duration: 2000,
            // 	icon: 'none'
            // })
            return Toast({
              message: res.data.msg,
            });
            // return this.showToast(res.data.msg);
          }
          if (res.data.data.type === 2) {
            if (res.data.data.discountType == '0') {
              return Toast({
                message: '该纸质优惠券未激活',
              });
              // return uni.showToast({
              //   title: '该纸质优惠券未激活',
              //   duration: 2000,
              //   icon: 'none',
              // });
            }
            if (res.data.data.discountRuleId == '1') {
              return Toast({
                message: '该纸质优惠券已领取',
              });
              // return uni.showToast({
              //   title: '该纸质优惠券已领取',
              //   duration: 2000,
              //   icon: 'none',
              // });
            }
            if (res.data.data.discountRuleId == '2') {
              return Toast({
                message: '该纸质优惠券已使用',
              });
              // return uni.showToast({
              //   title: '该纸质优惠券已使用',
              //   duration: 2000,
              //   icon: 'none',
              // });
            }
            if (res.data.data.discountRuleId == '3') {
              return Toast({
                message: '该纸质优惠券已核销',
              });
              // return uni.showToast({
              //   title: '该纸质优惠券已核销',
              //   duration: 2000,
              //   icon: 'none',
              // });
            }
          }
          if (this.paperCouponList.length) {
            const index = this.paperCouponList.findIndex(
              (e) => e.discountCode === couponCode
            );
            if (index === -1) {
              this.paperCouponList.push(res.data.data);
              this.paperDiscountFee += Number(res.data.data.discountValueMoney);
              this.paperDiscountTime =
                this.paperDiscountFee / this.parkFee.parkInfoEntity.needmoney;
            }
          } else {
            this.paperCouponList.push(res.data.data);
            this.paperDiscountFee += Number(res.data.data.discountValueMoney);
            this.paperDiscountTime =
              this.paperDiscountFee / this.parkFee.parkInfoEntity.needmoney;
          }

          // this.crossMessage();
        },
        fail: (err) => {
          uni.hideLoading();
          console.log(err);
        },
      });
    },

    // 删除
    deleteCoupon(i) {
      this.paperDiscountFee -= Number(
        this.paperCouponList[i].discountValueMoney
      );
      this.paperDiscountTime =
        this.paperDiscountFee / this.parkFee.parkInfoEntity.needmoney;
      this.paperCouponList.splice(i, 1);
    },

    /**
     * 2021-12-24 微信小群确定取消纸质券限制
     */
    // 超限提示
    // crossMessage() {
    // 	let totalFee = this.parkDiscountTotal.feeCopy;
    // 	if (this.paperCouponInfo && this.paperCouponInfo.paperDiscountFee !== 0) {
    // 		totalFee += this.paperDiscountFee - this.paperCouponInfo.paperDiscountFee;
    // 	} else {
    // 		totalFee += this.paperDiscountFee;
    // 	}
    // 	// 是否受每次最大优惠限制(浦东)
    // 	if (this.parkFee.parkPaperCouponsEntities[0].isMaxLimit !== 1) {
    // 		if (totalFee > this.maxonetimediscountFee) {
    // 			return uni.showToast({
    // 				title: `超出抵扣上限,每次最高可抵扣${this.parkFee.parkInfoEntity.maxonetimediscount}小时`,
    // 				icon: 'none'
    // 			});
    // 		}
    // 	}
    // 	// 浦东总优惠不包含纸质券
    // 	if (this.parkMallCode !== 1) {
    // 		if (totalFee > this.maxonedaydiscountFee) {
    // 			return uni.showToast({
    // 				title: `超出抵扣上限,每天最高可抵扣${this.parkFee.parkInfoEntity.maxonedaydiscount}小时`,
    // 				icon: 'none'
    // 			});
    // 		}
    // 	}
    // },

    // 确认
    confirm() {
      let paperCouponcode = '';
      this.paperCouponList.forEach((e, i) => {
        if (i === this.paperCouponList.length - 1) {
          paperCouponcode += e.discountCode;
        } else {
          paperCouponcode += e.discountCode + '#';
        }
      });
      uni.setStorageSync('paperCouponInfo', {
        paperDiscountFee: this.paperDiscountFee,
        paperDiscountTime: this.paperDiscountTime,
        paperCouponcode: paperCouponcode,
        paperCouponList: this.paperCouponList,
      });
      this.$router.back();
    },
    /*
    // h5获取配置---公众号支付
    getTicket() {
      let self = this;
      var datas = {
        groupId: this.$store.state.groupId,
        mallid: this.$store.state.mallid,
        url: window.location.href.split('#')[0],
      };
      self.$md(datas);
      uni.request({
        url: self.$baseURL + 'api/1.0/login/getTicket',
        method: 'POST',
        data: datas,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          if (res.data.code == 0) {
            self.$wx.config({
              debug: false, // 开启调试模式
              appId: res.data.data.appId, // 必填，公众号的唯一标识
              timestamp: res.data.data.timestamp, // 必填，生成签名的时间戳
              nonceStr: res.data.data.nonceStr, // 必填，生成签名的随机串
              signature: res.data.data.signature, // 必填，签名
              jsApiList: ['chooseWXPay', 'scanQRCode', 'checkJsApi'], // 必填，需要使用的JS接口列表
            });
            self.$wx.ready(function () {
              self.$wx.checkJsApi({
                jsApiList: ['chooseWXPay'],
                success: (res) => {
                  console.log('checked api:', res);
                },
                fail: (err) => {
                  console.log('check api fail:', err);
                },
              });
            });
            self.$wx.error(function (res) {
              console.log('err', res);
            });
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        },
      });
    },
    */
  },
};
</script>

<style lang="less" scoped>
@import '../../styles/common.less';

.scroll-Y {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f4f7ff;
}

.worp {
  padding-left: 30px;
  margin-top: 30px;
  overflow: hidden;

  .title {
    font-size: 30px;
    font-weight: 600;
    color: #333333;
    line-height: 42px;
  }
}

.worp_index1 {
  width: 92%;
  margin-top: 30px;
  margin-left: 4%;
  font-size: 30px;
  background: #fafbff;
  border-radius: 4px;
  border: 1px solid #d8dae0;
}

.worp_index1_index {
  width: 650px;
  height: 60px;
  margin-left: 20px;
  border-bottom: 1px solid #f2f2f2;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 10px;

  .content {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}

.worp_button {
  width: 690px;
  height: 80px;
  border-radius: 50px;
  text-align: center;
  font-size: 30px;
  line-height: 80px;
  color: #fff;
  margin-top: 45px;
  // background-image: linear-gradient(to right, #7e4fa1, #433c7f);
  background: #064c8a;
  margin-left: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.flewx {
  width: 100%;
  height: 100px;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  display: flex;
  align-items: center;
  // padding-bottom: constant(safe-area-inset-bottom);
  // padding-bottom: env(safe-area-inset-bottom);
  padding-bottom: 20px;

  .flewx-content {
    font-weight: 400;
    position: absolute;
    left: 16px;
    font-size: 28px;
    .num {
      color: #064c8a;
    }
    .discountFee {
      color: #ee4d3f;
    }
  }

  .flewx_index3 {
    width: 150px;
    height: 70px;
    border-radius: 45px;
    text-align: center;
    font-size: 28px;
    line-height: 70px;
    color: #fff;
    // background-image: linear-gradient(to right, #7e4fa1, #433c7f);
    background: #064c8a;
    box-shadow: 2px 3px 5px #888888;
    position: absolute;
    right: 16px;
  }
}

.blue_flewx_index3 {
  .color_flewx_index3('blue');
}

.green_flewx_index3 {
  .color_flewx_index3('green');
}

.color_flewx_index3(@value) {
  @color: 'color-@{value}';
  background-image: none !important;
  background-color: @@color !important;
}
</style>
