<template>
  <view class="content">
    <z-paging-swiper>
      <u-navbar
        slot="top"
        title-color="#fff"
        :custom-back="customBack"
        :border-bottom="false"
        back-icon-color="#CCE8FF"
        :background="{ background: '#008CFF' }"
        title="我的优惠券"
      >
        <view class="navbar-font" slot="right" @click="jumpPage('/pages/center/coupon/couponRules/couponRules')"> 规则 </view>
      </u-navbar>
      <z-tabs ref="tabs" slot="top" :list="tabList" :current="current" barWidth="90rpx" @change="tabsChange"> </z-tabs>
      <swiper class="swiper" :current="current" @transition="swiperTransition" @animationfinish="swiperAnimationfinish">
        <swiper-item class="swiper-item" v-for="(item, index) in tabList" :key="index">
          <!-- <view class="search-part" v-if="current === 0">
            <u-input class="search-part-input" v-model="form.exchangeCode" placeholder="请输入兑换码" />
            <u-button class="search-part-btn" type="primary" shape="circle" size="medium" @click.stop="handleExchange">兑换</u-button>
          </view> -->
          <coupon-swiper-list-item :tabIndex="index" :currentIndex="current" ref="swiperListItem" />
        </swiper-item>
      </swiper>
      <!-- 绑定车牌 -->
      <u-popup v-model="bindVehiclePop.showChangeVehicleNo" :mask-close-able="false" mode="center" border-radius="20" width="700rpx">
        <view class="popup-vehicleNo">
          <view class="popup-vehicleNo-title">绑定车牌</view>
          <view class="popup-vehicleNo-center"></view>
          <view class="popup-vehicleNo-content">
            <view class="new-plate-number">
              <view class="message-input-wrap" @click="messageInputClick">
                <u-message-input :maxlength="8" width="60" font-size="40" :disabled-keyboard="true" v-model="form.vehicleNo" />
              </view>
            </view>
          </view>
          <view class="popup-vehicleNo-select">
            <u-collapse ref="refValue" :head-style="{ fontSize: '28rpx' }">
              <u-collapse-item title="点击选择车牌" align="center">
                <scroll-view class="popup-vehicleNo-select-scroll" scroll-y="true">
                  <u-cell-group v-if="bindVehiclePop.vehicleList.length">
                    <u-cell-item :title="item.value" v-for="(item, index) in bindVehiclePop.vehicleList" :key="index" :arrow="false">
                      <u-radio-group v-model="form.vehicleNo" @change="radioGroupChange">
                        <u-radio :name="item.value" :key="index"></u-radio>
                      </u-radio-group>
                    </u-cell-item>
                  </u-cell-group>
                  <template v-else>
                    <view class="popup-vehicleNo-select-empty">暂无绑定车牌</view>
                  </template>
                </scroll-view>
              </u-collapse-item>
            </u-collapse>
          </view>
          <view class="vehicleNo-btn">
            <u-button type="primary" :disabled="!form.vehicleNo" :loading="bindVehiclePop.loading" @click="handleBindVehicle">确认</u-button>
            <u-button type="primary" plain @click="cencelBindVehicle">取消</u-button>
          </view>
        </view>
      </u-popup>
      <!-- 选择颜色 -->
      <u-action-sheet :list="bindVehiclePop.colorList" @click="confirmColor" v-model="bindVehiclePop.colorShow" />
      <!-- 车牌号键盘 -->
      <u-keyboard
        ref="uKeyboard"
        mode="car"
        @change="keyboardChange"
        @confirm="keyboardConfirm"
        @backspace="backspace"
        v-model="bindVehiclePop.keyboardshow"
      />
    </z-paging-swiper>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabList: [
        {
          name: '未使用',
          value: 0,
          list: []
        },
        {
          name: '已使用',
          value: 1,
          list: []
        },
        {
          name: '已失效',
          value: 2,
          list: []
        }
      ],
      current: 0,
      form: {
        exchangeCode: '',
        source: 1,
        vehicleNo: '',
        merchantCode: '',
        qrcodeNo: '',
        couponId: ''
      },
      // 绑定车牌
      bindVehiclePop: {
        show: false,
        vehicleList: [],
        showChangeVehicleNo: false,
        colorShow: false,
        loading: false,
        colorList: [
          {
            text: '蓝色',
            colorCode: 0
          },
          {
            text: '黄色',
            colorCode: 1
          },
          {
            text: '黑色',
            colorCode: 2
          },
          {
            text: '白色',
            colorCode: 3
          },
          {
            text: '绿色',
            colorCode: 4
          },
          {
            text: '其他',
            colorCode: 99
          }
        ],
        keyboardshow: false
      }
    };
  },
  onLoad(options) {
    const { merchantCode, qrcodeNo, couponId } = options;
    if (merchantCode && qrcodeNo && couponId) {
      this.form.merchantCode = merchantCode;
      this.form.couponId = couponId;
      this.form.qrcodeNo = qrcodeNo;
      this.bindVehiclePop.showChangeVehicleNo = true;
      this.getCarsList();
    }
  },
  methods: {
    // tabs通知swiper切换
    tabsChange(index) {
      this.current = index;
    },
    // swiper滑动中
    swiperTransition(e) {
      this.$refs.tabs.setDx(e.detail.dx);
    },
    //swiper滑动结束
    swiperAnimationfinish(e) {
      this.current = e.detail.current;
      this.$refs.tabs.unlockDx();
    },
    /**
     * 兑换
     * @date 2022-12-23
     * @returns {any}
     */
    handleExchange() {
      if (this.form.exchangeCode) {
        this.bindVehiclePop.showChangeVehicleNo = true;
        this.getCarsList();
      } else {
        this.$refs.uToast.show({
          title: '请输入兑换码',
          type: 'warning'
        });
      }
    },
    /**
     * @description: 获取我的车辆列表
     * @return {*}
     */
    async getCarsList() {
      const { data } = await this.$u.api.getMycars({ pageNum: 1, pageSize: 100 });
      const vehicleList = [];
      data.rows.forEach((item) => {
        const { vehicleNo } = item;
        vehicleList.push({ label: vehicleNo, value: vehicleNo });
      });
      this.bindVehiclePop.vehicleList = vehicleList;
      await this.$nextTick();
      this.$refs.refValue.init();
    },
    /**
     * 兑换优惠券
     * @date 2022-12-23
     * @returns {any}
     */
    async exchangeCoupon() {
      const { vehicleNo } = this.form;
      if (this.$u.test.carNo(vehicleNo)) {
        try {
          this.bindVehiclePop.loading = true;
          const { code } = await this.$u.api.exchangeCouponApi({ ...this.form });
          if (code === 200) {
            this.$refs.uToast.show({
              title: '兑换成功!',
              type: 'success'
            });
            this.$refs['swiperListItem'][this.current].reloadData();
            setTimeout(() => {
              location.href = location.origin + location.pathname;
            }, 500);
          }
          this.bindVehiclePop.loading = false;
        } catch (error) {
          this.bindVehiclePop.loading = false;
        }
      } else {
        this.$refs.uToast.show({
          title: '请输入有效的车牌号!',
          type: 'error'
        });
      }
    },
    /**
     * 点击输入框弹出车牌键盘
     * @date 2023-02-22
     * @returns {any}
     */
    messageInputClick() {
      this.bindVehiclePop.keyboardshow = true;
      this.form.vehicleNo = '';
    },
    /**
     * 颜色下拉确认
     * @date 2023-02-22
     * @param {any} e
     * @returns {any}
     */
    confirmColor(e) {
      this.bindVehiclePop.colorShow = false;
    },
    /**
     * 按键被点击(点击退格键不会触发此事件)
     * @date 2023-02-22
     * @param {any} val
     * @returns {any}
     */
    keyboardChange(val) {
      // 将每次按键的值拼接到value变量中，注意+=写法
      this.form.vehicleNo += val;
    },
    /**
     * 退格键被点击
     * @date 2023-02-22
     * @returns {any}
     */
    backspace() {
      // 删除value的最后一个字符
      if (this.form.vehicleNo.length) this.form.vehicleNo = this.form.vehicleNo.substr(0, this.form.vehicleNo.length - 1);
    },
    /**
     * 键盘输入完成后确认
     * @date 2023-02-22
     * @returns {any}
     */
    keyboardConfirm() {
      this.bindVehiclePop.colorShow = true;
    },
    /**
     * 单选点击
     * @date 2023-02-22
     * @param {any} e
     * @returns {any}
     */
    radioGroupChange(e) {
      this.form.vehicleNo = e;
    },
    /**
     * 关闭绑定弹框
     * @date 2023-02-22
     * @returns {any}
     */
    cencelBindVehicle() {
      this.form.vehicleNo = '';
      this.bindVehiclePop.showChangeVehicleNo = false;
    },
    /**
     * 提交绑定
     * @date 2023-02-22
     * @returns {any}
     */
    handleBindVehicle() {
      if (this.form.vehicleNo) {
        this.exchangeCoupon();
      } else {
        this.$refs.uToast.show({
          title: '请输入或选择车牌号!',
          type: 'warning'
        });
      }
    },
    /**
     * 调整页面
     * @date 2023-02-22
     * @param {any} url
     * @returns {any}
     */
    jumpPage(url) {
      this.$u.route({
        url
      });
    },
    /**
     * tabbar 返回
     * @date 2023-02-22
     * @returns {any}
     */
    customBack() {
      this.$u.route({
        type: 'switchTab',
        url: 'pages/center/index'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import './myCoupon.scss';
</style>
