<template>
  <a-row type="flex" justify="center" align="top">
    <a-col :span="10">
      <div class="container">
        <div class="ele-body ele-body-card">
          <h2 style="text-align: center; font-size: 28px; line-height: 3em"
            >申请免费体验</h2
          >
          <a-form
            :label-col="{ md: { span: 4 }, sm: { span: 24 } }"
            :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }"
          >
            <a-form-item label="手机号码" v-bind="validateInfos.customerMobile">
              <a-input
                v-model:value="form.customerMobile"
                placeholder="请输入手机号码"
                :maxlength="11"
                allow-clear
              />
            </a-form-item>
            <a-form-item label="验证码" v-bind="validateInfos.code">
              <div class="login-input-group">
                <a-input
                  placeholder="请输入验证码"
                  v-model:value="form.code"
                  :maxlength="6"
                  allow-clear
                />
                <a-button
                  class="login-captcha"
                  :disabled="!!countdownTime"
                  @click="openImgCodeModal"
                >
                  <span v-if="!countdownTime">发送验证码</span>
                  <span v-else>已发送 {{ countdownTime }} s</span>
                </a-button>
              </div>
            </a-form-item>
            <a-form-item label="企业名称" v-bind="validateInfos.customerName">
              <a-input
                v-model:value="form.customerName"
                placeholder="请输入企业名称"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              label="企业编号"
              v-bind="validateInfos.customerCode"
              style="display: none"
            >
              <a-input
                allow-clear
                :maxlength="20"
                v-model:value="form.customerCode"
              />
            </a-form-item>
            <a-form-item :wrapper-col="{ md: { offset: 5 } }">
              <a-button type="primary" style="width: 100px;" :loading="loading" @click="submit">
                {{ loading ? '提交..' : '提交' }}
              </a-button>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </a-col>
  </a-row>
  <!-- 编辑弹窗 -->
  <a-modal
    :width="340"
    :footer="null"
    title="发送验证码"
    v-model:visible="visible"
  >
    <div class="login-input-group" style="margin-bottom: 16px">
      <a-input
        v-model:value="imgCode"
        placeholder="请输入图形验证码"
        allow-clear
      />
      <a-button class="login-captcha">
        <img alt="" :src="captcha" @click="changeCaptcha" />
      </a-button>
    </div>
    <a-button
      block
      size="large"
      type="primary"
      :loading="codeLoading"
      @click="sendCode"
    >
      立即发送
    </a-button>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, onBeforeUnmount } from 'vue';
  import { useRouter } from 'vue-router';
  import { Form, message } from 'ant-design-vue';
  import { getCaptcha } from '@/api/passport/login';
  import { apply } from '@/api/oa/apply';
  import { phoneReg } from 'ele-admin-pro';
  import { Customer } from '@/api/oa/apply/model';
  import { createCode } from '@/utils/common';

  const useForm = Form.useForm;

  const { push } = useRouter();
  // 加载状态
  const loading = ref(false);
  // 表单数据
  const form = reactive<Customer>({
    customerCode: createCode(),
    customerName: '',
    customerType: undefined,
    customerMobile: '',
    customerAvatar: '',
    customerPhone: '',
    customerContacts: '',
    customerAddress: '',
    comments: '',
    status: '0',
    sortNumber: 100,
    customerId: 0,
    code: ''
  });
  // 表单验证规则
  const rules = reactive({
    customerName: [
      {
        required: true,
        message: '请输入企业名称',
        type: 'string'
      }
    ],
    customerMobile: [
      {
        required: true,
        message: '请输入手机号',
        type: 'string'
      },
      {
        pattern: phoneReg,
        message: '手机号格式不正确',
        type: 'string'
      }
    ],
    code: [
      {
        required: true,
        message: '请输入验证码',
        type: 'string'
      }
    ]
  });
  // 是否显示图形验证码弹窗
  const visible = ref(false);
  // 图形验证码
  const imgCode = ref('');
  // 发送验证码按钮loading
  const codeLoading = ref(false);
  // 验证码倒计时时间
  const countdownTime = ref(0);
  // 图形验证码地址
  const captcha = ref('');
  // 验证码倒计时定时器
  let countdownTimer: number | null = null;

  const { validate, validateInfos, clearValidate } = useForm(form, rules);

  /* 提交 */
  const submit = () => {
    validate()
      .then(() => {
        loading.value = true;
        apply({ ...form })
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            push('/');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 获取图形验证码 */
  const changeCaptcha = () => {
    // 这里演示的验证码是后端返回base64格式的形式, 如果后端地址直接是图片请参考忘记密码页面
    getCaptcha()
      .then((data) => {
        captcha.value = data.base64;
        // 实际项目后端一般会返回验证码的key而不是直接返回验证码的内容, 登录用key去验证, 你可以根据自己后端接口修改
        // text.value = data.text;
        // 自动回填验证码, 实际项目去掉这个
        // form.code = data.text;
        clearValidate();
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  /* 显示发送短信验证码弹窗 */
  const openImgCodeModal = () => {
    if (!form.customerMobile) {
      message.error('请输入手机号码');
      return;
    }
    imgCode.value = '';
    changeCaptcha();
    visible.value = true;
  };

  /* 发送短信验证码 */
  const sendCode = () => {
    if (!imgCode.value) {
      message.error('请输入图形验证码');
      return;
    }
    codeLoading.value = true;
    setTimeout(() => {
      message.success('短信验证码发送成功, 请注意查收!');
      visible.value = false;
      codeLoading.value = false;
      countdownTime.value = 30;
      // 开始对按钮进行倒计时
      countdownTimer = window.setInterval(() => {
        if (countdownTime.value <= 1) {
          countdownTimer && clearInterval(countdownTimer);
          countdownTimer = null;
        }
        countdownTime.value--;
      }, 1000);
    }, 1000);
  };

  onBeforeUnmount(() => {
    countdownTimer && clearInterval(countdownTimer);
  });
</script>

<style lang="less" scoped>
  /* 背景 */
  .login-wrapper {
    padding: 48px 16px 0 16px;
    position: relative;
    box-sizing: border-box;
    background-image: url('@/assets/bg-2.jpeg');
    background-repeat: no-repeat;
    background-size: cover;
    min-height: 100vh;

    &:before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.2);
    }
  }

  /* 卡片 */
  .login-form {
    width: 360px;
    margin: 0 auto;
    max-width: 100%;
    padding: 0 28px 16px 28px;
    box-sizing: border-box;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
    border-radius: 2px;
    position: relative;
    z-index: 2;

    h4 {
      padding: 22px 0;
      text-align: center;
    }
  }

  .login-form-right .login-form {
    margin: 0 15% 0 auto;
  }

  .login-form-left .login-form {
    margin: 0 auto 0 15%;
  }

  /* 验证码 */
  .login-input-group {
    display: flex;
    align-items: center;

    :deep(.ant-input-affix-wrapper) {
      flex: 1;
    }

    .login-captcha {
      width: 102px;
      margin-left: 10px;
      padding: 0;

      & > img {
        width: 100%;
        height: 100%;
      }
    }
  }

  /* 第三方登录图标 */
  .login-oauth-icon {
    color: #fff;
    padding: 5px;
    margin: 0 12px;
    font-size: 18px;
    border-radius: 50%;
    cursor: pointer;
  }

  /* 底部版权 */
  .login-copyright {
    color: #eee;
    text-align: center;
    padding: 48px 0 22px 0;
    position: relative;
    z-index: 1;
  }

  /* 响应式 */
  @media screen and (min-height: 640px) {
    .login-wrapper {
      padding-top: 0;
    }

    .login-form {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%);
      margin-top: -230px;
    }

    .login-form-right .login-form,
    .login-form-left .login-form {
      left: auto;
      right: 15%;
      transform: translateX(0);
      margin: -230px auto auto auto;
    }

    .login-form-left .login-form {
      right: auto;
      left: 15%;
    }

    .login-copyright {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
    }
  }

  @media screen and (max-width: 768px) {
    .login-form-right .login-form,
    .login-form-left .login-form {
      left: 50%;
      right: auto;
      margin-left: 0;
      margin-right: auto;
      transform: translateX(-50%);
    }
  }
</style>
