<template>
  <div class="graphic-verification-code-container">
    <div style="display: flex;align-items: center;">
      <el-input
        :value="inputCode" maxlength="6" type="text" auto-complete="off"
        style="width: 63%;max-width: 200px;"
        placeholder="请输入验证码" @input="handleCodeInput" @keyup.enter.native="$emit('enter-down')"
      >
        <template #prefix>
          <svg-icon icon-class="password" class="el-input__icon input-icon" />
        </template>
      </el-input>
      <div style="margin-left: 8px;">
        <el-button type="primary" :loading="codeLoading" @click="handleGainVerify">
          <span v-if="!codeLoading">获取验证码</span>
          <span v-else>{{ codeCount }} s</span>
        </el-button>
      </div>
    </div>
    <el-dialog
      :visible.sync="isShowGraphicVerificationDialog" v-bind="{ closeOnClickModal: false, width: '600px', title: '滑动码验证' }"
      append-to-body
    >
      <div>
        <div style="margin: 28rpx 0 0;">
          <SliderCaptcha
            v-model="slideVisible" :options="slideOptions" :loading="slideLoading"
            @check="handleConfirmSlide" @close="isShowGraphicVerificationDialog = false" @refresh="getSliderOptions"
            @error="getSliderOptions"
          >
            <template #title>安全验证</template>
            <template #successText>验证通过</template>
            <template #errorText>
              <text style="color: #dc362e;">是不是太难了，换一个</text>
            </template>
            <template #tips>拖动下方滑块完成拼图</template>
            <template #question>请尽快完成滑动自定义提示</template>
          </SliderCaptcha>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SliderCaptcha from './SliderCaptcha'
import { getCode, getVerificationImageCaptchaApi } from '@/api/user'
import { getUpdatePhoneCode, getPrivacyCode } from '@/api/privacy'

export default {
  name: 'GraphicVerificationCode',
  components: {
    SliderCaptcha
  },
  props: {
    phone: {
      type: [String, Number],
      default: ''
    },
    apiType: {
      type: [String, Number],
      default: 'default' // default, update, privacy
    }
  },
  data() {
    return {
      inputCode: '',
      codeTimer: '',
      codeLoading: false,
      codeCount: '',

      isShowGraphicVerificationDialog: false,
      slideVisible: false,
      slideLoading: false,
      slideOptions: {
        cutoutImage: '',
        shadeImage: '',
        sliderKey: '',
        sliderY: ''
      }
    }
  },
  mounted() { },
  methods: {
    handleCodeInput(e) {
      console.log(e)
      this.inputCode = e
      this.$emit('input', this.inputCode)
    },
    // 获取验证码
    async getVerificationCode() {
      if (!this.phone) {
        this.$message.error('请填写电话号码')
        return
      }
      try {
        let _api
        if (this.apiType === 'update') {
          _api = getUpdatePhoneCode
        } else if (this.apiType === 'privacy') {
          _api = getPrivacyCode
        } else {
          _api = getCode
        }
        const res = await _api({ phone: this.phone, x: '0', y: '0' })
        this.$message({
          message: '发送成功，请注意查看手机短信',
          type: 'success'
        })
        if (!this.codeTimer) {
          this.codeLoading = true
          this.codeTimer = setInterval(() => {
            if (this.codeCount > 1 && this.codeCount <= 60) {
              this.codeCount--
            } else {
              clearInterval(this.codeTimer) // 清除定时器
              this.codeTimer = null
              this.codeLoading = false
            }
          }, 1000)
        }
      } catch (e) {
        console.log(e)
      }
    },

    async handleGainVerify() {
      if (!this.phone) {
        this.$message.error('请填写电话号码')
        return
      } else if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        this.$message({
          message: '请输入正确手机号',
          type: 'warning'
        })
        return
      }
      this.isShowGraphicVerificationDialog = true
      this.slideVisible = true
      this.getSliderOptions()
    },
    getSliderOptions() {
      this.slideLoading = true
      getVerificationImageCaptchaApi({ type: 'slide' })
        .then((res) => {
          this.slideOptions = {
            cutoutImage: res.data.cutoutImage,
            shadeImage: res.data.shadeImage,
            sliderKey: 'key',
            sliderY: res.data.y
          }
          this.slideLoading = false
        })
    },
    handleConfirmSlide({ sliderKey, sliderX, done, error }) {
      this.slideLoading = true
      console.log(sliderX, this.slideOptions.sliderY)
      let _api
      if (this.apiType === 'update') {
        _api = getUpdatePhoneCode
      } else if (this.apiType === 'privacy') {
        _api = getPrivacyCode
      } else {
        _api = getCode
      }
      _api({ phone: this.phone, x: sliderX, y: this.slideOptions.sliderY, xxx: sliderKey })
        .then((res) => {
          this.$emit('success-verify', true)
          this.slideLoading = false
          done()
          if (!this.codeTimer) {
            this.codeLoading = true
            this.codeCount = 60
            this.codeTimer = setInterval(() => {
              if (this.codeCount > 1 && this.codeCount <= 60) {
                this.codeCount--
              } else {
                clearInterval(this.codeTimer) // 清除定时器
                this.codeTimer = null
                this.codeLoading = false
              }
            }, 1000)
          }
          this.isShowGraphicVerificationDialog = false
          this.$message({
            message: '发送成功，请注意查看手机短信',
            type: 'success'
          })
        })
        .catch(() => {
          this.slideLoading = false
          error()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.graphic-verification-code-container {
	width: 100%;
	box-sizing: border-box;
}
</style>
