<template>
  <div :class="[theme, 'bg']">
    <!-- 领取临牌：成功 -->
    <div class="success-box" v-if="type === 'success'">
      <img class="icon" :src="require(`./static/images/unlicensed/success.png`)" />
      <div class="status-title">临牌领取成功</div>
      <div class="status-info">若未正常抬杠，请关闭当前页面重新扫码</div>
      <div class="status-info">或联系车场管理人员处理</div>
      <div class="card-box">
        <img :src="`${require(`./static/images/unlicensed-0.png`)}`" style="margin-left: 10px"/>
        <div class="car-number">
          <div class="number">{{ vehicleNo | formatCarno}}</div>
          <div class="tips">车辆类型：无牌车辆</div>
        </div>
      </div>
      <k-button title="进入首页" disabledColor="#D1D2D9" @click="goHome" />
    </div>
    <!-- 领取临牌：失败 -->
    <div class="fail-box" v-if="type === 'fail'">
      <img class="icon" :src="require(`./static/images/unlicensed/fail.png`)" />
      <div class="status-title">临牌领取失败</div>
      <div class="status-info">请关闭当前页面重新扫码</div>
      <div class="status-info">或联系车场管理人员处理</div>
      <div class="card-box">
        <img :src="`${require(`./static/images/unlicensed-0.png`)}`" style="margin-left: 10px"/>
        <div class="car-number">
          <div class="number">临K ？？？</div>
          <div class="tips">车辆类型：无牌车辆</div>
        </div>
      </div>
      <k-button disabledColor="#D1D2D9" @click="scanCarCode">
        <template v-slot:left>
          <img class="unlicensed-scan" :src="`${require(`./static/images/unlicensed-scan.png`)}`" />
        </template>
        重新扫码
      </k-button>
    </div>
    <!-- 支付成功 -->
    <div class="pay-box" v-if="type === 'pay'">
      <img class="pay-log" :src="require(`./static/images/unlicensed/pay.svg`)" />
      <span class="info">您已缴费成功，欢迎下次光临</span>
    </div>
    <!-- 出场临牌：失败 -->
    <div class="fail-box" v-if="type === 'outFail'">
      <img class="out-fail-log" :src="require(`./static/images/unlicensed/no-car-out.svg`)" />
      <k-button disabledColor="#D1D2D9" @click="scanCarCode">
        <template v-slot:left>
          <img class="unlicensed-scan" :src="`${require(`./static/images/unlicensed-scan.png`)}`" />
        </template>
        重新扫码
      </k-button>
<!--      <span class="info">您已缴费成功，欢迎下次光临</span>-->
    </div>
  </div>
</template>

<script>
import { qrCodes,unlicensedCarCheckIn } from "@/api/parking";
import baseMixins from "@/pages/parkingFee/mixins/base";
import uni from '@/utils/uniHooks';
import { initWxJsSdkConfig } from '@/utils/login';
import { getPlatform,getUrlParams } from '@/utils';
import {mapState} from "vuex";

