<script setup lang="ts">
import GForm, { type FormListProps } from '@/components/Form';
import GAgreement from '@/components/LoginModal/widget/agreements.vue';
import { ref } from 'vue';
import { Button } from 'vue-devui/button';
import { Message } from 'vue-devui/message';
import { useFormInteraction } from '@/utils/hooks/useForm';
import { checkUsername, verifyRegisterCode, registerByMobile } from '@/api/user';
import { FormRules } from '@/components/LoginModal/form';
import { useGlobalInfoStore } from '@/stores/Global';

const globalStore = useGlobalInfoStore();
globalStore.setShowTools(false);

const cache_countdown = JSON.parse(localStorage.getItem('cache_countdown') as string);

const VerifyPassword:FormListProps[] = [
  {
    type: 'input',
    key: 'password',
    label: '密码',
    required: true,
    rules: FormRules.password,
    props: {
      'show-password': true,
      'autocomplete': true
    }
  },
  {
    type: 'input',
    key: 'pwd',
    label: '确认密码',
    required: true,
    rules: [
      {
        trigger: 'change',
        message: '验证密码与密码不一致',
        validator: (_rule: any, value: string, cb: Function) => {
          FormRef.value.ValidateFormKeys(['password']).then((fromData: any) => {
            if (fromData.type === 'success') {
              clearFormError('password');
              if (FormRef.value.Data.password === value) {
                clearFormError('pwd');
                return cb();
              } else {
                setFormErrorKey({
                  pwd: '验证密码与密码不一致'
                });
                return cb(new Error('验证密码与密码不一致'));
              }
            } else {
              setFormErrorKey({
                password: '密码最少包含一个大写字母、一个小写字母、一个数字'
              });
              return cb(new Error('密码最少包含一个大写字母、一个小写字母、一个数字'));
            }
          });
        }
      }
    ],
    props: {
      'show-password': true,
      'autocomplete': true
    }
  }
];

const requestCheck = {
  trigger: 'change',
  validator: async(_: any, val: string, cb: Function) => {
    const res = await checkUsername(val);
    if (!res.error) {
      if (res.data.data.result) {
        setFormErrorKey({ name: '用户名已存在' });
        return cb(new Error('用户名已存在'));
      }
    }
    return cb();
  }
};

const Form = ref<FormListProps[]>([
  {
    type: 'input',
    key: 'username',
    label: '用户名',
    required: true,
    rules: [...FormRules.name, requestCheck]
  },
  // {
  //   type: 'input',
  //   key: 'nickname',
  //   label: '昵称'
  // },
  {
    type: 'input',
    key: 'mobile',
    label: '手机号码',
    required: true,
    rules: FormRules.mobile,
    defaultValue: cache_countdown?.mobile || ''
  },
  {
    type: 'inputButton',
    key: 'verificationcode',
    label: '验证码',
    required: true,
    rules: FormRules.codes,
    props: {
      autocomplete: true,
      countdown: Boolean(cache_countdown),
      second: cache_countdown?.second || 59,
      aliasKey: 'mobile'
    }
  }
  // ...VerifyPassword
]);

const hwStatus = ref(false);

const {
  errorMsg,
  disabled,
  extraErrors,
  status,
  FormRef,
  cacheForm,
  loading,
  setFormErrorKey,
  clearFormError,
  AgreementWarn,
  PasswordInputSpacing,
  handleSubmit,
  handleCountDown,
  toCountDown,
  handleFormChange,
  handleFormInput,
  handleDisplay,
  saveUserInfo
} = useFormInteraction(Form, false, hwStatus);

if (cache_countdown) {
  cacheForm.countdownSecond = cache_countdown?.second || 59;
  toCountDown('verificationcode');
}

const handleSendMsg = (conf: any) => {
  handleCountDown(conf, async() => {
    const res = await verifyRegisterCode({ mobile: conf.value, type: 'REGISTER' });
    if (!res.error) {
      cacheForm.mobile = conf.value;
      Message.success('验证码已发送到你的手机, 请注意查收');
    }
    return Boolean(!res.error);
  });
};

