<template>
  <div class="register">
    <div class="register-container">
      <div class="register-left">
        <div class="brand-area">
          <div class="brand-logo">
            <svg-icon icon-class="system" class="logo-icon" />
          </div>
          <h1 class="brand-title">{{ title }}</h1>
          <p class="brand-desc">华晟ERP订单管理系统</p>
        </div>
      </div>
      <div class="register-right">
        <div class="register-card">
          <h2 class="card-title">创建账号</h2>
          <p class="card-sub">注册一个新账号以开始使用</p>
          <el-form ref="registerRef" :model="registerForm" :rules="registerRules" class="register-form">
            <el-form-item v-if="tenantEnabled" prop="tenantId">
              <el-select v-model="registerForm.tenantId" filterable
                :placeholder="proxy.$t('register.selectPlaceholder')" style="width: 100%" size="large">
                <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName"
                  :value="item.tenantId">
                </el-option>
                <template #prefix><svg-icon icon-class="company" class="input-icon" /></template>
              </el-select>
            </el-form-item>
            <el-form-item prop="username">
              <el-input v-model="registerForm.username" type="text" size="large" auto-complete="off"
                :placeholder="proxy.$t('register.username')">
                <template #prefix><svg-icon icon-class="user" class="input-icon" /></template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" size="large" auto-complete="off"
                :placeholder="proxy.$t('register.password')" @keyup.enter="handleRegister">
                <template #prefix><svg-icon icon-class="password" class="input-icon" /></template>
              </el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" type="password" size="large" auto-complete="off"
                :placeholder="proxy.$t('register.confirmPassword')" @keyup.enter="handleRegister">
                <template #prefix><svg-icon icon-class="password" class="input-icon" /></template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="captchaEnabled" prop="code">
              <el-input v-model="registerForm.code" size="large" auto-complete="off"
                :placeholder="proxy.$t('register.code')" style="width: 63%" @keyup.enter="handleRegister">
                <template #prefix><svg-icon icon-class="validCode" class="input-icon" /></template>
              </el-input>
              <div class="register-code">
                <img :src="codeUrl" class="register-code-img" @click="getCode" />
              </div>
            </el-form-item>
            <el-form-item style="width: 100%; margin-bottom: 0">
              <el-button :loading="loading" size="large" type="primary" class="register-btn"
                @click.prevent="handleRegister">
                <span v-if="!loading">{{ proxy.$t('register.register') }}</span>
                <span v-else>{{ proxy.$t('register.registering') }}</span>
              </el-button>
            </el-form-item>
            <div class="form-footer">
              <router-link class="link-type" :to="'/login'">{{ proxy.$t('register.switchLoginPage') }}</router-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
    <div class="register-footer">
      <span>Copyright © 2026 华晟ERP订单管理系统</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, register, getTenantList } from '@/api/login';
import { RegisterForm, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { useI18n } from 'vue-i18n';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const title = import.meta.env.VITE_APP_TITLE;
const router = useRouter();

const { t } = useI18n();

const registerForm = ref<RegisterForm>({
  tenantId: '',
  username: '',
  password: '',
  confirmPassword: '',
  code: '',
  uuid: '',
  userType: 'sys_user'
});

// 租户开关
const tenantEnabled = ref(true);

const equalToPassword = (rule: any, value: string, callback: any) => {
  if (registerForm.value.password !== value) {
    callback(new Error(t('register.rule.confirmPassword.equalToPassword')));
  } else {
    callback();
  }
};

const registerRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: t('register.rule.tenantId.required') }],
  username: [
    { required: true, trigger: 'blur', message: t('register.rule.username.required') },
    { min: 2, max: 20, message: t('register.rule.username.length', { min: 2, max: 20 }), trigger: 'blur' }
  ],
  password: [
    { required: true, trigger: 'blur', message: t('register.rule.password.required') },
    { min: 5, max: 20, message: t('register.rule.password.length', { min: 5, max: 20 }), trigger: 'blur' },
    { pattern: /^[^<>"'|\\]+$/, message: t('register.rule.password.pattern', { strings: '< > " \' \\ |' }), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', message: t('register.rule.confirmPassword.required') },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ],
  code: [{ required: true, trigger: 'change', message: t('register.rule.code.required') }]
};
const codeUrl = ref('');
const loading = ref(false);
const captchaEnabled = ref(true);
const registerRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

