<template>
  <div>
    <scroll-view scroll-y="true" class="scroll-Y">
      <div class="parkingFeeCoupon">
        <van-checkbox-group
          v-model="checkedCouponList"
          @change="checkboxChange"
        >
          <div class="card-list" v-if="list.length">
            <div class="item" v-for="(item, index) in list" :key="index">
              <div class="item-image cro">
                <div class="cro_right_top"></div>
                <div class="cro_right_bottom"></div>
                <div class="img">
                  <div>
                    <span style="font-weight: bold; color: #064c8a">￥</span>
                    <span class="itemValue">{{ item.value }}</span>
                  </div>
                  <span style="color: #064c8a; font-size: 30px">停车劵</span>
                </div>
              </div>
              <div class="item-content cro_">
                <div class="cro_left_top"></div>
                <div class="cro_left_bottom"></div>
                <div class="content">
                  <span class="h3">{{ item.ticketName }}</span>
                  <span class="span">有效期至 {{ item.cancelEndTime }}</span>
                </div>
                <div class="erwm_box">
                  <van-checkbox
                    color="#fff"
                    checked-color="#064C8A"
                    :disabled="item.disabled"
                    :name="index"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="no-coupon" v-else>
            <img :src="require('./static/images/no-card.png')" />
            <span class="message">您还没有卡券</span>
          </div>
        </van-checkbox-group>
        <div
          :class="['guide-box', 'mgb-110', !list?.length && 'flex-bottom']"
          v-if="platform === 'miniprogram'"
        >
          <div class="guide-title">优惠券兑换指导</div>
          <div class="guide-desc" @click="navigateToMiniProgram">
            停车优惠券可直接使用，若您还没有兑换或继续兑换，可前往
            <wx-open-launch-weapp
              username=""
              path=""
              env-version=""
              class="wx-open-launch-weapp"
              ><span class="guide-mini"
                >嘉里中心小程序>积分商城</span
              ></wx-open-launch-weapp
            >
            进行兑换
          </div>
        </div>
      </div>
    </scroll-view>
    <div class="flewx">
      <div class="flewx-content">
        <div style="color: #333; font-size: 24px; padding-top: 5px">合计:</div>
        <div class="actualFee-box">
          <div style="color: #333333; font-size: 32px; padding-left: 5px">
            {{ actualFee | currency }}
          </div>
          <div style="color: #ee4d3f; font-size: 24px; padding-left: 5px">
            已优惠{{ discountFee | currency }}元
          </div>
        </div>
      </div>
      <div
        :class="{
          flewx_index3: true,
          blue_flewx_index3: custTypeId === 1,
          green_flewx_index3: custTypeId === 2,
          'btn-disabled': !checkedCouponList.length,
        }"
        @click="confirm"
      >
        确定
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import uni from '@/utils/uniHooks';
// import { initWxJsSdkConfig } from '@/utils/login';
import { Toast } from 'vant';
import { getPlatform } from '@/utils/index';

