<template>
  <scroll-view scroll-y="true" class="scroll-Y">
    <wx-points-commit ref="wxPointsCommit"></wx-points-commit>

    <view class="worp">
      <view style="font-size: 32rpx">纸质优惠劵减免说明</view>
      <view style="font-size: 28rpx; color: #808080; padding-top: 12rpx">{{
        parkPaperCouponRemark
      }}</view>
    </view>
    <template v-if="paperCouponList.length">
      <view
        class="worp_index1"
        v-for="(item, index) in paperCouponList"
        :key="item.discountCode"
      >
        <view class="worp_index1_index">
          <view class="content">劵码 {{ item.discountCode }}</view>
          <view @click="deleteCoupon(index)"
            ><image
              src="static/images/delete.png"
              style="width: 30rpx; height: 30rpx; margin-right: 20rpx"
          /></view>
        </view>
        <view
          style="
            padding-bottom: 25rpx;
            margin-left: 20rpx;
            margin-top: 20rpx;
            font-size: 28rpx;
          "
          >优惠劵金额 :<text style="color: #ed1c24">{{
            item.discountValueMoney | currency
          }}</text></view
        >
      </view>
    </template>

    <view
      :class="{
        worp_button: true,
        blue_flewx_index3: custTypeId === 1,
        green_flewx_index3: custTypeId === 2,
      }"
      @click="scanCode"
    >
      <image
        src="static/images/sweep.png"
        style="width: 35rpx; height: 35rpx; margin-right: 20rpx"
      />
      <view>扫码用劵</view>
    </view>
    <view class="flewx">
      <view class="flewx-content"
        >应付<text style="color: red; font-size: 32rpx; padding-left: 20rpx">{{
          actualFee | currency
        }}</text>
        元
        <text style="color: #8d8d8d; padding-left: 30rpx; font-size: 28rpx"
          >已优惠{{ discountFee | currency }}元</text
        ></view
      >
      <view
        :class="{
          flewx_index3: true,
          blue_flewx_index3: custTypeId === 1,
          green_flewx_index3: custTypeId === 2,
          'btn-disabled': !parkInfo.servicefee,
        }"
        @click="confirm"
        >确定</view
      >
    </view>
    <!-- 新的toast -->
    <fui-toast ref="toast"></fui-toast>
  </scroll-view>
</template>

<script>
const app = getApp();
import { mapState } from 'vuex';
import fuiToast from '@/components/fui-toast/fui-toast.vue';

export default {
  components: {
    fuiToast,
  },
  onLoad() {
    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;
    }
  },
  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深圳 6天津
    };
  },
  computed: {
    ...mapState({
      custTypeId: (state) => state.custTypeId,
    }),
    // 实际支付金额
    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 || this.parkMallCode === 6) {
        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() {
      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: app.globalData.groupId,
        mallid: app.globalData.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 this.showToast(res.data.msg);
          }
          if (res.data.data.type === 2) {
            if (res.data.data.discountType == '0') {
              return uni.showToast({
                title: '该纸质优惠券未激活',
                duration: 2000,
                icon: 'none',
              });
            }
            if (res.data.data.discountRuleId == '1') {
              return uni.showToast({
                title: '该纸质优惠券已领取',
                duration: 2000,
                icon: 'none',
              });
            }
            if (res.data.data.discountRuleId == '2') {
              return uni.showToast({
                title: '该纸质优惠券已使用',
                duration: 2000,
                icon: 'none',
              });
            }
            if (res.data.data.discountRuleId == '3') {
              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,
      });
      uni.navigateBack();
    },
  },
};
</script>

<style lang="less" scoped>
@import '../../styles/common.less';
.scroll-Y {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f1f1f1;
}
.worp {
  padding-left: 30rpx;
  margin-top: 30rpx;
  overflow: hidden;
}
.worp_index1 {
  width: 92%;
  background-color: #fff;
  margin-top: 30rpx;
  border-radius: 10rpx;
  margin-left: 4%;
  font-size: 30rpx;
}
.worp_index1_index {
  width: 650rpx;
  height: 60rpx;
  margin-left: 20rpx;
  border-bottom: 1px solid #f2f2f2;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 10rpx;
  .content {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
.worp_button {
  width: 690rpx;
  height: 80rpx;
  border-radius: 50rpx;
  text-align: center;
  font-size: 30rpx;
  line-height: 80rpx;
  color: #fff;
  margin-top: 40rpx;
  background-image: linear-gradient(to right, #7e4fa1, #433c7f);
  margin-left: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.flewx {
  width: 100%;
  height: 100rpx;
  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: 20rpx;
  .flewx-content {
    position: absolute;
    left: 16px;
  }
  .flewx_index3 {
    width: 150rpx;
    height: 70rpx;
    border-radius: 50rpx;
    text-align: center;
    font-size: 28rpx;
    line-height: 70rpx;
    color: #fff;
    background-image: linear-gradient(to right, #7e4fa1, #433c7f);
    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>
