<template>
  <div class="box" ref="boxRef">
    <a v-if="success">√</a>
    <div class="rec" :style="recStyle">
      <div class="rect" ref="rectRef">
        {{ labelText }}
        <div class="silde" ref="sildeRef" :style="sildeStyle" @mousedown="onMouseDown">
          <p class="silde-text">>></p>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  modelValue: { type: Boolean, default: false }
})
const emit = defineEmits(['update:modelValue', 'passed'])

const boxRef = ref(null)
const rectRef = ref(null)
const sildeRef = ref(null)

const changeX = ref(0)
const success = ref(false)

watch(
  () => props.modelValue,
  (val) => {
    success.value = !!val
    if (!val) changeX.value = 0
  },
  { immediate: true }
)

const recStyle = computed(() => ({
  width: `${changeX.value}px`,
  color: success.value ? 'white' : ''
}))

const sildeStyle = computed(() => ({
  left: `${changeX.value}px`,
  background: success.value ? 'white' : 'white'
}))

const labelText = computed(() => (success.value ? '验证成功' : '拖拽验证'))

function onMouseDown(e) {
  if (success.value) return
  const rectWidth = rectRef.value?.offsetWidth || 400
  const sildeWidth = sildeRef.value?.offsetWidth || 40
  const maxX = rectWidth - sildeWidth
  const initX = e.clientX

  const onMouseMove = (ev) => {
    const delta = ev.clientX - initX
    changeX.value = Math.max(0, Math.min(delta, maxX))
    if (changeX.value >= maxX) {
      success.value = true
      emit('update:modelValue', true)
      emit('passed')
      cleanup()
    }
  }

  const onMouseUp = () => {
    if (!success.value) {
      changeX.value = 0
      emit('update:modelValue', false)
    }
    cleanup()
  }

  const cleanup = () => {
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)
  }

  document.addEventListener('mousemove', onMouseMove)
  document.addEventListener('mouseup', onMouseUp)
}
</script>

<style scoped>
.box {
  cursor: pointer;
  height: 40px;
  width: 400px;
  line-height: 40px;
  text-align: center;
  position: relative;
  background-color: #e8e8e8;
  border: 1px solid #D9D9D9;
}

.rec {
  position: absolute;
  left: 0;
  top: 0;
  width: 0;
  height: 100%;
  background: #00b894;
}

.rect {
  position: relative;
  width: 400px;
  height: 100%;
}

.silde {
  position: absolute;
  height: 38px;
  width: 40px;
  background: #fff;
  left: 1px;
  top: 1px;
  transform: translateY(0px);
}
.silde-text {
  font-size: 14px;
  color: #000000;
}
.silde img{
  width: 100%;
}
a{
  width: 40px;
  height: 100%;
  position: absolute;
  right: 0;
  bottom: 0;
  display: inline-block;
}
</style>