export default {
  created() {
    // 纸质优惠券
    if (uni.getStorageSync('paperCouponInfo')) {
      this.paperCouponFee =
        uni.getStorageSync('paperCouponInfo').paperDiscountFee || 0;
    }
    this.servicefee = uni.getStorageSync('servicefee'); // 应缴金额
    this.parkDiscountTotal = uni.getStorageSync('parkingTotal'); // 总停车优惠
    // 本页面数据缓存
    this.couponInfo = uni.getStorageSync('couponInfo');
    if (this.couponInfo) {
      this.parkDiscountTotal.feeCopy -= this.couponInfo.couponfee;
    }
    // console.log('定位报错原因', uni.getStorageSync('checkedCouponList'));
    const checkedCouponList = uni.getStorageSync('checkedCouponList');
    console.log('定位报错原因', checkedCouponList);
    this.checkedCouponList = checkedCouponList
      ? typeof checkedCouponList === 'string'
        ? JSON.parse(checkedCouponList)
        : checkedCouponList
      : [];
    // JSON.parse(uni.getStorageSync('checkedCouponList')) || [];
  },
  mounted() {
    // initWxJsSdkConfig([], ['wx-open-launch-weapp']);
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '优惠券',
      });
    }, 300);
    // console.log('查看结果', uni.getStorageSync('list'));
    const list = uni.getStorageSync('list');
    this.parkFee = JSON.parse(uni.getStorageSync('parkFee'));
    this.parkFee.parkInfoEntity.useReduceTime = this.parkFee.parkInfoEntity
      .useReduceTime
      ? this.parkFee.parkInfoEntity.useReduceTime
      : 0;
    this.parkMallCode = this.parkFee.parkInfoEntity.parkMallCode;
    console.log('parkMallCode', this.parkMallCode);
    // 上限金额
    this.maxonetimediscountFee =
      this.parkFee.parkInfoEntity.maxonetimediscount *
      this.parkFee.parkInfoEntity.needmoney;
    // 深圳特殊处理(单位:金额)
    if (this.parkMallCode === 5) {
      this.maxonedaydiscountFee =
        this.parkFee.parkInfoEntity.maxOneDayHour -
          this.parkFee.parkInfoEntity.ticketandMemeberGradeAndConsumeUseHour ||
        0;
    } else {
      this.maxonedaydiscountFee =
        (this.parkFee.parkInfoEntity.maxOneDayHour -
          this.parkFee.parkInfoEntity.ticketandMemeberGradeAndConsumeUseHour) *
          this.parkFee.parkInfoEntity.needmoney || 0;
    }
    if (this.maxonedaydiscountFee < 0) {
      this.maxonedaydiscountFee = 0;
    }
    if (list && list.length > 0) {
      this.list = list;
      // console.log(144, this.checkedCouponList);
      if (this.checkedCouponList.length > 0) {
        const index = this.checkedCouponList[0];
        const item = this.list[index];
        // 根据电子券规则判断是否可选
        this.isDisabledByRule(item);
      } else {
        this.list.map((e) => {
          // 没有选中项初始化状态
          e.checked = false;
          e.disabled = false;
        });
      }
      // 浦东上限控制
      if (
        this.parkMallCode === 1 ||
        this.parkMallCode === 4 ||
        this.parkMallCode === 5
      ) {
        if (this.crossMessage()) {
          this.list.forEach((item) => {
            if (!item.checked) {
              item.disabled = true;
            }
          });
        }
      }
    } else {
      this.list = this.parkFee.memberTicketList;
      console.log(181, this.list);
      this.list.forEach((item) => {
        item.disabled = false;
        item.checked = false;
        if (
          (this.parkMallCode === 1 ||
            this.parkMallCode === 4 ||
            this.parkMallCode === 5) &&
          this.crossMessage()
        ) {
          item.disabled = true;
        }
        if (item.carType == '2') {
          item.value = item.parktime * this.parkFee.parkInfoEntity.needmoney;
        } else if (item.carType == '1') {
          item.value = item.ticketValue;
        }
      });
      // this.list = [
      //   {
      //     value: '50',
      //     ticketName: 'ticketName',
      //     cancelEndTime: 'cancelEndTime',
      //     disabled: false,
      //     checked: false,
      //   },
      // ];
      // console.log(164, this.list);
    }
  },
  data() {
    return {
      parkFee: {}, // 停车规则信息及优惠信息
      list: [], // 电子券列表
      checkedCouponList: [], // 选中的电子券列表
      couponCode: [], // 选中的电子券码组
      servicefee: 0, // 应缴金额
      parkDiscountTotal: {}, // 总停车优惠
      couponInfo: {}, // 页面缓存(电子券优惠)
      maxonetimediscountFee: 0, // 每次优惠上限金额
      maxonedaydiscountFee: 0, // 每天优惠上限金额
      parkMallCode: 1, // 0静安 1浦东 2杭州 3北京 4沈阳 5深圳
      paperCouponFee: 0, // 纸质优惠金额
      platform: getPlatform(),
    };
  },
  computed: {
    // 电子券优惠金额总计
    totalFee() {
      this.couponCode = [];
      let total = 0;
      this.checkedCouponList.forEach((i) => {
        // console.log(221, this.list);
        if (this.list && this.list[i]) {
          this.couponCode.push(this.list[i].couponCode);
          total += this.list[i].value;
        }
      });
      return total;
    },
    // 实际支付金额
    actualFee() {
      const fee = this.servicefee - this.discountFee;
      return fee > 0 ? fee : 0;
    },
    // 已优惠金额
    discountFee() {
      let total = this.parkDiscountTotal?.feeCopy + this.totalFee;
      // 超出上限按上限计算
      if (this.parkMallCode === 1) {
        if (total - this.paperCouponFee > this.maxonetimediscountFee) {
          total = this.maxonetimediscountFee + this.paperCouponFee;
        }
      }
      if (this.parkMallCode === 4) {
        if (
          total - this.paperCouponFee - this.parkDiscountTotal?.bonusfee >
          this.maxonedaydiscountFee
        ) {
          total =
            this.maxonedaydiscountFee +
            this.parkDiscountTotal.bonusfee +
            this.paperCouponFee;
        }
      }
      if (this.parkMallCode === 5) {
        if (total > this.maxonedaydiscountFee) {
          total = this.maxonedaydiscountFee;
        }
      }
      return total;
    },
    ...mapState({
      custTypeId: (state) => state.custTypeId,
    }),
  },
  methods: {
    // 选择回调
    checkboxChange(value) {
      // console.log(269, item);
      // 获取动作项目索引
      // const current = value;
      // const pre = this.checkedCouponList;
      // console.log(273, pre.concat(current));
      // const diff = pre
      //   .concat(current)
      //   .map((i) => {
      //     console.log(281, `${i}`);
      //     return `${i}`;
      //   })
      //   .filter((v, i, arr) => {
      //     console.log(
      //       275,
      //       arr.indexOf(v),
      //       arr.lastIndexOf(v),
      //       arr.indexOf(v) === arr.lastIndexOf(v)
      //     );
      //     return arr.indexOf(v) === arr.lastIndexOf(v);
      //   });
      // console.log(diff);
      this.checkedCouponList = value;
      // console.log('如果有选中项', this.list);
      // return
      // 如果有选中项
      if (this.checkedCouponList.length > 0) {
        const index = this.checkedCouponList[0];
        const item = this.list[index];
        // console.log('根据电子券规则判断是否可选', index, item);
        // 根据电子券规则判断是否可选
        this.isDisabledByRule(item);
      } else {
        this.list.map((e) => {
          // 没有选中项初始化状态
          e.checked = false;
          e.disabled = false;
        });
      }
      // console.log(this.list);
    },

    // 根据电子券规则判断是否可选
    isDisabledByRule(item) {
      // console.log('根据电子券规则判断是否可选', item);
      // 杭州电子券使用上限(单位: 张)
      if (this.parkMallCode === 2) {
        // 达到上限
        if (
          this.checkedCouponList.length ===
          this.parkFee.parkInfoEntity.useTicketNum -
            this.parkFee.parkInfoEntity.couponcodeNum
        ) {
          this.list.forEach((e, i) => {
            if (this.checkedCouponList.findIndex((c) => c == i) === -1) {
              e.disabled = true;
            } else {
              e.checked = true;
            }
          });
          return Toast({
            message: `电子券每天最多可使用${this.parkFee.parkInfoEntity.useTicketNum}张`,
            icon: 'none',
          });
          // return uni.showToast({
          //   title: `电子券每天最多可使用${this.parkFee.parkInfoEntity.useTicketNum}张`,
          //   icon: 'none',
          // });
        } else {
          this.list.forEach((e) => {
            e.disabled = false;
          });
        }
      }

      // 浦东每次缴费超限控制、沈阳每日超限控制
      if (
        (this.parkMallCode === 1 ||
          this.parkMallCode === 4 ||
          this.parkMallCode === 5) &&
        this.crossMessage()
      ) {
        // console.log(331, '浦东每次缴费超限控制、沈阳每日超限控制');
        this.list = this.list.map((e, i) => {
          if (this.checkedCouponList.findIndex((c) => c == i) === -1) {
            e.disabled = true;
            e.checked = false;
          } else {
            e.checked = true;
          }
          return e;
        });
        return;
      }

      // 选中状态赋值
      this.list = this.list.map((e, i) => {
        if (this.checkedCouponList.findIndex((c) => c == i) !== -1) {
          e.checked = true;
        } else {
          e.checked = false;
        }
        // console.log(376, item.superpositionrule);
        // superpositionrule  叠加使用规则 （1不可叠加，2仅同类型可叠加，3可叠加）
        if (item.superpositionrule == '1') {
          if (e.couponCode !== item.couponCode) {
            e.disabled = true;
          }
        } else if (item.superpositionrule == '2') {
          if (e.superpositionrule == '2') {
            // 统计当前(同类型&同可叠加次数)
            let count = 0;
            this.checkedCouponList.forEach((i) => {
              if (this.list[i].ticketId === item.ticketId) {
                count++;
              }
            });
            // console.log(item.ticketId + '合计：' + count);
            if (item.ticketId === e.ticketId) {
              // 超限判断
              if (item.limitUseNum !== 0 && count + 1 > item.limitUseNum) {
                if (e.checked === false) {
                  e.disabled = true;
                }
              } else {
                e.disabled = false;
              }
            } else {
              e.disabled = false;
            }
          } else {
            // 异类
            e.disabled = true;
          }
        } else {
          // 类型3可叠加
          e.disabled = false;
        }
        return e;
      });
    },
    // 是否选中
    isCheck(val) {
      return this.checkedCouponList.findIndex((e) => e == val) !== -1;
    },

    // 跳转小程序
    navigateToMiniProgram() {
      if (this.platform === 'miniprogram') {
        window.toWXSendMsg({
          type: 'navigateToMiniProgram',
          options: {},
        });
      }
    },
    // 超限提示
    crossMessage() {
      let totalFee = this.parkDiscountTotal.feeCopy;
      totalFee += this.totalFee;
      // 浦东每次优惠上限
      if (
        this.parkMallCode === 1 &&
        totalFee - this.paperCouponFee >= this.maxonetimediscountFee
      ) {
        //  uni.showToast({
        //   title: `超出抵扣上限,每次最高可抵扣${this.parkFee.parkInfoEntity.maxonetimediscount}小时`,
        //   icon: 'none',
        // });
        return Toast({
          message: `超出抵扣上限,每次最高可抵扣${this.parkFee.parkInfoEntity.maxonetimediscount}小时`,
          icon: 'none',
        });
        return;
      }
      // 沈阳超限处理(maxonedaydiscountFee 会员、消费、电子券减免)
      if (
        this.parkMallCode === 4 &&
        totalFee - this.paperCouponFee - this.parkDiscountTotal.bonusfee >=
          this.maxonedaydiscountFee
      ) {
        return Toast({
          message: `(会员等级、消费、电子券)每日最高可抵扣${this.parkFee.parkInfoEntity.maxOneDayHour}小时`,
          icon: 'none',
        });
        // return uni.showToast({
        //   title: `(会员等级、消费、电子券)每日最高可抵扣${this.parkFee.parkInfoEntity.maxOneDayHour}小时`,
        //   icon: 'none',
        // });
      }
      // 深圳超限处理
      if (this.parkMallCode === 5 && totalFee >= this.maxonedaydiscountFee) {
        return Toast({
          message: `每日最高可抵扣${this.parkFee.parkInfoEntity.maxOneDayHour}元`,
          icon: 'none',
        });
        // return uni.showToast({
        //   title: `每日最高可抵扣${this.parkFee.parkInfoEntity.maxOneDayHour}元`,
        //   icon: 'none',
        // });
      }
    },

    // 确认
    confirm() {
      uni.setStorageSync('checkedCouponList', this.checkedCouponList);
      uni.setStorageSync('list', this.list);
      uni.setStorageSync('couponInfo', {
        couponfee: this.totalFee,
        couponcode: this.couponCode.join('#'),
      });
      this.$router.back();
    },
  },
};
</script>

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

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