export default {
  mixins: [baseMixins],
  name: 'parkingFeeMsg',
  data() {
    return {
      type: '',
      vehicleNo: '',
    };
  },
  computed:{
    ...mapState({
      unlicensedInfo: (state) => state.unlicensedInfo,
    })
  },
  async created() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '停车缴费提示',
      });
    }, 300);
    const platform = getPlatform();
    if (platform === 'micromessenger') {
      await initWxJsSdkConfig(['checkJsApi', 'scanQRCode']);
    }
    console.log(this.$route.query);
    this.pageInit()
  },
  mounted() {},
  methods: {
    pageInit(){
      if (this.$route.query?.type) {
        this.type = this.$route.query?.type;
      }
      if (this.type === 'success') {
        this.vehicleNo = this.$route.query?.vehicleNo;
      }
      this.$store.commit('SET_UNLICENSED_INFO', {});
    },
    // 无牌车闸机扫码
    scanCarCode() {
      const runScanFn = (res) => {
        /*
         针对微信的小程序码进行的兼容改造
         微信扫码结束之后的返回参数 {"errMsg": "scanCode:ok", "scanType": "WX_CODE", "charSet": "ISO8859-1", "rawData": "bGsoP3gyT1Aud3QpbW1JeHRfVHJsUjg4JnR5cGU9dW5saWNlbnNlZElu", "path": "pages/automatic/automaticIndex?scene=code%3D9988%26type%3DunlicensedIn"}
         */
        if(res.scanType && res.scanType === 'WX_CODE' && res?.path) {
          const params = getUrlParams(`?${decodeURIComponent(res.path.replace(/.*scene=/g, ''))}`)
          this.$store.commit('SET_UNLICENSED_INFO', params);
          this.$nextTick(() => {
            this.qrCodesRule(params.code);
          })
        }
        // 兜底逻辑，如果是其他小程序扫描，则提取rawData，进行解析提取入参
        if(res.scanType && res.scanType === 'WX_CODE' && !res?.path){
          let path = atob(res.rawData)
          path = path.replace(/.*([a-z0-9]{6}&type)/g, '8b$1')
          const regex = /(\w+)&type=(\w+)/;
          const match = path.match(regex);
          const obj = { code: match[1], type: match[2] };
          this.$store.commit('SET_UNLICENSED_INFO', obj);
          this.$nextTick(() => {
            this.qrCodesRule(obj.code);
          })
        }
      };
      // 微信小程序
      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('H5页面扫码获取到的参数——成功', res);
            runScanFn(res);
            // this.formMsg.deviceCode = res.resultStr;
          },
          error: (res) => {
            console.log('H5页面扫码获取到的参数——失败', res);
            // console.log(242, res);
          },
        });
      }
    },
    // 处理扫码结果: 组装参数，剩余流程，在 缴费支付页面 实现
    async qrCodesRule(code) {
      try {
        const qrCodesres = await qrCodes(code); // 无牌车扫码
        // 记录buildingId，确保 buildingId 是最新的数据
        window.localStorage.setItem('buildingId', qrCodesres.buildingId);
        // 如果是无牌车扫码：出场
        console.log('模拟出场', this.unlicensedInfo?.type);
        this.$store.commit('cachedViews/DEL_CACHED_VIEW', {
          name: 'parkingFeeDetail',
        });
        if (this.unlicensedInfo?.type === 'unlicensedOut') {
          setTimeout(() => {
            this.$router.replace({
              path: 'parkingFeeDetail',
              query: {
                gateId: qrCodesres.gateId,
                vehicleNo: '',
                type: 'unlicensedOut'
              }
            })  
          }, 300)
          return
        }
        // 如果是无牌车扫码：入场
        const unlicensedCarCheckInres = await unlicensedCarCheckIn({ // 获取无牌车牌
          gateId: qrCodesres.gateId
        });
        // 前往 缴费支付页面
        this.$router.replace({
          path: 'parkingFeeMsg',
          query: {
            type: 'success',
            vehicleNo: unlicensedCarCheckInres.vehicleNo
          }
        })
      } catch (err) {
        // 车场扫描道闸入口，发现无车/车场扫描道闸入口，发现有牌车 >>> 停止往下执行,默认提示报错信息
        if (/CAR_HAS_PLATE/.test(err.code)) {
          return
        }
        if (/CAR_NOT_FOUND|UNLICENSED_PLATE_ACQUISITION_FAILED/.test(err.code)) {
          setTimeout(() => {
            // 如果是其他错误的话，则继续往下执行
            this.$router.replace({
              path: 'parkingFeeMsg',
              query: {
                type: this.unlicensedInfo?.type === 'unlicensedOut' ? 'outFail' : 'fail'
                // this.type
              }
            }) 
            this.pageInit()
          }, 300)
        }
      }
    },
    goHome() {
      this.$router.replace({
        path: 'home',
      });
    },
  },
};
</script>

<style lang="less" scoped>
.bg {
  background-color: #FBFCFF;
}
.pay-box {
  text-align: center;
  height: calc(100vh - 100px);
  //margin-top: 84px;
  padding-top: 100px;
  .pay-log {
    width: 523px;
    display: block;
    margin: 0 auto;
  }
  .info {
    font-family: 'PingFang SC';
    font-style: normal;
    font-weight: 400;
    font-size: 28px;
    line-height: 39px;
    text-align: center;
    color: #919baa;
  }
}

.success-box,
.fail-box {
  //margin-top: 123px;
  //padding-top: 123px;
  text-align: center;
  padding: 123px 24px 0;
  .icon {
    width: 80px;
    height: 80px;
    display: block;
    margin: 0 auto 42px;
  }
  .status-title {
    font-family: 'PingFang SC';
    font-style: normal;
    font-weight: 400;
    font-size: 36px;
    line-height: 50px;
    color: #333333;
    margin-bottom: 42px;
  }
  .status-info {
    font-family: 'PingFang SC';
    font-style: normal;
    font-weight: 400;
    font-size: 26px;
    line-height: 40px;
    text-align: center;
    color: #999999;
  }
  .card-box {
    height: 230px;
    margin-top: 42px;
    margin-bottom: 52px;
    background: #fbfcff;
    border: 1px solid #d9dbe0;
    border-radius: 4px;
    display: flex;

    img {
      width: 288px;
      height: 142px;
      display: block;
      margin: auto 0;
    }
    .car-number {
      //margin-top: 68px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      .number {
        font-size: 50px;
        line-height: 56px;
        font-weight: 600;
        color: #333333;
        margin-bottom: 23px;
        letter-spacing: 6.5px;
      }
      .tips {
        color: #999999;
        text-align: left;
      }
    }
  }
  .out-fail-log {
    width: 535px;
    height: 410px;
    display: block;
    margin:  0 auto 68px;
  }
  
  .unlicensed-scan {
    width: 60px;
    height: 60px;
    margin-right: 16px;
  }
}
</style>
