import uniPop from '@/components/uni-popup/uni-popup.vue';
import plateNumber from '@/components/plate-number/plateNumber.vue';
// const app = getApp()
import uni from '@/utils/uniHooks';
import { Dialog, Toast } from 'vant';

const app = {};
import { LICENSE_PLATE_TYPE_ARR } from '@/constants.js';
import {
  kipAddMemberVehicles,
  kipModifyMemberVehicles,
} from '@/utils/api-kip.js';
import { mapState } from 'vuex';

export default {
  components: {
    uniPop,
    plateNumber,
  },
  data() {
    return {
      carInfo: {},
      carType: 0,
      active: null,
      ind: null,
      numArr: ['', '', '', '', '', '', ''],
      vehicleNumber: '',
      licensePlateTypeArr: LICENSE_PLATE_TYPE_ARR,
      preUrl: '',
    };
  },
  created() {
    // 埋点本地化
    this.preUrl = uni.getStorageSync('previousUrl');
    uni.setStorageSync('previousUrl', '/pages/parkingFee/vehicleAddOrEdit.vue');
  },
  mounted() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '绑定车牌号',
      });
    }, 300);
    setTimeout(() => {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#FBFCFF',
        },
      });
    }, 500)
    const params = this.$route.query;
    // console.log(252, params);
    if (params.carType) {
      this.carInfo = {
        ...params,
      };
      this.carType = Number.parseInt(this.carInfo.carType);
      this.numArr = this.carInfo.carno.split('');
      this.vehicleNumber = this.carInfo.carno;
    }
  },
  computed: {
    disabledBtn() {
      // console.log(
      //   190,
      //   this.numArr,
      //   this.numArr.findIndex((val) => !val)
      // );
      return this.numArr.findIndex((val) => !val) !== -1;
    },
    ...mapState({
      custTypeId: (state) => state.custTypeId, // custTypeId: 0 默认版本，1 上海静安 2 上海浦东
    }),
  },
  methods: {
    // 切换车牌类型
    toggleType(index) {
      this.ind = 0;
      this.active = 0;
      this.carType = index;

      if (this.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],
        ];
      }
    },
    // 唤起键盘
    clickShowKeyboard(index) {
      if ( this.carType !== 1 && index === 7) return
      this.ind = index;
      this.active = index;
      // console.log('唤起键盘', this.ind, this.active);
      this.$nextTick(() => {
        // return;
        if (index === 0) {
          this.$refs['plateKeyboard'].openKeyboardCN();
        } else {
          // this.$refs['plateKeyboard'].closeKeyboardCN();
          this.$refs['plateKeyboard'].openKeyboardEN();
        }
      });
    },
    // 接收子组件数据
    updateCarno(val) {
      // console.log(320, val);
      this.numArr = val.numArr;
      this.active = val.active;
      this.ind = val.ind;
      this.vehicleNumber = this.numArr.join('');
    },
    // 车牌号校验
    // isVehicleNumber(vehicleNumber) {
    // 	if (vehicleNumber.length == 7) {
    // 		this.vehicleNumber = vehicleNumber.join("");
    // 		var express =
    // 			/^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/;
    // 		if (!express.test(this.vehicleNumber)) {
    // 			uni.showToast({
    // 				title: "请输入正确的车牌号",
    // 				duration: 2000,
    // 				icon: "none",
    // 			});
    // 			return false;
    // 		}
    // 		return true;
    // 	}
    // 	if (vehicleNumber.length == 8) {
    // 		this.vehicleNumber = vehicleNumber.join("");
    // 		var express =
    // 			/^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$/;
    // 		if (!express.test(this.vehicleNumber)) {
    // 			uni.showToast({
    // 				title: "请输入正确的车牌号",
    // 				duration: 2000,
    // 				icon: "none",
    // 			});
    // 			return false;
    // 		}
    // 		return true;
    // 	}
    // },
    handleAddLicensePlateByKipMember() {
      // console.log('handleAddLicensePlateByKipMember执行');
      uni.showLoading({
        title: '加载中',
      });
      const params = {
        licensePlateType: this.licensePlateTypeArr[this.carType].value,
        vehicleNo: this.vehicleNumber,
      };
      let confirmType;
      this.$md(params);
      if (this.carInfo.id) {
        params.id = this.carInfo.id;
        kipModifyMemberVehicles(
          params,
          JSON.parse(uni.getStorageSync('handleUser'))
        )
          .then((result) => {
            uni.hideLoading();
            if (result && result.code == '000000') {
              if (result.data) {
                Toast({
                  message: '修改车牌成功',
                  position: 'top',
                  onClose: () => {
                    this.$router.replace({
                      path: `vehicleManagement`,
                    });
                  }
                });
              }
            } else {
              const message = result.message || '修改车牌失败';
              Toast({
                message: message,
              });
            }
          })
          .catch((err) => {
            uni.hideLoading();
            Toast({
              message: '修改车牌失败',
              position: 'top',
            });
          });
      } else {
        kipAddMemberVehicles(
          params,
          JSON.parse(uni.getStorageSync('handleUser') || '{}')
        )
          .then((result) => {
            uni.hideLoading();
            // const result = resp.data;
            if (result && result.code == '000000') {
              if (result.data) {
                Toast({
                  message: '绑定车牌成功',
                  position: 'top',
                  onClose: () => {
                    this.$router.replace({
                      path: `vehicleManagement`,
                    });
                  }
                });
               /* Dialog.alert({
                  message: '绑定车牌成功',
                  confirmButtonColor: '#333',
                }).then(() => {
                  // on confirm
                  this.$router.replace({
                    path: `vehicleManagement`,
                  });
                  // this.$router.back();
                });*/
                // setTimeout(() => {
                //   // this.$router.back();
                //   this.$router.replace({
                //     path: '/vehicleManagement',
                //   });
                // }, 1500);
              }
            } else {
              const message = result.message || '绑定车牌失败';
              Toast({
                message: message,
                position: 'top',
              });
              /* Dialog.alert({
               message: message,
               confirmButtonColor: '#333',
               }).then(() => {
               // on confirm
               // this.$router.back();
               }); */
            }
          })
          .catch((err) => {
            uni.hideLoading();
            // console.log(366);
            // console.error(err);
            // uni.showToast({
            //   title: '绑定车牌失败',
            //   duration: 2000,
            //   icon: 'none',
            // });

            Toast({
              message: '绑定车牌失败',
            });

            /* Dialog.alert({
             message: '绑定车牌失败',
             confirmButtonColor: '#333',
             }).then(() => {
             // on confirm
             // this.$router.back();
             }); */
          });
      }
    },
  },
};