.card-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 24px 20px;
  box-sizing: border-box;
  flex: 1;
  position: relative;

  .item {
    display: flex;
    margin-bottom: 16px;

    .item-image {
      border: 2px solid #f2f2f2;
      border-right: 2px dashed #f2f2f2;
      padding: 16px;
      border-radius: 16px 0 0 16px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #fff;

      &.cro {
        position: relative;
      }

      .img {
        width: 130px;
        height: 130px;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

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

        .itemValue {
          font-size: 50px;
          font-weight: 600;
          color: #064c8a;
        }
      }
    }

    .item-content {
      flex: 1;
      border: 2px solid #f2f2f2;
      border-radius: 0 8px 8px 0;
      padding: 16px;
      box-sizing: border-box;
      background: #fff;
      display: flex;

      &.cro_ {
        position: relative;
      }

      .content {
        display: flex;
        flex-direction: column;
        justify-content: center;
        flex: 1;

        .h3 {
          font-size: 28px;
          line-height: 48px;
          font-weight: 500;
        }

        .span {
          font-size: 24px;
          color: #999999;
          line-height: 40px;
        }
      }

      .erwm_box {
        display: flex;
        align-items: center;
        position: relative;

        img {
          width: 52px;
          height: 52px;
        }

        .tag {
          position: absolute;
          bottom: 0;
          right: 0;
          border-radius: 16px;
          padding: 5px 10px;
          box-sizing: border-box;
          background: #f7931e;
          text-align: center;
          color: #fff;
          width: 122px;
          font-size: 24px;
        }
      }
    }
  }
}

