<template>
  <div class="main user-layout-register">
    <h3 class="h3-title"><span>欢迎注册</span></h3>
    <h-alert
      v-if="loginErrorMsg"
      type="error"
      show-icon
      style="margin-bottom: 24px"
      :message="loginErrorMsg"
    />
    <h-form
      id="formRegister"
      layout="vertical"
      ref="formRegister"
      :model="modelRef"
      :rules="rulesRef"
    >
      <h-form-item name="username">
        <h-input
          size="large"
          type="text"
          placeholder="请设置用于登录的用户名"
          v-model:value="modelRef.username"
        />
      </h-form-item>
      <h-form-item name="password">
        <h-input-password
          size="large"
          @click="handlePasswordInputClick"
          placeholder="请设置您的密码"
          v-model:value="modelRef.password"
        />
      </h-form-item>
      <h-form-item name="password2">
        <h-input-password
          size="large"
          placeholder="请再次输入密码"
          v-model:value="modelRef.password2"
        />
      </h-form-item>
      <h-form-item name="userPhone">
        <h-input size="large" placeholder="请输入您的手机号" v-model:value="modelRef.userPhone">
          <template #addonBefore>
            <h-select size="large" default-value="+86">
              <h-select-option value="+86">+86</h-select-option>
              <h-select-option value="+87">+87</h-select-option>
            </h-select>
          </template>
        </h-input>
      </h-form-item>
      <h-row :gutter="16">
        <h-col class="gutter-row" :span="16">
          <h-form-item name="code">
            <h-input
              v-model:value="modelRef.code"
              size="large"
              type="text"
              placeholder="请输入右侧验证码"
            ></h-input>
          </h-form-item>
        </h-col>
        <h-col class="gutter-row" :span="8">
          <h-image
            :width="104"
            :height="42"
            :preview="false"
            :src="loginCodeInfo.src"
            @click="getLoginCodeData"
          />
        </h-col>
      </h-row>
      <h-form-item>
        <h-button
          size="large"
          type="primary"
          class="register-button"
          :loading="state.registerBtn"
          :disabled="state.registerBtn"
          @click="handleSubmit"
        >
          立即注册
        </h-button>
        <router-link class="login" :to="{ name: 'login' }">使用已有账户登录</router-link>
      </h-form-item>
    </h-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, createVNode, ref } from 'vue';
import { useForm } from 'ant-design-vue/es/form';
import { Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined, CheckCircleOutlined } from '@ant-design/icons-vue';
import { getLoginCode } from '@/api/platform/user/login';
import { postRegister } from '@/api/platform/user/register';
import { useRouter } from 'vue-router';
import md5 from 'js-md5';
import { ICP_CONFIG } from '@/utils/commMethods';

