<template>
  <uni-popup ref="popup" type="center" :mask-click="false">
    <view class="bg-white rounded overflow-hidden" style="width: 690rpx;">
      <view class="flex items-center justify-between px-15 py-12 border-b">
        <view class="text-lg font-semibold text-dark">身份校验</view>
        <uni-icons type="closeempty" :size="24" color="#999" @click="close"></uni-icons>
      </view>
      <view class="mt-15 px-15 pt-15 text-base text-dark">
        请填写档案人身份证号后四位，以确认身份。
      </view>
      <view class="relative flex justify-between mt-15 px-15 py-12 overflow-hidden">
        <view v-for="i in 4" :key="i"
          class="flex items-center justify-center code-cell text-large font-semibold border-auto text-gray rounded"
          :class="i === activeIndex ? 'text-primary' : 'text-gray'">
          <text :class="i === activeIndex ? 'text-primary' : 'text-dark'">{{ validCodes[i - 1] || '' }}</text>
        </view>
        <input class="code-input" type="idcard" :focus="focus" @focus="onFocus" @blur="onBlur" v-model="codes" />
      </view>
      <view class="footer-buttons">
        <button-footer hideden-shadow confirmText="确定" :showCancel="false" @confirm="confirm()" />
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { toast } from '@/utils/widget';

import ButtonFooter from '@/components/button-footer.vue';

const emits = defineEmits(['close', 'confirm'])
const props = defineProps({
  corpName: {
    type: String,
    default: ''
  },
  customer: {
    type: Object,
    default: () => { }
  },
  visible: {
    type: Boolean,
    default: false
  }
})
const popup = ref()
const codes = ref('');
const validCodes = computed(() => codes.value.replace(/\s/g, '').split('').slice(0, 4));
const codeStr = computed(() => validCodes.value.join(''));
const activeIndex = computed(() => Math.min(validCodes.value.length + 1, 4))
const focus = ref(false)
const timer = ref(null)

function close() {
  emits('close')
}

function confirm() {
  const data = props.customer && typeof props.customer.idNo === 'string' ? props.customer.idNo.slice(-4).toUpperCase() : '';
  const last4 = codeStr.value.toUpperCase();
  if (data.length === 4 && data === last4) {
    emits('confirm')
  } else {
    toast('请输入正确的身份证号后四位')
  }
}

function onFocus() {
  focus.value = true
}

function onBlur() {
  focus.value = false
}

watch(() => props.visible, n => {
  if (n) {
    codes.value = '';
    popup.value && popup.value.open();
    focus.value = false;
    setTimeout(() => focus.value = true, 500)
  } else {
    popup.value && popup.value.close()
  }
})

watch(codes, n => {
  if (timer.value) clearTimeout(timer.value);
  timer.value = setTimeout(() => {
    codes.value = codeStr.value;
  }, 500)
})
</script>

<style lang="scss" scoped>
.code-cell {
  width: 120rpx;
  height: 120rpx;
  font-size: 54rpx;
}

.code-input {
  position: absolute;
  width: 200%;
  height: 100%;
  top: 0;
  left: -100%;
}
</style>