.no-coupon {
  text-align: center;
  img {
    width: 60%;
    display: block;
    margin: 100px auto 20px;
  }

  .message {
    font-size: 36px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #919baa;
    line-height: 50px;
  }
}

// 凹圆角
.cro_left_top,
.cro_left_bottom,
.cro_right_top,
.cro_right_bottom {
  position: absolute;
  width: 8px;
  height: 8px;
  border: 1px solid #eee;
  z-index: 1;
  background: #f4f7ff;
}

.cro_left_top {
  top: -1px;
  left: -1px;
  border-radius: 0px 0px 8px 0px;
  border-bottom: 1px solid #f4f7ff;
  border-top: 1px solid #f4f7ff;
  border-right: 1px solid #f4f7ff;
  border-left: 1px solid #f4f7ff;
}

.cro_left_bottom {
  left: -1px;
  bottom: -1px;
  border-radius: 0px 8px 0px 0px;
  border-top: 1px solid #f4f7ff;
  border-bottom: 1px solid #f4f7ff;
  border-right: 1px solid #f4f7ff;
  border-left: 1px solid #f4f7ff;
}

.cro_right_top {
  top: -1px;
  right: -1px;
  border-radius: 0px 0px 0px 8px;
  border-top: 1px solid #f4f7ff;
  border-bottom: 1px solid #f4f7ff;
  border-left: 1px solid #f4f7ff;
  border-right: 1px solid #f4f7ff;
}