const handleConfirm = async() => {
  if (!hwStatus.value) {
    extraErrors.agreement = '请阅读并同意华为云用户协议以及隐私政策声明';
    AgreementWarn.value = true;
    setTimeout(() => {
      AgreementWarn.value = false;
    }, 500);
    return;
  }
  handleSubmit(async(res: any) => {
    const data = {
      username: res.username,
      password: res.password,
      nickname: res.nickname || res.username,
      mobile: res.mobile,
      verificationcode: res.verificationcode,
      signup_type: sessionStorage.getItem('loginType')
    };
    const result = await registerByMobile(data);
    if (!result.error) {
      extraErrors.requestInfo = '';
      // const { user_id, mask } = result.data.data;
      // redirectBind({
      //   user_id,
      //   mask,
      //   mobile: res.mobile
      // });
      saveUserInfo(result.data.data);
    } else {
      extraErrors.requestInfo = result.error.error_message;
    }
  });
};

</script>

<template>
  <div class="bg-white h-[100%]">
    <div class="gm-login-register">
      <div class="text-G900 text-[17px] tracking-[.5px] font-bold leading-[20px] my-[20px]">
        欢迎注册
      </div>
      <div class="my-[20px] text-[14px] text-G900 leading-[20px]">
        GitCode 与华为云共同为用户提供代码托管服务，在使用代码托管相关服务时，将同步授权并开通华为云服务，并与重庆开源共创科技有限公司（GitCode的运营主体）关联及共享。
      </div>
      <GForm
        :DataList="Form"
        ref="FormRef"
        show-label
        @count-down="handleSendMsg"
        @change="handleFormChange"
        @complete="handleFormInput"
        layout="horizontal"
        size="lg"
        message-type="none"
      >
        <template #submit>
          <div class="gm-login-register-info gm-login-register-ellipsis">
            {{ errorMsg }}
          </div>
          <div class="mb-[24px]">
            <div :class="['gm-login-register-args', AgreementWarn ? 'shaking-box' : '']">
              <GAgreement v-model="hwStatus" agreement-text="《华为云用户协议》" privacy-text="《华为云隐私政策声明》" @declares="(conf) => handleDisplay(conf.type, 'hw')" />
              <GAgreement v-model="status" agreement-text="《GitCode用户协议》" privacy-text="《GitCode隐私政策》" @declares="(conf) => handleDisplay(conf.type)" />
            </div>
          </div>
          <Button
            color="primary"
            variant="solid"
            @click="handleConfirm"
            :disabled="disabled"
            :loading="loading"
            size="lg"
            class="w-[100%]"
          >
            确认
          </Button>
        </template>
      </GForm>
    </div>
  </div>
</template>

<style lang="scss">
.gm-login-register {
  .devui-input--error {
    // border-color: inherit;
    background-color: inherit;
  }
  .devui-input__inner {
    font-size: 14px;
  }
  .devui-form__label-span {
    padding-left: 10px;
  }
  .devui-form__label--required {
    padding-left: 0;
  }
  .devui-form__label--required:before {
    display: inline-block;
    margin-right: 3px;
  }
  .devui-form__control--horizontal {
    margin-left: 10px;
  }
  .devui-form__label {
    line-height: 40px;
    height: 40px;
    font-size: 14px;
  }
  input[type="password"] {
    letter-spacing: v-bind(PasswordInputSpacing);
  }
  .devui-form__item--horizontal {
    margin-bottom: 12px;
    &:nth-last-child(3) {
      margin-bottom: 8px;
    }
  }
  &-info {
    @apply text-[#F2050D] text-[14px] break-all box-border leading-[20px] pl-[90px] h-[40px];
  }
  &-ellipsis {
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2; /* 设置文本最大行数为2行 */
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
    white-space: normal; /* 在Safari中需要添加这一行来处理部分情况 */
  }
  &-args {
    span {
        display: inline-block;
        font-size: 12px;
      }
  }
  .shaking-box {
    animation: shaking 0.25s ease-in-out;
  }
  @keyframes shaking {
    0%, 100% {
      transform: translateX(0);
    }
    25% {
      transform: translateX(-10px);
    }
    75% {
      transform: translateX(10px);
    }
  }
  @apply box-border p-[32px] m-auto
        sm:w-[414px] w-[100%];
}
.g-footer-box {
    background-color: white;
 }
</style>
