<template>
  <div class="content">
    <img src="@/assets/img/Frame.svg" alt="" style="width: 480px; height: 480px; margin-right: 160px" />
    <a-space
      direction="vertical"
      size="large"
      style="width: 400px; height: 480px; background-color: #fff; border-radius: 8px; margin-top: 40px"
      align="center"
    >
      <img src="@/assets/img/LOGO.svg" alt="" style="width: 155px; height: 37px; margin-top: 49px" />
      <span style="font-size: 16px; color: #737478">AI营销工具</span>
      <a-form
        ref="formRef"
        :model="loginForm"
        :rules="formRules"
        auto-label-width
        style="width: 320px; margin-top: 20px"
      >
        <a-form-item field="username" hide-label>
          <a-input
            v-model="loginForm.username"
            placeholder="输入手机号"
            class="form-input"
            style="margin-top: 48px; border-radius: 8px"
            clearable
            @blur="validateField('username')"
            @input="clearError('username')"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="code" hide-label>
          <div
            class="form-input"
            style="display: flex; justify-content: space-between; align-items: center; border-radius: 8px"
          >
            <a-input
              v-model="loginForm.code"
              placeholder="验证码"
              style="background-color: #fff; border: none"
              @blur="validateField('code')"
              @input="clearError('code')"
              allow-clear
              maxlength="6"
            />
            <span
              style="
                font-size: 16px;
                font-weight: 400;
                text-align: center;
                margin-right: 16px;
                width: 120px;
                text-align: right;
              "
              :style="{
                color: countdown > 0 || hasGetCode ? '#6D4CFE' : '#211F24',
                cursor: countdown > 0 ? 'not-allowed' : 'pointer',
              }"
              @click="getCode"
              >{{ countdown > 0 ? `${countdown}s` : hasGetCode ? '重新发送' : '发送验证码' }}</span
            >
          </div>
        </a-form-item>
        <a-form-item hide-label>
          <div
            type="primary"
            style="
              width: 480px;
              height: 48px;
              font-size: 16px;
              border-radius: 8px;
              color: #fff;
              text-align: center;
              line-height: 48px;
            "
            :style="{ backgroundColor: isFormValid && hasCheck ? '#6D4CFE' : '#C5B7FF' }"
            @click="handleSubmit"
            :disabled="!isFormValid || !hasCheck"
          >
            {{ isLogin ? '登录' : '注册并开通企业账号' }}
          </div>
        </a-form-item>
      </a-form>
      <a-space style="margin-top: 16px; color: #737478; font-size: 12px">
        <a-checkbox v-model="hasCheck" style="margin-right: 0px; font-size: 12px"
          >{{ isLogin ? '登录' : '注册' }}即代表同意</a-checkbox
        >
        <a-link href="link" class="form-link" target="_blank">用户协议</a-link>
        <span>和</span>
        <a-link href="link" class="form-link" target="_blank">隐私政策</a-link>
      </a-space>
    </a-space>
  </div>
  <PuzzleVerification
    :show="isVerificationVisible"
    @submit="handleVerificationSubmit"
    @cancel="isVerificationVisible = false"
  />
  <a-modal :visible="visible" @ok="handleOk" @cancel="handleCancel" unmountOnClose hide-cancel>
    <template #title>
      <span style="text-align: left; width: 100%">选择账号</span>
    </template>
    <div class="account-bind-container">
      <a-card :bordered="false" class="bind-card">
        <div class="bind-header">
          <a-typography-text class="phone-number">{{ phoneNumber }} 已在以下企业绑定了账号</a-typography-text>
        </div>

        <a-list :bordered="false" :split="false" class="account-list">
          <a-list-item
            v-for="(account, index) in accounts"
            :key="index"
            class="account-item"
            :class="{ selected: selectedAccount === index }"
            @click="selectAccount(index)"
          >
            <a-list-item-meta>
              <template #title>
                <div style="display: flex; align-items: center; gap: 12px">
                  <a-checkbox :model-value="selectedAccount == index" />
                  <a-typography-text>{{ account.name }}</a-typography-text>
                </div>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </a-list>
      </a-card>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import PuzzleVerification from './PuzzleVerification.vue';