.cro_right_bottom {
  right: -1px;
  bottom: -1px;
  border-radius: 8px 0px 0px 0px;
  border-top: 1px solid #f4f7ff;
  border-bottom: 1px solid #f4f7ff;
  border-left: 1px solid #f4f7ff;
  border-right: 1px solid #f4f7ff;
}

.mgb-110 {
  margin-bottom: 110px !important;
}

.guide-box {
  width: calc(100% - 60px);
  margin-left: 30px;

  .guide-title {
    font-size: 34px;
    font-weight: 400;
    color: #333333;
    line-height: 48px;
    margin-bottom: 22px;
  }

  .guide-desc {
    font-size: 28px;
    font-weight: 400;
    color: #999999;
    line-height: 42px;

    .guide-mini {
      color: #064c8a;
      text-decoration: underline;
      margin: 0 5px;
    }
  }

  .wx-open-launch-weapp {
    display: inline-block;
  }

  &.flex-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 50px;
    z-index: 20;
  }
}

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

  .flewx-content {
    position: absolute;
    left: 16px;
    display: flex;

    .actualFee-box {
      // display: flex;
    }
  }

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

  .blue_flewx_index3 {
    .color-background-color('blue');
  }

  .green_flewx_index3 {
    .color-background-color('green');
  }
}

/deep/ checkbox .wx-checkbox-input.wx-checkbox-input-checked {
  background-color: red !important;
  border-radius: 50% !important;
  border: 1px solid red;
}

/deep/ checkbox .wx-checkbox-input {
  border-radius: 50% !important;
}
</style>
