<template>
  <u-modal
    title="输入图形验证码"
    ref="uModal"
    v-model="picCodeShow"
    @cancel="cancel"
    @confirm="confirm"
    :show-cancel-button="true"
    :async-close="true"
  >
    <view class="code-field">
      <u-field
        label-width="0"
        v-model="code"
        placeholder="请填写验证码"
        :border-bottom="false"
        :focus="true"
        @blur="toTop"
        @focus="codeFocus"
      >
        <u-image
          width="160rpx"
          height="80rpx"
          slot="right"
          :src="codeBaseImg"
          @click="getPicCode"
          mode="aspectFit"
        >
          <u-loading slot="loading"></u-loading>
        </u-image>
      </u-field>
      <text class="error-message">{{ errorMessage }}</text>
    </view>
  </u-modal>
</template>

<script>
export default {
  data() {
    return {
      picCodeShow: this.value,
      codeBaseImg: "",
      preToken: "",
      errorMessage: "",
      code: "",
    };
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    // request 获取图形二维码
    getCheckCodeImg: {
      type: Function,
      default: () => {},
    },
    toTop: {
      type: Function,
      default: () => {},
    },
  },
  methods: {
    async getPicCode() {
      const { success, data } = await this.getCheckCodeImg();

      if (success) {
        const { img, preToken } = data;
        this.codeBaseImg = `data:image/png;base64,${img}`;
        this.preToken = preToken;
      }
    },
    init() {
      this.codeBaseImg = "";
      this.preToken = "";
      this.code = "";
      this.errorMessage = "";
    },
    codeFocus() {
      this.errorMessage = "";
    },
    cancel() {
      this.$emit("input", false);
    },
    confirm() {
      if (!this.code) {
        this.errorMessage = "请输入图形验证码";
        this.$refs.uModal.clearLoading();
        return;
      }

      this.$emit("confirm", {
        checkCode: this.code,
        preToken: this.preToken,
      });
      this.$emit("input", false);
    },
  },
  watch: {
    value: function (val, oldVa) {
      this.picCodeShow = val;

      if (val) {
        this.init();
        this.getPicCode();
      }
    },
  },
};
</script>

<style scoped lang="scss">
.code-field {
  margin: 40rpx 40rpx 40rpx;

  .u-field {
    padding: 0rpx;
    border: 1px solid #e9ebef;
  }

  .error-message {
    color: $u-type-error;
    font-size: 26rpx;
    line-height: 44rpx;
    text-align: left;
  }
}
</style>