export default defineComponent({
  setup() {
    const router = useRouter();
    const state = reactive({
      time: 60,
      smsSendBtn: false,
      passwordLevel: 0,
      passwordLevelChecked: false,
      percent: 10,
      progressColor: '#FF0000',
      registerBtn: false,
    });
    const modelRef = reactive({
      // 调用通用接口
      lang: 'zhs',
      connect: ICP_CONFIG.connect ?? 'MYSQL',
      productLine: ICP_CONFIG.project, //这个地方会有问题，不能写死，要用全局配置
      //++++++++++++++
      // companyId: 'P_SYS_COMPANY_default',
      // orgId: 'P_SYS_ORG_default',
      // roleId: 'P_SYS_ROLE_default',
      companyId: 'P_SYS_COMPANY_737d41f9e3b14bcfac0cc20f91d29521',
      orgId: 'P_SYS_ORG_4c93bdc2dfc646058a5f244aef7a8680',
      roleId: 'P_SYS_ROLE_3a3b1512e2734165a47c1920c5a2f5c0',
      username: '',
      password: '',
      password2: '',
      userPhone: '',
      code: '',
    });
    const rulesRef = reactive({
      username: [
        { required: true, message: '请输入用户名' },
        { max: 30, message: '用户名最长30位' },
        { pattern: /^[a-z0-9]+$/i, message: '请输入数字、字母' },
      ],
      password: [
        { required: true, min: 6, message: '至少6位密码，区分大小写' },
        { max: 20, message: '密码最长20位' },
        { pattern: /^\w+$/, message: '仅限数字、字母和下划线' },
      ],
      password2: [
        { required: true, message: '至少6位密码，区分大小写' },
        { max: 20, message: '密码最长20位' },
        {
          validator: (_rule: any, value: string) => {
            return new Promise((resolve, reject) => {
              const password = modelRef.password;
              if (value === undefined) {
                reject(new Error('请输入密码'));
              }
              if (value && password && value.trim() !== password.trim()) {
                reject(new Error('两次输入的密码不一致'));
              }
              resolve(null);
            });
          },
        },
      ],
      userPhone: [
        { required: true, message: '请输入手机号' },
        { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' },
      ],
      code: [{ required: true, message: '请输入验证码' }],
    });
    const { validate } = useForm(modelRef, rulesRef);

    const handlePasswordInputClick = () => {
      state.passwordLevelChecked = true;
    };

    // 获取图片验证码
    const loginCodeInfo = reactive({
      key: '',
      image: '',
      src: '',
    });
    // 获取图片验证码
    const getLoginCodeData = () => {
      getLoginCode()
        .then(res => {
          loginCodeInfo.src = 'data:image/png;base64,' + res.data.img;
          loginCodeInfo.key = res.data.uuid;
        })
        .catch(() => {
          loginCodeInfo.src = 'data:image/png;base64,';
        })
        .finally(() => {
          // state.loginBtn = false;
        });
    };
    onMounted(() => {
      getLoginCodeData();
    });
    // 立即注册（表单提交）
    const loginErrorMsg = ref('');
    const handleSubmit = (e: Event) => {
      state.registerBtn = true;
      e.preventDefault();
      validate()
        .then(values => {
          const registerParams = { ...modelRef };
          registerParams.password = md5(values.password);
          registerParams.password2 = md5(values.password);
          registerParams['uuid'] = loginCodeInfo.key;
          postRegister(registerParams)
            .then(res => {
              if (res.code === 200) {
                confirm({
                  status: 'success',
                  okText: '登录',
                  title: '注册成功！',
                  content: '账号已创建成功',
                });
                loginErrorMsg.value = '';
              } else {
                loginErrorMsg.value = res.msg;
                getLoginCodeData();
              }
            })
            .finally(() => {
              state.registerBtn = false;
            });
        })
        .catch(err => {
          console.warn('err', err);
          state.registerBtn = false;
        });
    };
    // 弹窗提示
    const confirm = ({ status, okText, content, title }) => {
      Modal[status]({
        title,
        icon: createVNode(status === 'fail' ? ExclamationCircleOutlined : CheckCircleOutlined),
        content,
        okText,
        cancelText: '关闭',
        closable: false,
        onOk() {
          if (status === 'success') {
            router.push({
              name: 'login',
            });
          } else {
            resetForm();
          }
        },
      });
    };
    // 注册失败，重置表单
    const formRegister = ref(null);
    const resetForm = () => {
      formRegister.value.resetFields();
      getLoginCodeData();
    };
    return {
      state,
      modelRef,
      rulesRef,
      formRegister,
      loginCodeInfo,
      loginErrorMsg,
      getLoginCodeData,
      handleSubmit,
      handlePasswordInputClick,
    };
  },
});
</script>

<style lang="less" scoped>
.user-layout-register {
  width: 440px;
  height: auto;
  opacity: 1;
  background: #fff;
  border-radius: 4px;
  padding: 40px 62px 31px 62px;
  box-shadow: 0 12px 11px 0 rgb(0 0 0 / 10%), 0 -8px 11px 0 rgb(0 0 0 / 10%);
  .h3-title {
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: bold;
    text-align: center;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .register-button {
    width: 50%;
  }

  .login {
    float: right;
    line-height: 40px;
  }
  .prefixIcon {
    color: @primary-color;
    font-size: @font-size-base;
  }
}
</style>