const handleRegister = () => {
  registerRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      const [err] = await to(register(registerForm.value));
      if (!err) {
        const username = registerForm.value.username;
        await ElMessageBox.alert('<span style="color: red; ">' + t('register.registerSuccess', { username }) + '</font>', '系统提示', {
          app: undefined,
          dangerouslyUseHTMLString: true,
          type: 'success'
        });
        await router.push('/login');
      } else {
        loading.value = false;
        if (captchaEnabled.value) {
          getCode();
        }
      }
    }
  });
};

const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    registerForm.value.uuid = data.uuid;
  }
};

const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      registerForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

onMounted(() => {
  getCode();
  initTenantList();
});
</script>

<style lang="scss" scoped>
.register {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f0 50%, #dce3eb 100%);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -20%;
    width: 600px;
    height: 600px;
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(26, 115, 232, 0.06) 0%, rgba(26, 115, 232, 0.02) 100%);
    pointer-events: none;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: -30%;
    left: -10%;
    width: 400px;
    height: 400px;
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(66, 133, 244, 0.05) 0%, rgba(66, 133, 244, 0.02) 100%);
    pointer-events: none;
  }
}

.register-container {
  display: flex;
  width: 960px;
  min-height: 560px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  z-index: 1;
}

.register-left {
  flex: 0 0 420px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1a73e8 0%, #4285f4 50%, #5b9cf6 100%);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -60px;
    right: -60px;
    width: 200px;
    height: 200px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.06);
    pointer-events: none;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: -40px;
    left: -40px;
    width: 160px;
    height: 160px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.04);
    pointer-events: none;
  }
}

.brand-area {
  text-align: center;
  color: #fff;
  z-index: 1;
}

.brand-logo {
  width: 72px;
  height: 72px;
  margin: 0 auto 24px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
}

.logo-icon {
  width: 40px;
  height: 40px;
  color: #fff;
}

.brand-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 12px;
  letter-spacing: 2px;
}

.brand-desc {
  font-size: 14px;
  opacity: 0.85;
  margin: 0;
  letter-spacing: 1px;
}

.register-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px 40px;
}

.register-card {
  width: 100%;
  max-width: 360px;
}

.card-title {
  font-size: 24px;
  font-weight: 700;
  color: #1a1a2e;
  margin: 0 0 8px;
}

.card-sub {
  font-size: 14px;
  color: #909399;
  margin: 0 0 32px;
}

.register-form {
  .input-icon {
    height: 16px;
    width: 16px;
    color: #909399;
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 0 0 1px #e4e7ed inset;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
  }

  :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #1a73e8 inset;
  }

  :deep(.el-select .el-input__wrapper) {
    border-radius: 8px;
  }
}

.register-btn {
  width: 100%;
  height: 44px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 2px;
  background: linear-gradient(135deg, #1a73e8 0%, #4285f4 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(26, 115, 232, 0.3);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 6px 20px rgba(26, 115, 232, 0.4);
  }

  &:active {
    transform: translateY(0);
  }
}

.form-footer {
  text-align: center;
  margin-top: 20px;

  .link-type {
    font-size: 14px;
    color: #1a73e8;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

.register-code {
  width: calc(37% - 10px);
  height: 40px;
  float: right;
  margin-left: 10px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #e4e7ed;

  img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.register-footer {
  position: fixed;
  bottom: 24px;
  width: 100%;
  text-align: center;
  color: #909399;
  font-size: 12px;
  letter-spacing: 0.5px;
  z-index: 1;
}

@media (max-width: 1000px) {
  .register-container {
    width: 90vw;
    flex-direction: column;
    min-height: auto;
  }

  .register-left {
    flex: 0 0 auto;
    padding: 40px 20px;
  }

  .register-right {
    padding: 32px 24px;
  }

  .brand-logo {
    width: 56px;
    height: 56px;
    margin-bottom: 16px;
  }

  .brand-title {
    font-size: 22px;
  }
}
</style>
