import plateNumber from '@/components/plate-number/plateNumber.vue';
import { REG_SOURCE } from '@/constants';
import LoginDom from '@/components/Login/Login.vue';
import { mapState } from 'vuex';
import { initWxJsSdkConfig } from '@/utils/login';
import { getPlatform,requestInit } from '@/utils/index';
import { wxToLoginCallback, getUrlParams } from '@/utils';

const app = {
  globalData: {
    regSource: '',
  },
};
import uni from '@/utils/uniHooks';
// import blueCom from '../components/blue/home.vue';
// import greenCom from '../components/green/home.vue';
// import officeBlueCom from '../components/officeBlue/home.vue';
// import purpleCom from '../components/purple/home.vue';
import { parkingLots, qrCodes, unlicensedCarCheckIn } from '@/api/parking';

export default {
  components: {
    plateNumber,
    LoginDom,
    // blueCom,
    // greenCom,
    // officeBlueCom,
    // purpleCom,
  },
  data() {
    return {
      vehicleMgt_content_index: -1, //历史车辆选中
      carType: 0, //车辆类型
      init_ch: false, // 字体超出隐藏显示
      search_price: false, //查询按钮隐藏显示
      parkInfoEntity: {},
      show_chinese: false, //是否显示汉字键盘
      show_allBoard: false, //是否显示英文数字键盘
      plate_number: '', //车牌号
      description: '', // 车场描述
      ind: null,
      numArr: ['', '', '', '', '', '', ''],
      active: null,
      carList: [], // 车辆列表
      classifyList: ['燃油车牌', '新能源', '特殊车牌'], // 车牌类型
      vehicleNumber: '',
      localimgPic: '',
      hourMoney: '',
      showSq: false,
      blueHeadBg: 'parkingFee/fee-head-bg.png',
      picUrl: this.$picUrl,
      colorAry: ['', '-blue', '-green'],
      openId: null,
      options: null,
      preUrl: '',
      tabbarActive: '手动缴费',
      supportUnlicensed: false, // 控制当前site，是否使用无牌车
      qrCodeHistory: ''
      // custTypeId: 0,
    };
  },
  computed: {
    disabledBtn() {
      return this.numArr.filter((val) => !val).length > 0;
    },
    ...mapState({
      groupId: (state) => state.groupId,
      openid: (state) => state.openid,
      mallId: (state) => state.mallId,
      kipUserId: (state) => state.kipUserId,
      userInfo: (state) => state.userInfo,
      member: (state) => state.member,
      mobile: (state) => state.mobile,
      custTypeId: (state) => state.custTypeId,
      unlicensedCar: (state) => state.order.unlicensedCar,
      // 如果是扫码进入的无牌车
      unlicensedInfo: (state) => state.unlicensedInfo,
      endlessLoop: (state) => state.endlessLoop,
      source: (state) => state.source,
    }),
  },
  beforeRouteLeave(to, from, next) {
    this.$store.commit('cachedViews/DEL_CACHED_VIEW', to);
    next();
  },
  watch: {
    openid() {
      if (this.openid) {
        this.getParkInfo();
        this.showSq = false;
      }
    },
    unlicensedInfo:{
      handler(){
        // const member = uni.getStorageSync('member');
        // if(!member) return // 如果用户走未登录流程的话
        // 不论是否出入场，都使用此函数获取 gateId（闸口机器的ID）
        if (this.unlicensedInfo?.type && /unlicensedOut|unlicensedIn/.test(this.unlicensedInfo.type) && this.endlessLoop.length === 0) {
          // 此处记录扫码流程执行次数。如果超过一次则不再执行
          this.$store.commit('SET_ENDLESS_LOOP', this.unlicensedInfo.type);
          this.$nextTick(() => {
            this.qrCodesRule(this.unlicensedInfo.code);
          })
        }
      },
      immediate:true //true就表示会立即执行
    }
  },
  async mounted() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '停车缴费',
      });
    }, 300);
    setTimeout(() => {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#FBFCFF',
        },
      });
    }, 500)
    const platform = getPlatform();
    if (platform === 'micromessenger') {
      await initWxJsSdkConfig(['checkJsApi', 'scanQRCode']);
    }
    const member = uni.getStorageSync('member');
    const openid= uni.getStorageSync('openid');
    // console.log(openid)
    // 如果用户未登录的话，返回之后，重新获取数据用户的基础数据
    if (!member && window?.toWXSendMsg) {
      /*wxToLoginCallback('parkingFee', (options) => {
        console.log('用户是扫码进来的125', this.unlicensedInfo);
        console.log('用户是扫码进来的126', options);
        this.$store.commit('SET_IS_INIT', false);
        // 请求 projectId
        window.toWXSendMsg({
          type: 'getProjectId',
          options: {},
        });
        window.subscribe('projectId', (newOptions) => {
          console.log('用户是扫码进来的134', newOptions);
          this.$store.dispatch('baseInit', {
            options: newOptions,
            callback: () => {
              this.$nextTick(( ) => {
                requestInit();
                this.getParkInfo();
                this.$store.commit('SET_IS_INIT', true);
                this.$nextTick(() => {
                  // 如果是无牌车的扫码出入场
                  if(options?.options?.type && /unlicensedIn|unlicensedOut/.test(options.options.type)) {
                    this.$store.commit('SET_UNLICENSED_INFO', options.options);
                    this.qrCodesRule(options.options.code);
                  }
                })
              })
            },
          });
        });
      });*/
    }
    // console.log(136, this.openid);
    if (openid) {
      this.getParkInfo();
      this.showSq = false;
    } else {
      const regSource = REG_SOURCE.PARKING;
      app.globalData.regSource = regSource;
      if (this.options?.regSource) {
        app.globalData.regSource = REG_SOURCE[this.options?.regSource];
      }
      if (this.options?.tpName) {
        app.globalData.tpName = this.options?.tpName;
      }
      this.showSq = true;
    }
  },
  methods: {
    toggleType(carType) {
      this.ind = 0;
      this.active = 0;
      this.carType = carType;
      if (carType === 1) {
        this.numArr = [
          this.numArr[0],
          this.numArr[1],
          this.numArr[2],
          this.numArr[3],
          this.numArr[4],
          this.numArr[5],
          this.numArr[6],
          this.numArr[7],
        ];
      } else {
        this.numArr = [
          this.numArr[0],
          this.numArr[1],
          this.numArr[2],
          this.numArr[3],
          this.numArr[4],
          this.numArr[5],
          this.numArr[6],
        ];
      }
    },
    // 获取停车场信息
    getParkInfo: async function () {
      uni.showLoading({
        title: '加载中',
      });
      try {
        console.log('加载车场信息', this.$store.state.lbsId);
        // const res = await parkingLots('8aaa82ea804d07cd0180516ff03b0008'); // TODO: 临时写死
        const res = await parkingLots(this.$store.state.lbsId); // TODO: 临时写死
        console.log(res);
        let reg = /[;；]/g;
        this.description = res?.description?.replace(reg, '\r\n').replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>');
        this.supportUnlicensed = res.supportUnlicensed || false
        const carList = uni.getStorageSync('carList');
        if (carList) {
          this.carList = JSON.parse(carList);
        }
      } catch (e) {
        console.log(225225, e);
      }
    },
    //缴费说明隐藏显示
    top_display() {
      this.init_ch = !this.init_ch;
    },
    // 唤起键盘
    clickShowKeyboard(index) {
      if ( this.carType !== 1 && index === 7) return
      this.ind = index;
      this.active = index;
      if (index === 0) {
        this.$refs['plateKeyboard'].openKeyboardCN();
      } else {
        this.$refs['plateKeyboard'].closeKeyboardCN();
        this.$refs['plateKeyboard'].openKeyboardEN();
      }
    },
    // 接收子组件数据
    updateCarno(val) {
      this.numArr = [...val.numArr];
      this.vehicleNumber = this.numArr.join('');
      this.active = val.active;
      this.ind = val.ind;
    },
    // 节流函数
    throttle(fc, waitTime = 500, imme = true) {
      if (imme) {
        if (!this.flag) {
          this.flag = true;
          typeof fc === 'function' && fc();
          this.timer = setTimeout(() => {
            this.flag = false;
          }, waitTime);
        }
      } else {
        if (!this.flag) {
          this.flag = true;
          this.timer = setTimeout(() => {
            this.flag = false;
            typeof fc === 'function' && fc();
          }, waitTime);
        }
      }
    },
    // 校验车牌号
    preHandleSearch() {
      if (this.disabledBtn) return
      uni.setStorageSync('carList', [
        ...new Set([this.vehicleNumber, ...this.carList]),
      ].slice(0, 6));
      this.$store.commit('cachedViews/DEL_CACHED_VIEW', {
        name: 'parkingFeeDetail',
      });
      this.$nextTick(() => {
        this.$router.push({
          path: 'parkingFeeDetail',
          query: {
            vehicleNo: this.vehicleNumber,
          },
        });
      })
    },
    // 历史车牌快速查询
    toHandleSearch(vehicleNo) {
      uni.setStorageSync('carList', [...new Set([vehicleNo, ...this.carList])].slice(0, 6));
      this.$store.commit('cachedViews/DEL_CACHED_VIEW', {
        name: 'parkingFeeDetail',
      });

      this.$nextTick(() => {
        this.$router.push({
          path: 'parkingFeeDetail',
          query: {
            vehicleNo,
          },
        });
      });
    },
    // 查询车费信息
    async handleSearch(carno, clickEvent = '$ClickQueryAndPayment') {
      this.vehicleNumber = carno;
      const params = {
        carno,
        mallid: this.mallId,
        openid: this.openid,
        vipcode: this.member?.vipcode,
        mobile: this.mobile,
        groupId: this.groupId,
        createuser: 'sys_miniprogram',
      };
      // 查询缴费按钮埋点
      let [carTypeName, redirectUrl, parkTime] = ['ordinary', '', ''];
      switch (this.carType) {
        case 0:
          carTypeName = 'ordinary';
          break;
        case 1:
          carTypeName = 'newEnergy';
          break;
        case 2:
          carTypeName = 'special';
          break;
      }
      this.$md(params);
      this.$request({
        // url: this.$baseURL + 'api/1.0/park/checkCarIsInPark',
        url: this.$baseURL + 'api/1.0/park/checkCarIsInParkAndCarFee',
        // url: 'http://172.21.90.87:8083/xcrm-api/api/1.0/park/checkCarIsInParkAndCarFee',
        data: params,
        method: 'POST',
        header: JSON.parse(uni.getStorageSync('handleUser')),
        timeout: 60000 * 2, // 120S
        showLoading: {
          title: '加载中',
          duration: 0,
        },
      })
        .then((res) => {
          // console.log(555555, res);
          // ToastObj.clear();
          // uni.hideLoading();
          if (res.data.code === 0) {
            // 清理旧数据
            this.parkingFeeDetailInit();
            uni.setStorageSync('isReload', '3');
            // this.$destroy();
            this.$router.push({
              path: 'parkingFeeDetail',
              query: {
                vehicleNo: carno,
              },
            });
            parkTime = res.data?.data?.serviceMin;
            redirectUrl = '/pages/parkingFee/parkingFeeDetail.vue';
          } else if (res.data.code === 1) {
            // 当前车辆没有查到账单
            this.$router.push({
              path: 'parkingFeePayment',
              query: {
                msg: res.data.msg,
                carno,
              },
            });
            redirectUrl = '/pages/parkingFee/parkingFeePayment.vue';
          } else if (res.data.code === 2) {
            // 月租车
            this.$router.push({
              path: './parkingFeeHint/parkingFeeHint',
              query: {
                carno,
              },
            });

            redirectUrl = '/pages/parkingFee/parkingFeeHint/parkingFeeHint.vue';
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        })
        .catch((err) => {
          // uni.hideLoading();
          uni.showToast({
            title: '网络超时请稍后再试',
            duration: 2000,
            icon: 'none',
          });
          console.log(err);
        });
    },
    // 页面初始清空缓存
    parkingFeeDetailInit() {
      console.log('清理数据');
      // 优惠减免(首停、会员、消费)
      uni.removeStorageSync('checkedList'); // 选中list
      uni.removeStorageSync('checkedTotal'); // 选中count数
      uni.removeStorageSync('discountTotal'); // 减免信息(时长、费用)

      // 停车减免(优惠、积分、停车券)
      uni.removeStorageSync('parkFee');

      // 电子券优惠信息
      uni.removeStorageSync('checkedCouponList'); // 选中list
      uni.removeStorageSync('couponInfo'); // 减免信息(时长、费用)
      uni.removeStorageSync('list'); // 电子券list

      // 总停车优惠信息(时长、费用)
      uni.removeStorageSync('parkingTotal');

      // 应缴金额
      uni.removeStorageSync('servicefee');

      // 订单号
      uni.removeStorageSync('orderno');

      // 纸质优惠券
      uni.removeStorageSync('paperCouponInfo');
    },
    // 缴费记录
    doRouter: function () {
      this.$store.dispatch('clearUnlicensed');
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setStorageSync',
        options: {
          key: 'noLoginParkingFeeWebViewPath',
          value: ''
        },
      });
      uni.setStorageSync('loadData', '');
      if (this.$store.state.isLogin === '3') {
        this.$router.push({ path: 'login' });
        return;
      }
      this.$router.push({ path: 'parkingFeeList' });
    },
    // 车牌管理
    doRouter2: function () {
      this.$store.dispatch('clearUnlicensed');
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setStorageSync',
        options: {
          key: 'noLoginParkingFeeWebViewPath',
          value: ''
        },
      });
      uni.setStorageSync('loadData', '');
      if (this.$store.state.isLogin === '3') {
        this.$router.push({ path: 'login' });
        return;
      }
      uni.removeStorageSync('passLogin');
      this.$router.push({ path: 'vehicleManagement' });
    },
    //停车发票
    doRouter1: function () {
      uni.removeStorageSync('invoiceindex');
      this.$store.dispatch('clearUnlicensed');
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setStorageSync',
        options: {
          key: 'noLoginParkingFeeWebViewPath',
          value: ''
        },
      });
      uni.setStorageSync('loadData', '');
      if (this.$store.state.isLogin === '3') {
        this.$router.push({ path: 'login' });
        return;
      }
      // uni.removeStorageSync('passLogin');
      // TODO: 北京停车场开票
      /* if (this.parkInfoEntity.parkMallCode === 3) {
        uni.navigateToMiniProgram({
          appId: this.$etcpAppId,
          path: this.$etcpAppInvoicePath,
          envVersion: 'release',
        })
        return
      }
      */
      this.$router.push({ path: 'parkingReceipt' });
    },
    //停车券兑换
    doRouter3: function () {
      this.$store.dispatch('clearUnlicensed');
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setStorageSync',
        options: {
          key: 'noLoginParkingFeeWebViewPath',
          value: ''
        },
      });
      uni.setStorageSync('loadData', '');
      window.toWXSendMsg({
        type: 'toPage',
        options: {
          fnName: 'navigateTo',
          url: '/pages/pointsMall/pointsMall?exchangeTypes=2',
        },
      });
    },
    blueComChange(value) {
      console.log('blueComChange', value);
    },
    tabbarActiveEvent(name) {
      this.tabbarActive = name
      if (name === '无牌缴费') {
        this.$store.dispatch('order/unlicensedRule', (code) => {

          // CAR_NOT_FOUND 车场扫描道闸入口，发现无车
          if (code === 'CAR_NOT_FOUND') {

          }
          // CAR_HAS_PLATE 车场扫描道闸入口，发现有牌车
          if (code === 'CAR_HAS_PLATE') {

          }
        })
      }
    },
    // 无牌车闸机扫码
    async scanCarCode() {
      try {
        const runScanFn = (res) => {
          if (res.scanType && res.scanType == 'QR_CODE') {
            console.log(res.result);
            // 获取二维码参数之后，模拟提取参数
            const url = res.result;
            const {path} = getUrlParams(res.result)
            let params = null
            if(path) {
              params = getUrlParams(decodeURIComponent(path))
            }
            /*
            微信扫码之后，处理过的参数 {"code": "e41d4d9dd5534f4aa3de88326a2e6f85", "type": "unlicensedIn#wechat-redirect"}
            */
            if (params?.type.indexOf('wechat-redirect') > -1) {
              params.type = params.type.replace('#wechat-redirect', '');
            }
            console.log('微信扫码之后，处理过的参数', params);
            this.$store.commit('SET_UNLICENSED_INFO', params);
            this.$nextTick(() => {
              this.qrCodesRule(params.code);
            })
            return
          }
          /*
            针对微信的小程序码进行的兼容改造
            微信扫码结束之后的返回参数 {"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);
            },
          });
        }
      } catch (err) {
        console.log(624, err);
      }

    },
    // 处理扫码结果: 组装参数，剩余流程，在 缴费支付页面 实现
    async qrCodesRule(code) {
      try {
        if ( this.qrCodeHistory && this.qrCodeHistory === code ) {
          return
        }
        this.qrCodeHistory = code
        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',
        });
        // return
        if (this.unlicensedInfo?.type === 'unlicensedOut') {
          this.$router.push({
            path: 'parkingFeeDetail',
            query: {
              gateId: qrCodesres.gateId,
              vehicleNo: '',
              type: this.unlicensedInfo.type
            }
          })
          return
        }
        // 如果是无牌车扫码：入场
        const unlicensedCarCheckInres = await unlicensedCarCheckIn({ // 获取无牌车牌
          gateId: qrCodesres.gateId
        });
        // 前往 缴费支付页面
        this.$router.push({
          path: 'parkingFeeMsg',
          query: {
            type: 'success',
            vehicleNo: unlicensedCarCheckInres.vehicleNo
          }
        })
      } catch (err) {
        // 车场扫描道闸入口，发现无车/车场扫描道闸入口，发现有牌车 >>> 停止往下执行,默认提示报错信息
        if (/CAR_HAS_PLATE/.test(err.code)) {
          return
        }
        if (/CAR_NOT_FOUND|INOUT_FAILED|UNLICENSED_PLATE_ACQUISITION_FAILED/.test(err.code)) {
          // 如果是其他错误的话，则继续往下执行
          this.$router.push({
            path: 'parkingFeeMsg',
            query: {
              type: 'fail'
            }
          })
        }
      }
    },
    // 前往支付
    unlicensedToPay() {
      // 无牌车这边去支付的时候，属于场内缴费，需要调用场内缴费的接口 /parking/check-out
      this.$store.commit('SET_ENDLESS_LOOP', '');
      this.toHandleSearch(this.unlicensedCar);
    }
  },
};
