import uniPop from '@/components/uni-popup/uni-popup.vue';
import { Dialog } from 'vant';
import LoginDom from '@/components/Login/Login.vue';
// const app = getApp()
const app = {};
import {
  kipGetMemberVehicles,
  kipDeleteMemberVehicles,
} from '@/utils/api-kip.js';
import { LICENSE_PLATE_TYPE_ARR } from '@/constants.js';
import { mapState } from 'vuex';
// import authorize from '@/components/authorize/authorize.vue';
import { isCruMarketByKey } from '@/utils/location-util.js';
import MemberCacheTool from '@/utils/member-cache-tool.js';
import { REG_SOURCE } from '@/constants.js';
import uni from '@/utils/uniHooks.js';
// import { vehicles as vehiclesList } from './list';
import { wxToLoginCallback } from '@/utils/index';
import { Toast } from 'vant';

export default {
  components: {
    uniPop,
    // authorize,
    LoginDom,
  },
  computed: {
    ...mapState({
      custTypeId: (state) => state.custTypeId,
      member: (state) => state.member,
      groupId: (state) => state.groupId,
      openid: (state) => state.openid,
      mallid: (state) => state.mallId,
      mobile: (state) => state.mobile,
    }),
    isNoLogin() {
      return JSON.stringify(this.member) === '{}'
    }
  },
  data() {
    return {
      list: [],
      activeId: '',
      activeCarno: '',
      licensePlateList: [],
      isBeijing: false,
      options: null,
      preUrl: '',
      deleteDialogSwitch: false,
      deleteSuccessDialogSwitch: false,
      show: false, // 删除车牌时提示内容
    };
  },

  async created() {
    this.options = this.$route.query;
  },
  async mounted() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '车辆管理',
      });
    }, 300);
    setTimeout(() => {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#FBFCFF',
        },
      });
    }, 500)
    this.$store.dispatch('clearUnlicensed');
    const member = uni.getStorageSync('member');
    if (member && JSON.stringify(this.member) !== '{}') {
      this.getKipMemberVehicles();
    } else {
      wxToLoginCallback('vehicleManagement', (options) => {
        if (options?.noLoginParkingFeeWebView === 'fail') {
          // 如果是用户明确拒绝登录，执行这段逻辑
          setTimeout(() => {
            Toast({
              message: '您还未登录，请登录',
              icon: 'none',
              onClose: () => {
                this.$router.back();
                return
              },
            });
          }, 300)
        } else {
          this.$router.back();
        }
      });
    }
  },
  onUnload() {
    // #ifdef MP-WEIXIN
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    console.log('==> 车牌管理-返回上一页');
    prevPage.setData({
      parkData: 'parkData',
    });
    // #endif
    // #ifdef H5
    uni.setStorage({
      key: 'parkData',
      data: 'parkData',
      success: function () {
        console.log('parkData-success');
      },
    });
    // #endif
  },
  methods: {
    // 添加车牌号
    toAdd() {
      if(this.isNoLogin) return
      this.$router.push({ path: 'vehicleAddOrEdit' });
    },
    // 跳转支付页面
    toPay(carno) {
      if(this.isNoLogin) return
      this.$store.commit('cachedViews/DEL_CACHED_VIEW', {
        name: 'parkingFeeDetail',
      });
      uni.setStorageSync('carList', [...new Set([carno, ...JSON.parse(uni.getStorageSync('carList') || '[]')])].slice(0, 6));
      this.$store.commit('cachedViews/DEL_CACHED_VIEW', {
        name: 'parkingFeeDetail',
      });
      this.$nextTick(() => {
        this.$router.push({
          path: 'parkingFeeDetail',
          query: {
            vehicleNo: carno,
          },
        });
      });
      return
      // 查询车费信息
      uni.showLoading({
        title: '加载中',
      });
      // const openId = MemberCacheTool.getOpenId(app)
      const params = {
        carno,
        mallid: this.mallid,
        openid: this.openid,
        vipcode: this.member?.vipcode,
        mobile: this.mobile,
        groupId: this.groupId,
        createuser: 'sys_miniprogram',
      };
      this.$md(params);
      this.$request({
        url: this.$baseURL + 'api/1.0/park/checkCarIsInPark',
        data: params,
        method: 'POST',
        header: JSON.parse(uni.getStorageSync('handleUser')),
        timeout: 10000,
      })
        .then((res) => {
          // console.log(227, res);
          uni.hideLoading();
          if (res.data.code === 0) {
            this.$router.push({
              path: 'parkingFeeDetail?carno=' + carno,
            });
          } else if (res.data.code === 1) {
            // 当前车辆没有查到账单
            this.$router.push({
              path: 'parkingFeePayment?msg=' + res.data.msg + '&carno=' + carno,
            });
          } else if (res.data.code === 2) {
            // 月租车
            this.$router.push({
              path: './parkingFeeHint/parkingFeeHint?carno=' + carno,
            });
          } 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);
        });
    },
    // 编辑
    toEdit(item) {
      if(this.isNoLogin) return
      if (!item) {
        return;
      }
      const { id, vehicleNo, licensePlateType } = item;
      const carType = LICENSE_PLATE_TYPE_ARR.findIndex(
        (e) => e.value == licensePlateType
      );
      this.$router.push({
        path: `vehicleAddOrEdit?id=${id}&carno=${vehicleNo}&carType=${carType}`,
      });
    },
    activeCarnoFilter(str){
      return str.replace(/(.{2})/, '$1·')
    },
    // 删除
    toDelete(item) {
      this.activeId = item.id;
      this.activeCarno = item.vehicleNo;
      this.show = true

      // Dialog.confirm({
      //   title: '删除已绑定车牌',
      //   message: '是否确认删除已经绑定车牌' + '\n' + this.activeCarno,
      //   confirmButtonColor: '#333',
      // })
      //   .then(() => {
      //     // on confirm
      //     this.doDelete();
      //   })
      //   .catch(() => {
      //     // on cancel
      //     // this.cancelDelete();
      //   });
      // this.deleteDialogSwitch = true;
    },
    doDelete() {
      uni.showLoading({
        title: '加载中',
      });
      const _this = this;
      kipDeleteMemberVehicles(this.activeId)
        .then((result) => {
          uni.hideLoading();
          // console.log(resp)
          // const result = resp.data
          if (result && result.code == '000000') {
            if (result.data) {
              // this.deleteDialogSwitch = false;
              // this.deleteSuccessDialogSwitch = true;
              
              Toast({
                message: '删除成功',
                type: 'success',
                position: 'top',
                duration: 5000,
                className: 'top300',
                icon: require('../static/images/success.svg')
              });
              setTimeout(() => {
                this.getKipMemberVehicles();
              }, 1500)
              // _this.$refs.deleteSuccessDialog.open()
              return;
            }
          }
          const message = result.message || '删除失败';
          uni.showToast({
            title: message,
            duration: 2000,
            icon: 'none',
          });
        })
        .catch((err) => {
          uni.hideLoading();
          console.log(err);
          uni.showToast({
            title: '删除失败',
            duration: 2000,
            icon: 'none',
          });
        });
    },
    cancelDelete() {
      this.deleteDialogSwitch = true;
    },
    confirmDialog() {
      // this.$refs.deleteSuccessDialog.close()
      this.deleteSuccessDialogSwitch = false;

      this.getKipMemberVehicles();
    },
    // 获取会员绑定的车牌列表
    getKipMemberVehicles() {
      // console.log(453);
      uni.showLoading({
        title: '加载中',
      });
      kipGetMemberVehicles()
        .then((result) => {
          uni.hideLoading();
          console.log(result);
          // const result = resp.data
          if (result && result.code == '000000') {
            const data = result.data || [];
            if (data && data.length > 0) {
              // data.forEach((item) => {
              //   const curLicensePlateType = LICENSE_PLATE_TYPE_ARR.find(
              //     (e) => e.value == item.licensePlateType
              //   )
              //   if (curLicensePlateType) {
              //     item.licensePlateTypeDesc = curLicensePlateType.label
              //   }
              // })
              this.licensePlateList = this.setLicensePlateList(data);
            } else {
              this.licensePlateList = [];
            }
            // this.licensePlateList = vehiclesList.data;
          } else {
            const message = result.message || '获取信息失败';
            uni.showToast({
              title: message,
              duration: 2000,
              icon: 'none',
            });
          }
          // console.log(380, this.licensePlateList);
        })
        .catch((err) => {
          uni.hideLoading();
          console.error(err);
        });
      // this.licensePlateList = this.setLicensePlateList(vehiclesList.data);
    },
    setLicensePlateList(data) {
      if (!data.length) return [];
      return data.map((item) => {
        const curLicensePlateType = LICENSE_PLATE_TYPE_ARR.find(
          (e) => e.value == item.licensePlateType
        );
        if (curLicensePlateType) {
          item.licensePlateTypeDesc = curLicensePlateType.label;
        }
        return item;
      });
    },
  },
};