import { fetchLoginCaptCha } from '@/api/all/login';
import { ref, reactive, onUnmounted, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import router from '@/router';
const $message = Message;

const formRef = ref();
const countdown = ref(0);
let timer = ref();
const isLogin = ref(false);
const isVerificationVisible = ref(false);
const visible = ref(false);
const hasGetCode = ref(false);
const submitting = ref(false);
const hasCheck = ref(false);
const phoneNumber = ref('13616544933');
const selectedAccount = ref(0);

const accounts = ref([{ name: '灵机用户291094' }, { name: '灵机用户291094' }]);

const loginForm = reactive({
  username: '',
  code: '',
});

// 表单校验规则
const formRules = {
  username: [
    {
      required: true,
      message: '请填写手机号',
      trigger: ['blur', 'change'],
    },
    {
      validator: (value: string, callback: (error?: string) => void) => {
        if (!/^1[3-9]\d{9}$/.test(value)) {
          callback('手机号格式不正确');
        } else {
          callback();
        }
      },
      trigger: ['blur', 'change'],
    },
  ],
  code: [
    {
      required: true,
      message: '请填写验证码',
      trigger: ['blur', 'change'],
    },
    {
      validator: (value: string, callback: (error?: string) => void) => {
        if (!/^\d{6}$/.test(value)) {
          callback('验证码必须是6位数字');
        } else {
          callback();
        }
      },
      trigger: ['blur', 'change'],
    },
  ],
};

// 表单是否有效
const isFormValid = computed(() => {
  return (
    loginForm.username.trim() !== '' &&
    /^1[3-9]\d{9}$/.test(loginForm.username) &&
    loginForm.code.trim() !== '' &&
    /^\d{6}$/.test(loginForm.code)
  );
});

const selectAccount = (index: any) => {
  selectedAccount.value = index;
};

const validateField = (field: string) => {
  formRef.value.validateField(field);
};

const clearError = (field: string) => {
  formRef.value.clearValidate(field);
};

const handleOk = () => {
  visible.value = false;
};

const handleCancel = () => {
  visible.value = false;
};

const getCode = async () => {
  if (countdown.value > 0) return;

  // 先重置验证状态
  formRef.value.clearValidate('username');

  // 验证手机号字段
  try {
    const result = await formRef.value.validateField('username');
    // 只有当验证通过时才会显示滑块验证
    if (result === true || result === undefined) {
      isVerificationVisible.value = true;
    }
  } catch (error) {
    // 验证失败，错误信息会自动显示
    console.log('手机号验证失败:', error);
  }
};

// 验证码验证通过后
const handleVerificationSubmit = async () => {
  isVerificationVisible.value = false;
  startCountdown();

  try {
    await fetchLoginCaptCha({ mobile: loginForm.username });
    $message.success('验证码发送成功');
  } catch (error) {
    $message.error('验证码发送失败');
    // 重置倒计时
    countdown.value = 0;
    clearInterval(timer.value);
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 校验所有字段
    await formRef.value.validate();

    if (!hasCheck.value) {
      $message.error('请先勾选同意用户协议');
      return;
    }

    submitting.value = true;
    // 调用登录/注册API
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 处理登录成功逻辑
    $message.success(isLogin.value ? '登录成功' : '注册成功');
    router.replace({ path: '/dataEngine', replace: true });
  } catch (error) {
    // 错误信息会显示在输入框下方
  } finally {
    submitting.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  hasGetCode.value = true;
  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer.value as number);
      timer.value = null;
    }
  }, 1000);
};

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style scoped>
.content {
  background-image: url('@/assets/img/BG.svg');
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-size: cover;
  background-position: center;
  background-color: #f0edff;
}
.form-input {
  border: 1px solid #d7d7d9;
  background-color: #fff;
  border-radius: 4px;
  width: 320px;
  height: 48px;
  font-size: 14px;
  color: #333333;
}
.form-link {
  color: #211f24;
  font-size: 12px;
  margin: 0px;
}
:deep(.arco-space-item) {
  margin: 0px !important;
}

.account-bind-container {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
  display: flex;
}

.bind-card {
  background-color: var(--color-bg-2);
  width: 100%;
  flex-direction: column;
  align-items: start;
}

.bind-header {
  margin-bottom: 8px;
  text-align: left;
}

.phone-number {
  font-size: 14px;
  color: var(--color-text-4);
  text-align: left;
}

.account-list {
  margin-top: 16px;
}

.account-item {
  padding: 12px 16px;
  margin-bottom: 8px;
  background-color: var(--color-bg-2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
}

.account-item {
  padding: 12px 16px;
  margin-bottom: 8px;
  background-color: var(--color-bg-2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid var(--color-border-2);
  box-shadow: 0 2px 4px 0 #b1b2b5;
}

.account-item.selected {
  border-color: #6d4cfe;
  background-color: rgba(109, 76, 254, 0.1);
  box-shadow: 0 2px 4px 0 rgba(109, 76, 254, 0.5);
}

:deep(.arco-list-item-main) {
  padding: 0;
}

:deep(.arco-list-item-actions) {
  margin-left: 12px;
}

:deep(.arco-checkbox) {
  margin-right: 0;
}

:deep(.arco-checkbox-checked .arco-checkbox-mask) {
  background-color: #6d4cfe;
  border-color: #6d4cfe;
}
</style>
